diff --git a/.gitignore b/.gitignore index 8c20501..860ef11 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,7 @@ bin .envrc dist/ .idea +.pytest_cache +.DS_Store +*.pyc +__pycache__/ \ No newline at end of file diff --git a/.goreleaser.yaml b/.goreleaser.yaml index 3768e8d..7e53517 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -35,12 +35,12 @@ brews: commit_author: name: shipyard - email: hello@shipyard.build + email: hello@shipyard.khulnasoft.com commit_msg_template: "Brew formula update for {{ .ProjectName }} version {{ .Tag }}" folder: Formula - homepage: "https://shipyard.build" + homepage: "https://shipyard.khulnasoft.com" description: "A tool to manage Ephemeral Environments on the Shipyard platform" license: "Apache2" diff --git a/README.md b/README.md index 6b574dc..d691b9c 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ save your API token in a local config. You're ready to start running commands. Set your Shipyard API token as the value of the `SHIPYARD_API_TOKEN` environment variable. Or set it as the value for the `api_token` config key. -You can get it by going to [your profile page](https://shipyard.build/profile). +You can get it by going to [your profile page](https://shipyard.khulnasoft.com/profile). ### Set a Shipyard token @@ -35,7 +35,7 @@ You can get it by going to [your profile page](https://shipyard.build/profile). shipyard set token ``` -You can get in touch with us at [support@shipyard.build](mailto:support@shipyard.build) if you would like to enable API +You can get in touch with us at [support@shipyard.khulnasoft.com](mailto:support@shipyard.khulnasoft.com) if you would like to enable API access for your org. If you have any other questions, feel free to join our community [Slack](https://join.slack.com/t/shipyardcommunity/shared_invite/zt-x830cx39-BuiQKZwvhG7zGRTXAvojVQ). diff --git a/action.yml b/action.yml index 545e412..30db164 100644 --- a/action.yml +++ b/action.yml @@ -19,7 +19,7 @@ runs: with: python-version: '3.x' - name: Install Dependencies - run: pip install -r $GITHUB_ACTION_PATH/actions/src/requirements.txt > /dev/null + run: pip install -r $GITHUB_ACTION_PATH/src/requirements.txt > /dev/null shell: bash # Pass inputs via shell until https://github.com/actions/runner/issues/665 resolved - name: Pass Inputs to Shell @@ -29,7 +29,7 @@ runs: echo "INPUT_APP_NAME=${{ inputs.app-name }}" >> $GITHUB_ENV shell: bash - name: Authenticate into Shipyard - run: python $GITHUB_ACTION_PATH/actions/src/fetch_shipyard_env.py + run: python $GITHUB_ACTION_PATH/src/fetch_shipyard_env.py shell: bash branding: icon: git-pull-request diff --git a/actions/.gitignore b/actions/.gitignore deleted file mode 100644 index 14b891d..0000000 --- a/actions/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.pytest_cache -.DS_Store -*.pyc -__pycache__/ \ No newline at end of file diff --git a/actions/LICENSE b/actions/LICENSE deleted file mode 100644 index 3ee6017..0000000 --- a/actions/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2022 Shipyard - -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/actions/README.md b/actions/README.md deleted file mode 100644 index 31107ed..0000000 --- a/actions/README.md +++ /dev/null @@ -1,84 +0,0 @@ -# Shipyard Github Action - -[![GitHub License](https://img.shields.io/badge/license-MIT-lightgrey.svg)](https://raw.githubusercontent.com/shipyard/github-action/master/LICENSE) [![Github Action Community](https://img.shields.io/badge/community-Github%20Actions%20Discuss-343434.svg)](https://github.community/c/github-ecosystem/github-apps/64) - -Use Github Action to run jobs on ephemeral environments automatically deployed by Shipyard, authenticating into them via a bypass token. -This job connects with Shipyard during a Github Action job, fetching necessary environment variables in order to run e2e tests where authentication via OAuth is normally required. - -## How to use - -In your Github Workflow file located in `.github/workflows/`, you can use the Shipyard's Github Action as per the following example: - -``` -on: [pull_request] - -jobs: - cypress-e2e-tests: - runs-on: ubuntu-latest - name: Collect the bypass token and URL for an authenticated ephemeral environment attached to this PR in order to run e2e tests on it. - steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Fetch Shipyard Tokens - uses: shipyard/github-action/fetch-shipyard-env@1.0.0 - env: - SHIPYARD_API_TOKEN: ${{ secrets.SHIPYARD_API_TOKEN }} - - name: Run the e2e tests on the ephemeral environment - run: npm run test - shell: bash - env: - CYPRESS_BASE_URL: $SHIPYARD_ENVIRONMENT_URL - CYPRESS_BYPASS_TOKEN: $SHIPYARD_BYPASS_TOKEN - -``` - -The Github Action can be configured by passing inputs or environment variables: - -**Inputs** -``` - - name: Fetch Shipyard Tokens - uses: shipyard/github-action/fetch-shipyard-env@1.0.0 - with: - api-token: ${{ secrets.SHIPYARD_API_TOKEN }} - timeout-minutes: 30 -``` - -| Input name | Description | Default Value | -| --------------- | --------------- |--------------- | -| `api-token` | Token required to connect to Shipyard's APIs. Can be obtained from your Organization's setting page | -| -| `timeout-minutes` | Number of minutes to wait for Shipyard environment before timing out. | 60| -| `app-name` | Filter the environments by name of the application on the Shipyard app. | -| - - -**Environment Variables** -``` - - name: Fetch Shipyard Tokens - uses: shipyard/github-action/fetch-shipyard-env@1.0.0 - env: - SHIPYARD_API_TOKEN: ${{ secrets.SHIPYARD_API_TOKEN }} - SHIPYARD_TIMEOUT: 30 - INPUT_APP_NAME: 'react-app' -``` - -| Environment Variable | Description | Default Value | -| --------------- | --------------- |--------------- | -| `SHIPYARD_API_TOKEN` | Token required to connect to Shipyard's APIs. Can be obtained from your Organization's setting page |-| -| `SHIPYARD_TIMEOUT` | Number of minutes to wait for Shipyard environment before timing out. |60| -| `SHIPYARD_APP_NAME` | Filter the environments by name of the application on the Shipyard app. |-| - -**NOTE**: Inputs are given precedence over environment variables. - -If input `api-token` or environment variable `SHIPYARD_API_TOKEN` is not provided, error is raised. - -On successful run, the following environment variables are set, which can then be passed on to other actions in the same workflow. - -| Parameter Name | Description | -| --------------- | --------------- | -|`SHIPYARD_ENVIRONMENT_URL` | URL of the ephemeral environment | -|`SHIPYARD_ENVIRONMENT_ID` | ID of the ephemeral environment | -|`SHIPYARD_BYPASS_TOKEN` | Token to bypass authentication | - - -## Resources - -[Shipyard Documentation](https://docs.shipyard.build/docs/) \ No newline at end of file diff --git a/actions/action/LICENSE b/actions/action/LICENSE deleted file mode 100644 index 3ee6017..0000000 --- a/actions/action/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2022 Shipyard - -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/actions/action/README.md b/actions/action/README.md deleted file mode 100644 index d4838be..0000000 --- a/actions/action/README.md +++ /dev/null @@ -1,92 +0,0 @@ -# Integrate Shipyard - -[![GitHub License](https://img.shields.io/badge/license-MIT-lightgrey.svg)](https://raw.githubusercontent.com/shipyard/github-action/master/LICENSE) [![Github Action Community](https://img.shields.io/badge/community-Github%20Actions%20Discuss-343434.svg)](https://github.community/c/github-ecosystem/github-apps/64) - -Securely authenticate into [Shipyard](https://shipyard.build)-generated environments to test before merge by running E2E tests against an ephemeral environment on every commit. - -This action connects to Shipyard using your **API token** and fetches the environment variables necessary to test against your existing environments within your [GitHub Actions](https://docs.github.com/en/actions) workflow. - -## Setup -- Obtain your API token from your Shipyard **Org Settings** page - - -- Create a new GitHub repository secret named `SHIPYARD_API_TOKEN` -- Open a PR on your Shipyard-enabled app - -## How to use - -In your GitHub workflow file located in `.github/workflows/`, you can use the **Shipyard GitHub Action** as per the following example: - -``` -on: [pull_request] - -jobs: - cypress-e2e-tests: - runs-on: ubuntu-latest - name: Auth into Shipyard and run Cypress E2E tests against ephemeral environments - steps: - - name: Checkout - uses: actions/checkout@v3 - - name: Integrate Shipyard - uses: shipyard/shipyard-action@1.0.0 - env: - SHIPYARD_API_TOKEN: ${{ secrets.SHIPYARD_API_TOKEN }} - - name: Run E2E tests against the ephemeral environment - run: npm run test - shell: bash - env: - CYPRESS_BASE_URL: $SHIPYARD_ENVIRONMENT_URL - CYPRESS_BYPASS_TOKEN: $SHIPYARD_BYPASS_TOKEN - -``` - -This action can be configured by passing inputs or environment variables: - -**Inputs** -``` - - name: Integrate Shipyard - uses: shipyard/shipyard-action@1.0.0 - with: - api-token: ${{ secrets.SHIPYARD_API_TOKEN }} - timeout-minutes: 30 -``` - -| Input name | Description | Default Value | -| --------------- | --------------- |--------------- | -| `api-token` | Token required to connect to Shipyard's APIs. Can be obtained from your Shipyard **Org Settings** page | -| -| `timeout-minutes` | Number of minutes to wait for Shipyard environment before timing out. | 60| -| `app-name` | Filter the environments by name of the application on the Shipyard app. | -| - - -**Environment Variables** -``` - - name: Integrate Shipyard - uses: shipyard/shipyard-action@1.0.0 - env: - SHIPYARD_API_TOKEN: ${{ secrets.SHIPYARD_API_TOKEN }} - SHIPYARD_TIMEOUT: 30 - INPUT_APP_NAME: 'react-app' -``` - -| Environment Variable | Description | Default Value | -| --------------- | --------------- |--------------- | -| `SHIPYARD_API_TOKEN` | Token required to connect to Shipyard's APIs. Can be obtained from your Shipyard **Org Settings** page |-| -| `SHIPYARD_TIMEOUT` | Number of minutes to wait for Shipyard environment before timing out. |60| -| `SHIPYARD_APP_NAME` | Filter the environments by name of the application on the Shipyard app. |-| - -**NOTE**: Inputs are given precedence over environment variables. - -If input `api-token` or environment variable `SHIPYARD_API_TOKEN` is not provided, error is raised. - -On a successful run, the following environment variables are set, which can then be passed on to other actions in the same workflow: - -| Parameter Name | Description | -| --------------- | --------------- | -|`SHIPYARD_ENVIRONMENT_URL` | URL of the ephemeral environment | -|`SHIPYARD_ENVIRONMENT_ID` | ID of the ephemeral environment | -|`SHIPYARD_BYPASS_TOKEN` | Token to bypass authentication | - - -## Resources - -[Shipyard Documentation](https://docs.shipyard.build/docs/) diff --git a/actions/src/fetch_shipyard_env.py b/actions/src/fetch_shipyard_env.py deleted file mode 100644 index 2c8dea5..0000000 --- a/actions/src/fetch_shipyard_env.py +++ /dev/null @@ -1,213 +0,0 @@ -""" -# Purpose: -Wait for the Shipyard environment to be ready, -then put its data in the environment. -# Required environment variables: -- GITHUB_ENV -- GITHUB_REPOSITORY -- GITHUB_REF_NAME -- INPUT_API_TOKEN or SHIPYARD_API_TOKEN -- INPUT_TIMEOUT_MINUTES or SHIPYARD_TIMEOUT -- INPUT_APP_NAME or SHIPYARD_APP_NAME -""" -from __future__ import print_function - -import os -import sys -import time -from datetime import datetime, timedelta - -import swagger_client -from swagger_client.rest import ApiException - - -def exit(msg): - print(msg) - sys.exit(1) - - -# Make sure there's a bash env file in the environment -bash_env_path = os.environ.get("GITHUB_ENV") -if not bash_env_path: - exit("ERROR: missing GITHUB_ENV environment variable") - -# Constants -repo_owner = os.environ.get("GITHUB_REPOSITORY_OWNER") -github_repo = os.environ.get("GITHUB_REPOSITORY") # repo_owner/repo -repo = github_repo.replace(f"{repo_owner}/", "") if github_repo else None -# GITHUB_HEAD_REF - The head ref or source branch of the pull request in a workflow run -branch = os.environ.get("GITHUB_HEAD_REF") -if not branch: - # GITHUB_REF_NAME - The branch or tag name that triggered the workflow run - branch = os.environ.get("GITHUB_REF_NAME") -ref_type = os.environ.get("GITHUB_REF_TYPE") # TODO: handle branch or tag? - -# Get auth token -api_token = os.environ.get("INPUT_API_TOKEN") -# if input is not provided, check ENV vars -if not api_token: - api_token = os.environ.get("SHIPYARD_API_TOKEN") -if not api_token: - exit("No SHIPYARD_API_TOKEN provided, exiting.") - -# Get the timeout -timeout_minutes = os.environ.get("INPUT_TIMEOUT_MINUTES") -if not timeout_minutes: - timeout_minutes = os.environ.get("SHIPYARD_TIMEOUT") -if timeout_minutes: - try: - timeout_minutes = int(timeout_minutes) - except Exception: - exit( - 'ERROR: the SHIPYARD_TIMEOUT provided ("{}") is not an integer'.format( - timeout_minutes - ) - ) -else: - timeout_minutes = 60 - -# Get the app name -app_name = os.environ.get("INPUT_APP_NAME") -if not app_name: - app_name = os.environ.get("SHIPYARD_APP_NAME") - -# Prepare API client -configuration = swagger_client.Configuration() -configuration.api_key["x-api-token"] = api_token -client = swagger_client.ApiClient(configuration) -api_instance = swagger_client.EnvironmentApi(client) - - -def fetch_shipyard_environment(): - """Fetch the Shipyard environment for this Github job""" - - # Hit the Shipyard API - try: - args = { - "repo_owner": repo_owner, - "repo_name": repo, - "branch": branch - } - if app_name: - args["name"] = app_name - response = api_instance.list_environments(**args).to_dict() - except ApiException as e: - exit("ERROR: issue while listing environments via API: {}".format(e)) - - # Exit if any errors - errors = response.get("errors") - if errors: - exit("ERROR: {}".format(errors[0]["title"])) - - # Verify an environment was found - if not len(response["data"]): - exit("ERROR: no matching Shipyard environment found") - - # Verify the data is where we expect - try: - environment_id = response["data"][0]["id"] - environment_data = response["data"][0]["attributes"] - except Exception: - exit("ERROR: invalid response data structure") - - # Verify all the needed fields are available - for param in ("bypass_token", "url", "ready", "stopped", "retired"): - if param not in environment_data: - exit("ERROR: no {} found!".format(param)) - - return environment_id, environment_data - - -def restart_environment(environment_id): - """Restart the Shipyard environment with the provided ID""" - - try: - api_instance.restart_environment(environment_id) - except ApiException as e: - exit("ERROR: issue while restart the environment: {}".format(e)) - - -def wait_for_environment(): - """Return the Shipyard environment data once it's ready""" - - auto_restart = True - was_restarted = False - - # Check the environment - environment_id, environment_data = fetch_shipyard_environment() - - start = datetime.now() - timeout_end = datetime.now() + timedelta(minutes=timeout_minutes) - - # Until the environment is ready - while not environment_data["ready"]: - now = datetime.now() - # Check if the timeout has elapsed - if datetime.now() > timeout_end: - exit("{} minute timeout elapsed, exiting!".format(timeout_minutes)) - - # Auto-restart the environment once if indicated - if all([environment_data["retired"], auto_restart, not was_restarted]): - restart_environment(environment_id) - was_restarted = True - print("Restarted Shipyard environment...") - elif environment_data["stopped"] and not environment_data["processing"]: - exit("ERROR: this environment is stopped and no builds are processing") - - # Wait 15 seconds - seconds_waited = int((now - start).total_seconds()) - wait_string = " ({}s elapsed)".format(seconds_waited) if seconds_waited else "" - print("Waiting for Shipyard environment...{}".format(wait_string)) - time.sleep(15) - - # Check on the environment again - environment_id, environment_data = fetch_shipyard_environment() - - return environment_id, environment_data - - -def main(): - """ - Wait for the Shipyard environment to be ready, - then put it's data in the bash environment. - """ - - environment_id, environment_data = wait_for_environment() - - try: - # Try to fetch the commit hash of classic environments - commit_hash = environment_data.get("commit_hash") - - # Fetch the commit hash if this is a single-repo app - if not commit_hash: - projects = environment_data.get("projects") - if len(projects) == 1: - commit_hash = projects[0]["commit_hash"] - except Exception: - print("WARNING: unable to retrieve commit hash") - commit_hash = None - - # Write the data to the job's environment - with open(bash_env_path, "a") as bash_env: - bash_env.write( - "\n".join( - [ - "SHIPYARD_BYPASS_TOKEN={}".format(environment_data["bypass_token"]), - "SHIPYARD_ENVIRONMENT_ID={}".format(environment_id), - "SHIPYARD_ENVIRONMENT_URL={}".format(environment_data["url"]), - "SHIPYARD_ENVIRONMENT_READY={}".format(environment_data["ready"]), - "SHIPYARD_ENVIRONMENT_RETIRED={}".format( - environment_data["retired"] - ), - ] - + ["SHIPYARD_ENVIRONMENT_COMMIT_HASH={}".format(commit_hash)] - if commit_hash - else [] - ) - ) - - print("Shipyard environment data written to {}!".format(bash_env_path)) - - -if __name__ == "__main__": - main() diff --git a/actions/src/requirements.txt b/actions/src/requirements.txt deleted file mode 100644 index bafdc07..0000000 --- a/actions/src/requirements.txt +++ /dev/null @@ -1,5 +0,0 @@ -certifi >= 14.05.14 -six >= 1.10 -python_dateutil >= 2.5.3 -setuptools >= 21.0.0 -urllib3 >= 1.15.1 diff --git a/actions/src/swagger_client/__init__.py b/actions/src/swagger_client/__init__.py deleted file mode 100644 index 5d459fa..0000000 --- a/actions/src/swagger_client/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# coding: utf-8 - -# flake8: noqa - -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -from __future__ import absolute_import - -# import apis into sdk package -from swagger_client.api.environment_api import EnvironmentApi - -# import ApiClient -from swagger_client.api_client import ApiClient -from swagger_client.configuration import Configuration - -# import models into sdk package -from swagger_client.models.inline_response200 import InlineResponse200 -from swagger_client.models.inline_response2001 import InlineResponse2001 -from swagger_client.models.inline_response2001_data import InlineResponse2001Data -from swagger_client.models.inline_response2001_data_attributes import ( - InlineResponse2001DataAttributes, -) -from swagger_client.models.inline_response2001_data_attributes_projects import ( - InlineResponse2001DataAttributesProjects, -) -from swagger_client.models.inline_response2001_data_links import ( - InlineResponse2001DataLinks, -) diff --git a/actions/src/swagger_client/api/__init__.py b/actions/src/swagger_client/api/__init__.py deleted file mode 100644 index 8e65c7b..0000000 --- a/actions/src/swagger_client/api/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -from __future__ import absolute_import - -# flake8: noqa - -# import apis into api package -from swagger_client.api.environment_api import EnvironmentApi diff --git a/actions/src/swagger_client/api/environment_api.py b/actions/src/swagger_client/api/environment_api.py deleted file mode 100644 index db47341..0000000 --- a/actions/src/swagger_client/api/environment_api.py +++ /dev/null @@ -1,433 +0,0 @@ -# coding: utf-8 - -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -from __future__ import absolute_import - -import re # noqa: F401 - -# python 2 and python 3 compatibility library -import six - -from swagger_client.api_client import ApiClient - - -class EnvironmentApi(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - Ref: https://github.com/swagger-api/swagger-codegen - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient() - self.api_client = api_client - - def get_environment(self, uuid, **kwargs): # noqa: E501 - """Get an environment # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.get_environment(uuid, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str uuid: the environment's identifying UUID (required) - :return: InlineResponse2001 - If the method is called asynchronously, - returns the request thread. - """ - kwargs["_return_http_data_only"] = True - if kwargs.get("async_req"): - return self.get_environment_with_http_info(uuid, **kwargs) # noqa: E501 - else: - (data) = self.get_environment_with_http_info(uuid, **kwargs) # noqa: E501 - return data - - def get_environment_with_http_info(self, uuid, **kwargs): # noqa: E501 - """Get an environment # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.get_environment_with_http_info(uuid, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str uuid: the environment's identifying UUID (required) - :return: InlineResponse2001 - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ["uuid"] # noqa: E501 - all_params.append("async_req") - all_params.append("_return_http_data_only") - all_params.append("_preload_content") - all_params.append("_request_timeout") - - params = locals() - for key, val in six.iteritems(params["kwargs"]): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method get_environment" % key - ) - params[key] = val - del params["kwargs"] - # verify the required parameter 'uuid' is set - if "uuid" not in params or params["uuid"] is None: - raise ValueError( - "Missing the required parameter `uuid` when calling `get_environment`" - ) # noqa: E501 - - collection_formats = {} - - path_params = {} - if "uuid" in params: - path_params["uuid"] = params["uuid"] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params["Accept"] = self.api_client.select_header_accept( - ["application/json"] - ) # noqa: E501 - - # Authentication setting - auth_settings = ["ApiKeyAuth"] # noqa: E501 - - return self.api_client.call_api( - "/api/v1/environment/{uuid}", - "GET", - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type="InlineResponse2001", # noqa: E501 - auth_settings=auth_settings, - async_req=params.get("async_req"), - _return_http_data_only=params.get("_return_http_data_only"), - _preload_content=params.get("_preload_content", True), - _request_timeout=params.get("_request_timeout"), - collection_formats=collection_formats, - ) - - def list_environments(self, **kwargs): # noqa: E501 - """List your organization's environments # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.list_environments(async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str name: - :param str repo_owner: - :param str repo_name: - :param str branch: - :param int pull_request_number: - :param str branch: - :return: InlineResponse200 - If the method is called asynchronously, - returns the request thread. - """ - kwargs["_return_http_data_only"] = True - if kwargs.get("async_req"): - return self.list_environments_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.list_environments_with_http_info(**kwargs) # noqa: E501 - return data - - def list_environments_with_http_info(self, **kwargs): # noqa: E501 - """List your organization's environments # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.list_environments_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str name: - :param str repo_owner: - :param str repo_name: - :param str branch: - :param int pull_request_number: - :return: InlineResponse200 - If the method is called asynchronously, - returns the request thread. - """ - - all_params = [ - "name", - "repo_owner", - "repo_name", - "branch", - "pull_request_number", - ] # noqa: E501 - all_params.append("async_req") - all_params.append("_return_http_data_only") - all_params.append("_preload_content") - all_params.append("_request_timeout") - - params = locals() - for key, val in six.iteritems(params["kwargs"]): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method list_environments" % key - ) - params[key] = val - del params["kwargs"] - - collection_formats = {} - - path_params = {} - - query_params = [] - if "name" in params: - query_params.append(("name", params["name"])) # noqa: E501 - if "repo_owner" in params: - query_params.append(("repo_owner", params["repo_owner"])) # noqa: E501 - if "repo_name" in params: - query_params.append(("repo_name", params["repo_name"])) # noqa: E501 - if "branch" in params: - query_params.append(("branch", params["branch"])) # noqa: E501 - if "pull_request_number" in params: - query_params.append( - ("pull_request_number", params["pull_request_number"]) - ) # noqa: E501 - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params["Accept"] = self.api_client.select_header_accept( - ["application/json"] - ) # noqa: E501 - - # Authentication setting - auth_settings = ["ApiKeyAuth"] # noqa: E501 - - return self.api_client.call_api( - "/api/v1/environment", - "GET", - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type="InlineResponse200", # noqa: E501 - auth_settings=auth_settings, - async_req=params.get("async_req"), - _return_http_data_only=params.get("_return_http_data_only"), - _preload_content=params.get("_preload_content", True), - _request_timeout=params.get("_request_timeout"), - collection_formats=collection_formats, - ) - - def restart_environment(self, uuid, **kwargs): # noqa: E501 - """Restart an environment # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.restart_environment(uuid, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str uuid: the environments's identifying UUID (required) - :return: None - If the method is called asynchronously, - returns the request thread. - """ - kwargs["_return_http_data_only"] = True - if kwargs.get("async_req"): - return self.restart_environment_with_http_info(uuid, **kwargs) # noqa: E501 - else: - (data) = self.restart_environment_with_http_info( - uuid, **kwargs - ) # noqa: E501 - return data - - def restart_environment_with_http_info(self, uuid, **kwargs): # noqa: E501 - """Restart an environment # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.restart_environment_with_http_info(uuid, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str uuid: the environments's identifying UUID (required) - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ["uuid"] # noqa: E501 - all_params.append("async_req") - all_params.append("_return_http_data_only") - all_params.append("_preload_content") - all_params.append("_request_timeout") - - params = locals() - for key, val in six.iteritems(params["kwargs"]): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method restart_environment" % key - ) - params[key] = val - del params["kwargs"] - # verify the required parameter 'uuid' is set - if "uuid" not in params or params["uuid"] is None: - raise ValueError( - "Missing the required parameter `uuid` when calling `restart_environment`" - ) # noqa: E501 - - collection_formats = {} - - path_params = {} - if "uuid" in params: - path_params["uuid"] = params["uuid"] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # Authentication setting - auth_settings = ["ApiKeyAuth"] # noqa: E501 - - return self.api_client.call_api( - "/api/v1/environment/{uuid}/restart", - "POST", - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, # noqa: E501 - auth_settings=auth_settings, - async_req=params.get("async_req"), - _return_http_data_only=params.get("_return_http_data_only"), - _preload_content=params.get("_preload_content", True), - _request_timeout=params.get("_request_timeout"), - collection_formats=collection_formats, - ) - - def stop_environment(self, uuid, **kwargs): # noqa: E501 - """Stop an environment # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.stop_environment(uuid, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str uuid: the environments's identifying UUID (required) - :return: None - If the method is called asynchronously, - returns the request thread. - """ - kwargs["_return_http_data_only"] = True - if kwargs.get("async_req"): - return self.stop_environment_with_http_info(uuid, **kwargs) # noqa: E501 - else: - (data) = self.stop_environment_with_http_info(uuid, **kwargs) # noqa: E501 - return data - - def stop_environment_with_http_info(self, uuid, **kwargs): # noqa: E501 - """Stop an environment # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.stop_environment_with_http_info(uuid, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str uuid: the environments's identifying UUID (required) - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ["uuid"] # noqa: E501 - all_params.append("async_req") - all_params.append("_return_http_data_only") - all_params.append("_preload_content") - all_params.append("_request_timeout") - - params = locals() - for key, val in six.iteritems(params["kwargs"]): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method stop_environment" % key - ) - params[key] = val - del params["kwargs"] - # verify the required parameter 'uuid' is set - if "uuid" not in params or params["uuid"] is None: - raise ValueError( - "Missing the required parameter `uuid` when calling `stop_environment`" - ) # noqa: E501 - - collection_formats = {} - - path_params = {} - if "uuid" in params: - path_params["uuid"] = params["uuid"] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # Authentication setting - auth_settings = ["ApiKeyAuth"] # noqa: E501 - - return self.api_client.call_api( - "/api/v1/environment/{uuid}/stop", - "POST", - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, # noqa: E501 - auth_settings=auth_settings, - async_req=params.get("async_req"), - _return_http_data_only=params.get("_return_http_data_only"), - _preload_content=params.get("_preload_content", True), - _request_timeout=params.get("_request_timeout"), - collection_formats=collection_formats, - ) diff --git a/actions/src/swagger_client/api_client.py b/actions/src/swagger_client/api_client.py deleted file mode 100644 index f0c5911..0000000 --- a/actions/src/swagger_client/api_client.py +++ /dev/null @@ -1,705 +0,0 @@ -# coding: utf-8 -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" -from __future__ import absolute_import - -import datetime -import json -import mimetypes -from multiprocessing.pool import ThreadPool -import os -import re -import tempfile - -# python 2 and python 3 compatibility library -import six -from six.moves.urllib.parse import quote - -from swagger_client.configuration import Configuration -import swagger_client.models -from swagger_client import rest - - -class ApiClient(object): - """Generic API client for Swagger client library builds. - - Swagger generic API client. This client handles the client- - server communication, and is invariant across implementations. Specifics of - the methods and models for each application are generated from the Swagger - templates. - - NOTE: This class is auto generated by the swagger code generator program. - Ref: https://github.com/swagger-api/swagger-codegen - Do not edit the class manually. - - :param configuration: .Configuration object for this client - :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to - the API. - :param cookie: a cookie to include in the header when making calls - to the API - """ - - PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types - NATIVE_TYPES_MAPPING = { - "int": int, - "long": int if six.PY3 else long, # noqa: F821 - "float": float, - "str": str, - "bool": bool, - "date": datetime.date, - "datetime": datetime.datetime, - "object": object, - } - - def __init__( - self, configuration=None, header_name=None, header_value=None, cookie=None - ): - if configuration is None: - configuration = Configuration() - self.configuration = configuration - - self.pool = ThreadPool() - self.rest_client = rest.RESTClientObject(configuration) - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.cookie = cookie - # Set default User-Agent. - self.user_agent = "Swagger-Codegen/1.0.0/python" - - def __del__(self): - self.pool.close() - self.pool.join() - - @property - def user_agent(self): - """User agent for this API client""" - return self.default_headers["User-Agent"] - - @user_agent.setter - def user_agent(self, value): - self.default_headers["User-Agent"] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - def __call_api( - self, - resource_path, - method, - path_params=None, - query_params=None, - header_params=None, - body=None, - post_params=None, - files=None, - response_type=None, - auth_settings=None, - _return_http_data_only=None, - collection_formats=None, - _preload_content=True, - _request_timeout=None, - ): - - config = self.configuration - - # header parameters - header_params = header_params or {} - header_params.update(self.default_headers) - if self.cookie: - header_params["Cookie"] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - header_params = dict( - self.parameters_to_tuples(header_params, collection_formats) - ) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, collection_formats) - for k, v in path_params: - # specified safe chars, encode everything - resource_path = resource_path.replace( - "{%s}" % k, quote(str(v), safe=config.safe_chars_for_path_param) - ) - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = self.parameters_to_tuples(query_params, collection_formats) - - # post parameters - if post_params or files: - post_params = self.prepare_post_parameters(post_params, files) - post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, collection_formats) - - # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings) - - # body - if body: - body = self.sanitize_for_serialization(body) - - # request url - url = self.configuration.host + resource_path - - # perform request and return response - response_data = self.request( - method, - url, - query_params=query_params, - headers=header_params, - post_params=post_params, - body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - ) - - self.last_response = response_data - - return_data = response_data - if _preload_content: - # deserialize response data - if response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None - - if _return_http_data_only: - return return_data - else: - return (return_data, response_data.status, response_data.getheaders()) - - def sanitize_for_serialization(self, obj): - """Builds a JSON POST object. - - If obj is None, return None. - If obj is str, int, long, float, bool, return directly. - If obj is datetime.datetime, datetime.date - convert to string in iso8601 format. - If obj is list, sanitize each element in the list. - If obj is dict, return the dict. - If obj is swagger model, return the properties dict. - - :param obj: The data to serialize. - :return: The serialized form of data. - """ - if obj is None: - return None - elif isinstance(obj, self.PRIMITIVE_TYPES): - return obj - elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] - elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj) - elif isinstance(obj, (datetime.datetime, datetime.date)): - return obj.isoformat() - - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `swagger_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = { - obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in six.iteritems(obj.swagger_types) - if getattr(obj, attr) is not None - } - - return { - key: self.sanitize_for_serialization(val) - for key, val in six.iteritems(obj_dict) - } - - def deserialize(self, response, response_type): - """Deserializes response into an object. - - :param response: RESTResponse object to be deserialized. - :param response_type: class literal for - deserialized object, or string of class name. - - :return: deserialized object. - """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) - - # fetch data from response object - try: - data = json.loads(response.data) - except ValueError: - data = response.data - - return self.__deserialize(data, response_type) - - def __deserialize(self, data, klass): - """Deserializes dict, list, str into an object. - - :param data: dict, list or str. - :param klass: class literal, or string of class name. - - :return: object. - """ - if data is None: - return None - - if type(klass) == str: - if klass.startswith("list["): - sub_kls = re.match(r"list\[(.*)\]", klass).group(1) - return [self.__deserialize(sub_data, sub_kls) for sub_data in data] - - if klass.startswith("dict("): - sub_kls = re.match(r"dict\(([^,]*), (.*)\)", klass).group(2) - return { - k: self.__deserialize(v, sub_kls) for k, v in six.iteritems(data) - } - - # convert str to class - if klass in self.NATIVE_TYPES_MAPPING: - klass = self.NATIVE_TYPES_MAPPING[klass] - else: - klass = getattr(swagger_client.models, klass) - - if klass in self.PRIMITIVE_TYPES: - return self.__deserialize_primitive(data, klass) - elif klass == object: - return self.__deserialize_object(data) - elif klass == datetime.date: - return self.__deserialize_date(data) - elif klass == datetime.datetime: - return self.__deserialize_datatime(data) - else: - return self.__deserialize_model(data, klass) - - def call_api( - self, - resource_path, - method, - path_params=None, - query_params=None, - header_params=None, - body=None, - post_params=None, - files=None, - response_type=None, - auth_settings=None, - async_req=None, - _return_http_data_only=None, - collection_formats=None, - _preload_content=True, - _request_timeout=None, - ): - """Makes the HTTP request (synchronous) and returns deserialized data. - - To make an async request, set the async_req parameter. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. - :param async_req bool: execute request asynchronously - :param _return_http_data_only: response data without head status code - and headers - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: - If async_req parameter is True, - the request will be called asynchronously. - The method will return the request thread. - If parameter async_req is False or missing, - then the method will return the response directly. - """ - if not async_req: - return self.__call_api( - resource_path, - method, - path_params, - query_params, - header_params, - body, - post_params, - files, - response_type, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - ) - else: - thread = self.pool.apply_async( - self.__call_api, - ( - resource_path, - method, - path_params, - query_params, - header_params, - body, - post_params, - files, - response_type, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - ), - ) - return thread - - def request( - self, - method, - url, - query_params=None, - headers=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return self.rest_client.GET( - url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers, - ) - elif method == "HEAD": - return self.rest_client.HEAD( - url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers, - ) - elif method == "OPTIONS": - return self.rest_client.OPTIONS( - url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - elif method == "POST": - return self.rest_client.POST( - url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - elif method == "PUT": - return self.rest_client.PUT( - url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - elif method == "PATCH": - return self.rest_client.PATCH( - url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - elif method == "DELETE": - return self.rest_client.DELETE( - url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - else: - raise ValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - - def parameters_to_tuples(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. - - :param params: Parameters as dict or list of two-tuples - :param dict collection_formats: Parameter collection formats - :return: Parameters as list of tuples, collections formatted - """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in ( - six.iteritems(params) if isinstance(params, dict) else params - ): # noqa: E501 - if k in collection_formats: - collection_format = collection_formats[k] - if collection_format == "multi": - new_params.extend((k, value) for value in v) - else: - if collection_format == "ssv": - delimiter = " " - elif collection_format == "tsv": - delimiter = "\t" - elif collection_format == "pipes": - delimiter = "|" - else: # csv is the default - delimiter = "," - new_params.append((k, delimiter.join(str(value) for value in v))) - else: - new_params.append((k, v)) - return new_params - - def prepare_post_parameters(self, post_params=None, files=None): - """Builds form parameters. - - :param post_params: Normal form parameters. - :param files: File parameters. - :return: Form parameters with files. - """ - params = [] - - if post_params: - params = post_params - - if files: - for k, v in six.iteritems(files): - if not v: - continue - file_names = v if type(v) is list else [v] - for n in file_names: - with open(n, "rb") as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = ( - mimetypes.guess_type(filename)[0] - or "application/octet-stream" - ) - params.append(tuple([k, tuple([filename, filedata, mimetype])])) - - return params - - def select_header_accept(self, accepts): - """Returns `Accept` based on an array of accepts provided. - - :param accepts: List of headers. - :return: Accept (e.g. application/json). - """ - if not accepts: - return - - accepts = [x.lower() for x in accepts] - - if "application/json" in accepts: - return "application/json" - else: - return ", ".join(accepts) - - def select_header_content_type(self, content_types): - """Returns `Content-Type` based on an array of content_types provided. - - :param content_types: List of content-types. - :return: Content-Type (e.g. application/json). - """ - if not content_types: - return "application/json" - - content_types = [x.lower() for x in content_types] - - if "application/json" in content_types or "*/*" in content_types: - return "application/json" - else: - return content_types[0] - - def update_params_for_auth(self, headers, querys, auth_settings): - """Updates header and query params based on authentication setting. - - :param headers: Header parameters dict to be updated. - :param querys: Query parameters tuple list to be updated. - :param auth_settings: Authentication setting identifiers list. - """ - if not auth_settings: - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - if not auth_setting["value"]: - continue - elif auth_setting["in"] == "header": - headers[auth_setting["key"]] = auth_setting["value"] - elif auth_setting["in"] == "query": - querys.append((auth_setting["key"], auth_setting["value"])) - else: - raise ValueError( - "Authentication token must be in `query` or `header`" - ) - - def __deserialize_file(self, response): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - :param response: RESTResponse. - :return: file path. - """ - fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - content_disposition = response.getheader("Content-Disposition") - if content_disposition: - filename = re.search( - r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition - ).group(1) - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "wb") as f: - f.write(response.data) - - return path - - def __deserialize_primitive(self, data, klass): - """Deserializes string to primitive type. - - :param data: str. - :param klass: class literal. - - :return: int, long, float, str, bool. - """ - try: - return klass(data) - except UnicodeEncodeError: - return six.text_type(data) - except TypeError: - return data - - def __deserialize_object(self, value): - """Return a original value. - - :return: object. - """ - return value - - def __deserialize_date(self, string): - """Deserializes string to date. - - :param string: str. - :return: date. - """ - try: - from dateutil.parser import parse - - return parse(string).date() - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, reason="Failed to parse `{0}` as date object".format(string) - ) - - def __deserialize_datatime(self, string): - """Deserializes string to datetime. - - The string should be in iso8601 datetime format. - - :param string: str. - :return: datetime. - """ - try: - from dateutil.parser import parse - - return parse(string) - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason=("Failed to parse `{0}` as datetime object".format(string)), - ) - - def __hasattr(self, object, name): - return name in object.__class__.__dict__ - - def __deserialize_model(self, data, klass): - """Deserializes list or dict to model. - - :param data: dict, list. - :param klass: class literal. - :return: model object. - """ - - if not klass.swagger_types and not self.__hasattr( - klass, "get_real_child_model" - ): - return data - - kwargs = {} - if klass.swagger_types is not None: - for attr, attr_type in six.iteritems(klass.swagger_types): - if ( - data is not None - and klass.attribute_map[attr] in data - and isinstance(data, (list, dict)) - ): - value = data[klass.attribute_map[attr]] - kwargs[attr] = self.__deserialize(value, attr_type) - - instance = klass(**kwargs) - - if ( - isinstance(instance, dict) - and klass.swagger_types is not None - and isinstance(data, dict) - ): - for key, value in data.items(): - if key not in klass.swagger_types: - instance[key] = value - if self.__hasattr(instance, "get_real_child_model"): - klass_name = instance.get_real_child_model(data) - if klass_name: - instance = self.__deserialize(data, klass_name) - return instance diff --git a/actions/src/swagger_client/configuration.py b/actions/src/swagger_client/configuration.py deleted file mode 100644 index 1dbeed1..0000000 --- a/actions/src/swagger_client/configuration.py +++ /dev/null @@ -1,251 +0,0 @@ -# coding: utf-8 - -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -from __future__ import absolute_import - -import copy -import logging -import multiprocessing -import sys -import urllib3 - -import six -from six.moves import http_client as httplib - - -class TypeWithDefault(type): - def __init__(cls, name, bases, dct): - super(TypeWithDefault, cls).__init__(name, bases, dct) - cls._default = None - - def __call__(cls): - if cls._default is None: - cls._default = type.__call__(cls) - return copy.copy(cls._default) - - def set_default(cls, default): - cls._default = copy.copy(default) - - -class Configuration(six.with_metaclass(TypeWithDefault, object)): - """NOTE: This class is auto generated by the swagger code generator program. - - Ref: https://github.com/swagger-api/swagger-codegen - Do not edit the class manually. - """ - - def __init__(self): - """Constructor""" - # Default Base url - self.host = "https://shipyard.build" - # Temp file folder for downloading files - self.temp_folder_path = None - - # Authentication Settings - # dict to store API key(s) - self.api_key = {} - # dict to store API prefix (e.g. Bearer) - self.api_key_prefix = {} - # function to refresh API key if expired - self.refresh_api_key_hook = None - # Username for HTTP basic authentication - self.username = "" - # Password for HTTP basic authentication - self.password = "" - # Logging Settings - self.logger = {} - self.logger["package_logger"] = logging.getLogger("swagger_client") - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - # Log format - self.logger_format = "%(asctime)s %(levelname)s %(message)s" - # Log stream handler - self.logger_stream_handler = None - # Log file handler - self.logger_file_handler = None - # Debug file location - self.logger_file = None - # Debug switch - self.debug = False - - # SSL/TLS verification - # Set this to false to skip verifying SSL certificate when calling API - # from https server. - self.verify_ssl = True - # Set this to customize the certificate file to verify the peer. - self.ssl_ca_cert = None - # client certificate file - self.cert_file = None - # client key file - self.key_file = None - # Set this to True/False to enable/disable SSL hostname verification. - self.assert_hostname = None - - # urllib3 connection pool's maximum number of connections saved - # per pool. urllib3 uses 1 connection as default value, but this is - # not the best value when you are making a lot of possibly parallel - # requests to the same host, which is often the case here. - # cpu_count * 5 is used as default value to increase performance. - self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - - # Proxy URL - self.proxy = None - # Safe chars for path_param - self.safe_chars_for_path_param = "" - - @property - def logger_file(self): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - return self.__logger_file - - @logger_file.setter - def logger_file(self, value): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - self.__logger_file = value - if self.__logger_file: - # If set logging file, - # then add file handler and remove stream handler. - self.logger_file_handler = logging.FileHandler(self.__logger_file) - self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in six.iteritems(self.logger): - logger.addHandler(self.logger_file_handler) - if self.logger_stream_handler: - logger.removeHandler(self.logger_stream_handler) - else: - # If not set logging file, - # then add stream handler and remove file handler. - self.logger_stream_handler = logging.StreamHandler() - self.logger_stream_handler.setFormatter(self.logger_formatter) - for _, logger in six.iteritems(self.logger): - logger.addHandler(self.logger_stream_handler) - if self.logger_file_handler: - logger.removeHandler(self.logger_file_handler) - - @property - def debug(self): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - return self.__debug - - @debug.setter - def debug(self, value): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - self.__debug = value - if self.__debug: - # if debug status is True, turn on debug logging - for _, logger in six.iteritems(self.logger): - logger.setLevel(logging.DEBUG) - # turn on httplib debug - httplib.HTTPConnection.debuglevel = 1 - else: - # if debug status is False, turn off debug logging, - # setting log level to default `logging.WARNING` - for _, logger in six.iteritems(self.logger): - logger.setLevel(logging.WARNING) - # turn off httplib debug - httplib.HTTPConnection.debuglevel = 0 - - @property - def logger_format(self): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - return self.__logger_format - - @logger_format.setter - def logger_format(self, value): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - self.__logger_format = value - self.logger_formatter = logging.Formatter(self.__logger_format) - - def get_api_key_with_prefix(self, identifier): - """Gets API key (with prefix if set). - - :param identifier: The identifier of apiKey. - :return: The token for api key authentication. - """ - if self.refresh_api_key_hook: - self.refresh_api_key_hook(self) - - key = self.api_key.get(identifier) - if key: - prefix = self.api_key_prefix.get(identifier) - if prefix: - return "%s %s" % (prefix, key) - else: - return key - - def get_basic_auth_token(self): - """Gets HTTP basic authentication header (string). - - :return: The token for basic HTTP authentication. - """ - return urllib3.util.make_headers( - basic_auth=self.username + ":" + self.password - ).get("authorization") - - def auth_settings(self): - """Gets Auth Settings dict for api client. - - :return: The Auth Settings information dict. - """ - return { - "ApiKeyAuth": { - "type": "api_key", - "in": "header", - "key": "x-api-token", - "value": self.get_api_key_with_prefix("x-api-token"), - }, - } - - def to_debug_report(self): - """Gets the essential information for debugging. - - :return: The report for debugging. - """ - return ( - "Python SDK Debug Report:\n" - "OS: {env}\n" - "Python Version: {pyversion}\n" - "Version of the API: 0.1\n" - "SDK Package Version: 1.0.0".format(env=sys.platform, pyversion=sys.version) - ) diff --git a/actions/src/swagger_client/models/__init__.py b/actions/src/swagger_client/models/__init__.py deleted file mode 100644 index b6de179..0000000 --- a/actions/src/swagger_client/models/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -# coding: utf-8 - -# flake8: noqa -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -from __future__ import absolute_import - -# import models into model package -from swagger_client.models.inline_response200 import InlineResponse200 -from swagger_client.models.inline_response2001 import InlineResponse2001 -from swagger_client.models.inline_response2001_data import InlineResponse2001Data -from swagger_client.models.inline_response2001_data_attributes import ( - InlineResponse2001DataAttributes, -) -from swagger_client.models.inline_response2001_data_attributes_projects import ( - InlineResponse2001DataAttributesProjects, -) -from swagger_client.models.inline_response2001_data_links import ( - InlineResponse2001DataLinks, -) diff --git a/actions/src/swagger_client/models/inline_response200.py b/actions/src/swagger_client/models/inline_response200.py deleted file mode 100644 index 907268a..0000000 --- a/actions/src/swagger_client/models/inline_response200.py +++ /dev/null @@ -1,110 +0,0 @@ -# coding: utf-8 - -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 - -import six - - -class InlineResponse200(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = {"data": "list[object]"} - - attribute_map = {"data": "data"} - - def __init__(self, data=None): # noqa: E501 - """InlineResponse200 - a model defined in Swagger""" # noqa: E501 - self._data = None - self.discriminator = None - if data is not None: - self.data = data - - @property - def data(self): - """Gets the data of this InlineResponse200. # noqa: E501 - - - :return: The data of this InlineResponse200. # noqa: E501 - :rtype: list[object] - """ - return self._data - - @data.setter - def data(self, data): - """Sets the data of this InlineResponse200. - - - :param data: The data of this InlineResponse200. # noqa: E501 - :type: list[object] - """ - - self._data = data - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - if issubclass(InlineResponse200, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, InlineResponse200): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/actions/src/swagger_client/models/inline_response2001.py b/actions/src/swagger_client/models/inline_response2001.py deleted file mode 100644 index 6ac9384..0000000 --- a/actions/src/swagger_client/models/inline_response2001.py +++ /dev/null @@ -1,110 +0,0 @@ -# coding: utf-8 - -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 - -import six - - -class InlineResponse2001(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = {"data": "InlineResponse2001Data"} - - attribute_map = {"data": "data"} - - def __init__(self, data=None): # noqa: E501 - """InlineResponse2001 - a model defined in Swagger""" # noqa: E501 - self._data = None - self.discriminator = None - if data is not None: - self.data = data - - @property - def data(self): - """Gets the data of this InlineResponse2001. # noqa: E501 - - - :return: The data of this InlineResponse2001. # noqa: E501 - :rtype: InlineResponse2001Data - """ - return self._data - - @data.setter - def data(self, data): - """Sets the data of this InlineResponse2001. - - - :param data: The data of this InlineResponse2001. # noqa: E501 - :type: InlineResponse2001Data - """ - - self._data = data - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - if issubclass(InlineResponse2001, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, InlineResponse2001): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/actions/src/swagger_client/models/inline_response2001_data.py b/actions/src/swagger_client/models/inline_response2001_data.py deleted file mode 100644 index 5cd0281..0000000 --- a/actions/src/swagger_client/models/inline_response2001_data.py +++ /dev/null @@ -1,192 +0,0 @@ -# coding: utf-8 - -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 - -import six - - -class InlineResponse2001Data(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - "attributes": "InlineResponse2001DataAttributes", - "links": "InlineResponse2001DataLinks", - "id": "str", - "type": "str", - } - - attribute_map = { - "attributes": "attributes", - "links": "links", - "id": "id", - "type": "type", - } - - def __init__(self, attributes=None, links=None, id=None, type=None): # noqa: E501 - """InlineResponse2001Data - a model defined in Swagger""" # noqa: E501 - self._attributes = None - self._links = None - self._id = None - self._type = None - self.discriminator = None - if attributes is not None: - self.attributes = attributes - if links is not None: - self.links = links - if id is not None: - self.id = id - if type is not None: - self.type = type - - @property - def attributes(self): - """Gets the attributes of this InlineResponse2001Data. # noqa: E501 - - - :return: The attributes of this InlineResponse2001Data. # noqa: E501 - :rtype: InlineResponse2001DataAttributes - """ - return self._attributes - - @attributes.setter - def attributes(self, attributes): - """Sets the attributes of this InlineResponse2001Data. - - - :param attributes: The attributes of this InlineResponse2001Data. # noqa: E501 - :type: InlineResponse2001DataAttributes - """ - - self._attributes = attributes - - @property - def links(self): - """Gets the links of this InlineResponse2001Data. # noqa: E501 - - - :return: The links of this InlineResponse2001Data. # noqa: E501 - :rtype: InlineResponse2001DataLinks - """ - return self._links - - @links.setter - def links(self, links): - """Sets the links of this InlineResponse2001Data. - - - :param links: The links of this InlineResponse2001Data. # noqa: E501 - :type: InlineResponse2001DataLinks - """ - - self._links = links - - @property - def id(self): - """Gets the id of this InlineResponse2001Data. # noqa: E501 - - - :return: The id of this InlineResponse2001Data. # noqa: E501 - :rtype: str - """ - return self._id - - @id.setter - def id(self, id): - """Sets the id of this InlineResponse2001Data. - - - :param id: The id of this InlineResponse2001Data. # noqa: E501 - :type: str - """ - - self._id = id - - @property - def type(self): - """Gets the type of this InlineResponse2001Data. # noqa: E501 - - - :return: The type of this InlineResponse2001Data. # noqa: E501 - :rtype: str - """ - return self._type - - @type.setter - def type(self, type): - """Sets the type of this InlineResponse2001Data. - - - :param type: The type of this InlineResponse2001Data. # noqa: E501 - :type: str - """ - - self._type = type - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - if issubclass(InlineResponse2001Data, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, InlineResponse2001Data): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/actions/src/swagger_client/models/inline_response2001_data_attributes.py b/actions/src/swagger_client/models/inline_response2001_data_attributes.py deleted file mode 100644 index e60cfc2..0000000 --- a/actions/src/swagger_client/models/inline_response2001_data_attributes.py +++ /dev/null @@ -1,306 +0,0 @@ -# coding: utf-8 - -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 - -import six - - -class InlineResponse2001DataAttributes(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - "bypass_token": "str", - "paused": "bool", - "stopped": "bool", - "projects": "list[InlineResponse2001DataAttributesProjects]", - "ready": "bool", - "name": "str", - "processing": "bool", - "url": "str", - } - - attribute_map = { - "bypass_token": "bypass_token", - "paused": "paused", - "stopped": "stopped", - "projects": "projects", - "ready": "ready", - "name": "name", - "processing": "processing", - "url": "url", - } - - def __init__( - self, - bypass_token=None, - paused=None, - stopped=None, - projects=None, - ready=None, - name=None, - processing=None, - url=None, - ): # noqa: E501 - """InlineResponse2001DataAttributes - a model defined in Swagger""" # noqa: E501 - self._bypass_token = None - self._paused = None - self._stopped = None - self._projects = None - self._ready = None - self._name = None - self._processing = None - self._url = None - self.discriminator = None - if bypass_token is not None: - self.bypass_token = bypass_token - if paused is not None: - self.paused = paused - if stopped is not None: - self.stopped = stopped - if projects is not None: - self.projects = projects - if ready is not None: - self.ready = ready - if name is not None: - self.name = name - if processing is not None: - self.processing = processing - if url is not None: - self.url = url - - @property - def bypass_token(self): - """Gets the bypass_token of this InlineResponse2001DataAttributes. # noqa: E501 - - - :return: The bypass_token of this InlineResponse2001DataAttributes. # noqa: E501 - :rtype: str - """ - return self._bypass_token - - @bypass_token.setter - def bypass_token(self, bypass_token): - """Sets the bypass_token of this InlineResponse2001DataAttributes. - - - :param bypass_token: The bypass_token of this InlineResponse2001DataAttributes. # noqa: E501 - :type: str - """ - - self._bypass_token = bypass_token - - @property - def paused(self): - """Gets the paused of this InlineResponse2001DataAttributes. # noqa: E501 - - - :return: The paused of this InlineResponse2001DataAttributes. # noqa: E501 - :rtype: bool - """ - return self._paused - - @paused.setter - def paused(self, paused): - """Sets the paused of this InlineResponse2001DataAttributes. - - - :param paused: The paused of this InlineResponse2001DataAttributes. # noqa: E501 - :type: bool - """ - - self._paused = paused - - @property - def stopped(self): - """Gets the stopped of this InlineResponse2001DataAttributes. # noqa: E501 - - - :return: The stopped of this InlineResponse2001DataAttributes. # noqa: E501 - :rtype: bool - """ - return self._stopped - - @stopped.setter - def stopped(self, stopped): - """Sets the stopped of this InlineResponse2001DataAttributes. - - - :param stopped: The stopped of this InlineResponse2001DataAttributes. # noqa: E501 - :type: bool - """ - - self._stopped = stopped - - @property - def projects(self): - """Gets the projects of this InlineResponse2001DataAttributes. # noqa: E501 - - - :return: The projects of this InlineResponse2001DataAttributes. # noqa: E501 - :rtype: list[InlineResponse2001DataAttributesProjects] - """ - return self._projects - - @projects.setter - def projects(self, projects): - """Sets the projects of this InlineResponse2001DataAttributes. - - - :param projects: The projects of this InlineResponse2001DataAttributes. # noqa: E501 - :type: list[InlineResponse2001DataAttributesProjects] - """ - - self._projects = projects - - @property - def ready(self): - """Gets the ready of this InlineResponse2001DataAttributes. # noqa: E501 - - - :return: The ready of this InlineResponse2001DataAttributes. # noqa: E501 - :rtype: bool - """ - return self._ready - - @ready.setter - def ready(self, ready): - """Sets the ready of this InlineResponse2001DataAttributes. - - - :param ready: The ready of this InlineResponse2001DataAttributes. # noqa: E501 - :type: bool - """ - - self._ready = ready - - @property - def name(self): - """Gets the name of this InlineResponse2001DataAttributes. # noqa: E501 - - - :return: The name of this InlineResponse2001DataAttributes. # noqa: E501 - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """Sets the name of this InlineResponse2001DataAttributes. - - - :param name: The name of this InlineResponse2001DataAttributes. # noqa: E501 - :type: str - """ - - self._name = name - - @property - def processing(self): - """Gets the processing of this InlineResponse2001DataAttributes. # noqa: E501 - - - :return: The processing of this InlineResponse2001DataAttributes. # noqa: E501 - :rtype: bool - """ - return self._processing - - @processing.setter - def processing(self, processing): - """Sets the processing of this InlineResponse2001DataAttributes. - - - :param processing: The processing of this InlineResponse2001DataAttributes. # noqa: E501 - :type: bool - """ - - self._processing = processing - - @property - def url(self): - """Gets the url of this InlineResponse2001DataAttributes. # noqa: E501 - - - :return: The url of this InlineResponse2001DataAttributes. # noqa: E501 - :rtype: str - """ - return self._url - - @url.setter - def url(self, url): - """Sets the url of this InlineResponse2001DataAttributes. - - - :param url: The url of this InlineResponse2001DataAttributes. # noqa: E501 - :type: str - """ - - self._url = url - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - if issubclass(InlineResponse2001DataAttributes, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, InlineResponse2001DataAttributes): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/actions/src/swagger_client/models/inline_response2001_data_attributes_projects.py b/actions/src/swagger_client/models/inline_response2001_data_attributes_projects.py deleted file mode 100644 index 56bf8f4..0000000 --- a/actions/src/swagger_client/models/inline_response2001_data_attributes_projects.py +++ /dev/null @@ -1,225 +0,0 @@ -# coding: utf-8 - -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 - -import six - - -class InlineResponse2001DataAttributesProjects(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - "pull_request_number": "Object", - "repo_name": "str", - "org_name": "str", - "branch": "str", - "commit_hash": "str", - } - - attribute_map = { - "pull_request_number": "pull_request_number", - "repo_name": "repo_name", - "org_name": "org_name", - "branch": "branch", - "commit_hash": "commit_hash", - } - - def __init__( - self, - pull_request_number=None, - repo_name=None, - org_name=None, - branch=None, - commit_hash=None, - ): # noqa: E501 - """InlineResponse2001DataAttributesProjects - a model defined in Swagger""" # noqa: E501 - self._pull_request_number = None - self._repo_name = None - self._org_name = None - self._branch = None - self._commit_hash = None - self.discriminator = None - if pull_request_number is not None: - self.pull_request_number = pull_request_number - if repo_name is not None: - self.repo_name = repo_name - if org_name is not None: - self.org_name = org_name - if branch is not None: - self.branch = branch - if commit_hash is not None: - self.commit_hash = commit_hash - - @property - def pull_request_number(self): - """Gets the pull_request_number of this InlineResponse2001DataAttributesProjects. # noqa: E501 - - - :return: The pull_request_number of this InlineResponse2001DataAttributesProjects. # noqa: E501 - :rtype: Object - """ - return self._pull_request_number - - @pull_request_number.setter - def pull_request_number(self, pull_request_number): - """Sets the pull_request_number of this InlineResponse2001DataAttributesProjects. - - - :param pull_request_number: The pull_request_number of this InlineResponse2001DataAttributesProjects. # noqa: E501 - :type: Object - """ - - self._pull_request_number = pull_request_number - - @property - def repo_name(self): - """Gets the repo_name of this InlineResponse2001DataAttributesProjects. # noqa: E501 - - - :return: The repo_name of this InlineResponse2001DataAttributesProjects. # noqa: E501 - :rtype: str - """ - return self._repo_name - - @repo_name.setter - def repo_name(self, repo_name): - """Sets the repo_name of this InlineResponse2001DataAttributesProjects. - - - :param repo_name: The repo_name of this InlineResponse2001DataAttributesProjects. # noqa: E501 - :type: str - """ - - self._repo_name = repo_name - - @property - def org_name(self): - """Gets the org_name of this InlineResponse2001DataAttributesProjects. # noqa: E501 - - - :return: The org_name of this InlineResponse2001DataAttributesProjects. # noqa: E501 - :rtype: str - """ - return self._org_name - - @org_name.setter - def org_name(self, org_name): - """Sets the org_name of this InlineResponse2001DataAttributesProjects. - - - :param org_name: The org_name of this InlineResponse2001DataAttributesProjects. # noqa: E501 - :type: str - """ - - self._org_name = org_name - - @property - def branch(self): - """Gets the branch of this InlineResponse2001DataAttributesProjects. # noqa: E501 - - - :return: The branch of this InlineResponse2001DataAttributesProjects. # noqa: E501 - :rtype: str - """ - return self._branch - - @branch.setter - def branch(self, branch): - """Sets the branch of this InlineResponse2001DataAttributesProjects. - - - :param branch: The branch of this InlineResponse2001DataAttributesProjects. # noqa: E501 - :type: str - """ - - self._branch = branch - - @property - def commit_hash(self): - """Gets the commit_hash of this InlineResponse2001DataAttributesProjects. # noqa: E501 - - - :return: The commit_hash of this InlineResponse2001DataAttributesProjects. # noqa: E501 - :rtype: str - """ - return self._commit_hash - - @commit_hash.setter - def commit_hash(self, commit_hash): - """Sets the commit_hash of this InlineResponse2001DataAttributesProjects. - - - :param commit_hash: The commit_hash of this InlineResponse2001DataAttributesProjects. # noqa: E501 - :type: str - """ - - self._commit_hash = commit_hash - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - if issubclass(InlineResponse2001DataAttributesProjects, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, InlineResponse2001DataAttributesProjects): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/actions/src/swagger_client/models/inline_response2001_data_links.py b/actions/src/swagger_client/models/inline_response2001_data_links.py deleted file mode 100644 index 1033307..0000000 --- a/actions/src/swagger_client/models/inline_response2001_data_links.py +++ /dev/null @@ -1,110 +0,0 @@ -# coding: utf-8 - -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 - -import six - - -class InlineResponse2001DataLinks(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = {"_self": "str"} - - attribute_map = {"_self": "self"} - - def __init__(self, _self=None): # noqa: E501 - """InlineResponse2001DataLinks - a model defined in Swagger""" # noqa: E501 - self.__self = None - self.discriminator = None - if _self is not None: - self._self = _self - - @property - def _self(self): - """Gets the _self of this InlineResponse2001DataLinks. # noqa: E501 - - - :return: The _self of this InlineResponse2001DataLinks. # noqa: E501 - :rtype: str - """ - return self.__self - - @_self.setter - def _self(self, _self): - """Sets the _self of this InlineResponse2001DataLinks. - - - :param _self: The _self of this InlineResponse2001DataLinks. # noqa: E501 - :type: str - """ - - self.__self = _self - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list( - map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) - ) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict( - map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") - else item, - value.items(), - ) - ) - else: - result[attr] = value - if issubclass(InlineResponse2001DataLinks, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, InlineResponse2001DataLinks): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/actions/src/swagger_client/rest.py b/actions/src/swagger_client/rest.py deleted file mode 100644 index 831e8b3..0000000 --- a/actions/src/swagger_client/rest.py +++ /dev/null @@ -1,414 +0,0 @@ -# coding: utf-8 - -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -from __future__ import absolute_import - -import io -import json -import logging -import re -import ssl - -import certifi - -# python 2 and python 3 compatibility library -import six -from six.moves.urllib.parse import urlencode - -try: - import urllib3 -except ImportError: - raise ImportError("Swagger python client requires urllib3.") - - -logger = logging.getLogger(__name__) - - -class RESTResponse(io.IOBase): - def __init__(self, resp): - self.urllib3_response = resp - self.status = resp.status - self.reason = resp.reason - self.data = resp.data - - def getheaders(self): - """Returns a dictionary of the response headers.""" - return self.urllib3_response.getheaders() - - def getheader(self, name, default=None): - """Returns a given response header.""" - return self.urllib3_response.getheader(name, default) - - -class RESTClientObject(object): - def __init__(self, configuration, pools_size=4, maxsize=None): - # urllib3.PoolManager will pass all kw parameters to connectionpool - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 - # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 - # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 - - # cert_reqs - if configuration.verify_ssl: - cert_reqs = ssl.CERT_REQUIRED - else: - cert_reqs = ssl.CERT_NONE - - # ca_certs - if configuration.ssl_ca_cert: - ca_certs = configuration.ssl_ca_cert - else: - # if not set certificate file, use Mozilla's root certificates. - ca_certs = certifi.where() - - addition_pool_args = {} - if configuration.assert_hostname is not None: - addition_pool_args[ - "assert_hostname" - ] = configuration.assert_hostname # noqa: E501 - - if maxsize is None: - if configuration.connection_pool_maxsize is not None: - maxsize = configuration.connection_pool_maxsize - else: - maxsize = 4 - - # https pool manager - if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=ca_certs, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - **addition_pool_args - ) - else: - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=ca_certs, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - **addition_pool_args - ) - - def request( - self, - method, - url, - query_params=None, - headers=None, - body=None, - post_params=None, - _preload_content=True, - _request_timeout=None, - ): - """Perform requests. - - :param method: http request method - :param url: http request url - :param query_params: query parameters in the url - :param headers: http request headers - :param body: request json body, for `application/json` - :param post_params: request post parameters, - `application/x-www-form-urlencoded` - and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - """ - method = method.upper() - assert method in ["GET", "HEAD", "DELETE", "POST", "PUT", "PATCH", "OPTIONS"] - - if post_params and body: - raise ValueError( - "body parameter cannot be used with post_params parameter." - ) - - post_params = post_params or {} - headers = headers or {} - - timeout = None - if _request_timeout: - if isinstance( - _request_timeout, (int,) if six.PY3 else (int, long) - ): # noqa: E501,F821 - timeout = urllib3.Timeout(total=_request_timeout) - elif isinstance(_request_timeout, tuple) and len(_request_timeout) == 2: - timeout = urllib3.Timeout( - connect=_request_timeout[0], read=_request_timeout[1] - ) - - if "Content-Type" not in headers: - headers["Content-Type"] = "application/json" - - try: - # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` - if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]: - if query_params: - url += "?" + urlencode(query_params) - if re.search("json", headers["Content-Type"], re.IGNORECASE): - request_body = "{}" - if body is not None: - request_body = json.dumps(body) - r = self.pool_manager.request( - method, - url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - elif ( - headers["Content-Type"] == "application/x-www-form-urlencoded" - ): # noqa: E501 - r = self.pool_manager.request( - method, - url, - fields=post_params, - encode_multipart=False, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - elif headers["Content-Type"] == "multipart/form-data": - # must del headers['Content-Type'], or the correct - # Content-Type which generated by urllib3 will be - # overwritten. - del headers["Content-Type"] - r = self.pool_manager.request( - method, - url, - fields=post_params, - encode_multipart=True, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is - # provided in serialized form - elif isinstance(body, str): - request_body = body - r = self.pool_manager.request( - method, - url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - else: - # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided - arguments. Please check that your arguments match - declared content type.""" - raise ApiException(status=0, reason=msg) - # For `GET`, `HEAD` - else: - r = self.pool_manager.request( - method, - url, - fields=query_params, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - except urllib3.exceptions.SSLError as e: - msg = "{0}\n{1}".format(type(e).__name__, str(e)) - raise ApiException(status=0, reason=msg) - - if _preload_content: - r = RESTResponse(r) - - # In the python 3, the response.data is bytes. - # we need to decode it to string. - if six.PY3: - r.data = r.data.decode("utf8") - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - raise ApiException(http_resp=r) - - return r - - def GET( - self, - url, - headers=None, - query_params=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "GET", - url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params, - ) - - def HEAD( - self, - url, - headers=None, - query_params=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "HEAD", - url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params, - ) - - def OPTIONS( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "OPTIONS", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def DELETE( - self, - url, - headers=None, - query_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "DELETE", - url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def POST( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "POST", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def PUT( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "PUT", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def PATCH( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "PATCH", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - -class ApiException(Exception): - def __init__(self, status=None, reason=None, http_resp=None): - if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data - self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None - - def __str__(self): - """Custom error messages for exception""" - error_message = "({0})\n" "Reason: {1}\n".format(self.status, self.reason) - if self.headers: - error_message += "HTTP response headers: {0}\n".format(self.headers) - - if self.body: - error_message += "HTTP response body: {0}\n".format(self.body) - - return error_message diff --git a/commands/login.go b/commands/login.go index 86a7016..8911e23 100644 --- a/commands/login.go +++ b/commands/login.go @@ -70,7 +70,7 @@ func login() error { }() display.Println("Opening the default web browser...") - backendURL := fmt.Sprintf("https://shipyard.build/api/me/user-token/cli?callbackUrl=http://%s", server.Addr) + backendURL := fmt.Sprintf("https://shipyard.khulnasoft.com/api/me/user-token/cli?callbackUrl=http://%s", server.Addr) if err := browser.OpenURL(backendURL); err != nil { return err } diff --git a/actions/fetch-shipyard-env/action.yml b/fetch-shipyard-env/action.yml similarity index 100% rename from actions/fetch-shipyard-env/action.yml rename to fetch-shipyard-env/action.yml diff --git a/github-action/src/fetch_shipyard_env.py b/github-action/src/fetch_shipyard_env.py deleted file mode 100644 index f809b53..0000000 --- a/github-action/src/fetch_shipyard_env.py +++ /dev/null @@ -1,213 +0,0 @@ -""" -# Purpose: -Wait for the Shipyard environment to be ready, -then put its data in the environment. -# Required environment variables: -- GITHUB_ENV -- GITHUB_REPOSITORY -- GITHUB_REF_NAME -- INPUT_API_TOKEN or SHIPYARD_API_TOKEN -- INPUT_TIMEOUT_MINUTES or SHIPYARD_TIMEOUT -- INPUT_APP_NAME or SHIPYARD_APP_NAME -""" -from __future__ import print_function - -import os -import sys -import time -from datetime import datetime, timedelta - -import swagger_client -from swagger_client.rest import ApiException - - -def exit(msg): - print(msg) - sys.exit(1) - - -# Make sure there's a bash env file in the environment -bash_env_path = os.environ.get("GITHUB_ENV") -if not bash_env_path: - exit("ERROR: missing GITHUB_ENV environment variable") - -# Constants -repo_owner = os.environ.get("GITHUB_REPOSITORY_OWNER") -github_repo = os.environ.get("GITHUB_REPOSITORY") # repo_owner/repo -repo = github_repo.replace(f"{repo_owner}/", "") if github_repo else None -# GITHUB_HEAD_REF - The head ref or source branch of the pull request in a workflow run -branch = os.environ.get("GITHUB_HEAD_REF") -if not branch: - # GITHUB_REF_NAME - The branch or tag name that triggered the workflow run - branch = os.environ.get("GITHUB_REF_NAME") -ref_type = os.environ.get("GITHUB_REF_TYPE") # TODO: handle branch or tag? - -# Get auth token -api_token = os.environ.get("INPUT_API_TOKEN") -# if input is not provided, check ENV vars -if not api_token: - api_token = os.environ.get("SHIPYARD_API_TOKEN") -if not api_token: - exit("No SHIPYARD_API_TOKEN provided, exiting.") - -# Get the timeout -timeout_minutes = os.environ.get("INPUT_TIMEOUT_MINUTES") -if not timeout_minutes: - timeout_minutes = os.environ.get("SHIPYARD_TIMEOUT") -if timeout_minutes: - try: - timeout_minutes = int(timeout_minutes) - except Exception: - exit( - 'ERROR: the SHIPYARD_TIMEOUT provided ("{}") is not an integer'.format( - timeout_minutes - ) - ) -else: - timeout_minutes = 60 - -# Get the app name -app_name = os.environ.get("INPUT_APP_NAME") -if not app_name: - app_name = os.environ.get("SHIPYARD_APP_NAME") - -# Prepare API client -configuration = swagger_client.Configuration() -configuration.api_key["x-api-token"] = api_token -client = swagger_client.ApiClient(configuration) -api_instance = swagger_client.EnvironmentApi(client) - - -def fetch_shipyard_environment(): - """Fetch the Shipyard environment for this Github job""" - - # Hit the Shipyard API - try: - args = { - "repo_owner": repo_owner, - "repo_name": repo, - "branch": branch - } - if app_name: - args["name"] = app_name - response = api_instance.list_environments(**args).to_dict() - except ApiException as e: - exit("ERROR: issue while listing environments via API: {}".format(e)) - - # Exit if any errors - errors = response.get("errors") - if errors: - exit("ERROR: {}".format(errors[0]["title"])) - - # Verify an environment was found - if not len(response["data"]): - exit("ERROR: no matching Shipyard environment found") - - # Verify the data is where we expect - try: - environment_id = response["data"][0]["id"] - environment_data = response["data"][0]["attributes"] - except Exception: - exit("ERROR: invalid response data structure") - - # Verify all the needed fields are available - for param in ("bypass_token", "url", "ready", "stopped", "retired"): - if param not in environment_data: - exit("ERROR: no {} found!".format(param)) - - return environment_id, environment_data - - -def restart_environment(environment_id): - """Restart the Shipyard environment with the provided ID""" - - try: - api_instance.restart_environment(environment_id) - except ApiException as e: - exit("ERROR: issue while restart the environment: {}".format(e)) - - -def wait_for_environment(): - """Return the Shipyard environment data once it's ready""" - - auto_restart = True - was_restarted = False - - # Check the environment - environment_id, environment_data = fetch_shipyard_environment() - - start = datetime.now() - timeout_end = datetime.now() + timedelta(minutes=timeout_minutes) - - # Until the environment is ready - while not environment_data["ready"]: - now = datetime.now() - # Check if the timeout has elapsed - if datetime.now() > timeout_end: - exit("{} minute timeout elapsed, exiting!".format(timeout_minutes)) - - # Auto-restart the environment once if indicated - if all([environment_data["retired"], auto_restart, not was_restarted]): - restart_environment(environment_id) - was_restarted = True - print("Restarted Shipyard environment...") - elif environment_data["stopped"] and not environment_data["processing"]: - exit("ERROR: this environment is stopped and no builds are processing") - - # Wait 15 seconds - seconds_waited = int((now - start).total_seconds()) - wait_string = " ({}s elapsed)".format(seconds_waited) if seconds_waited else "" - print("Waiting for Shipyard environment...{}".format(wait_string)) - time.sleep(15) - - # Check on the environment again - environment_id, environment_data = fetch_shipyard_environment() - - return environment_id, environment_data - - -def main(): - """ - Wait for the Shipyard environment to be ready, - then put it's data in the bash environment. - """ - - environment_id, environment_data = wait_for_environment() - - try: - # Try to fetch the commit hash of classic environments - commit_hash = environment_data.get("commit_hash") - - # Fetch the commit hash if this is a single-repo app - if not commit_hash: - projects = environment_data.get("projects") - if len(projects) == 1: - commit_hash = projects[0]["commit_hash"] - except Exception: - print("WARNING: unable to retrieve commit hash") - commit_hash = None - - # Write the data to the job's environment - with open(bash_env_path, "a") as bash_env: - bash_env.write( - "\n".join( - [ - "SHIPYARD_BYPASS_TOKEN={}".format(environment_data["bypass_token"]), - "SHIPYARD_ENVIRONMENT_ID={}".format(environment_id), - "SHIPYARD_ENVIRONMENT_URL={}".format(environment_data["url"]), - "SHIPYARD_ENVIRONMENT_READY={}".format(environment_data["ready"]), - "SHIPYARD_ENVIRONMENT_RETIRED={}".format( - environment_data["retired"] - ), - ] - + ["SHIPYARD_ENVIRONMENT_COMMIT_HASH={}".format(commit_hash)] - if commit_hash - else [] - ) - ) - - print("Shipyard environment data written to {}!".format(bash_env_path)) - - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/github-action/src/requirements.txt b/github-action/src/requirements.txt deleted file mode 100644 index cbcae1f..0000000 --- a/github-action/src/requirements.txt +++ /dev/null @@ -1,5 +0,0 @@ -certifi >= 14.05.14 -six >= 1.10 -python_dateutil >= 2.5.3 -setuptools >= 21.0.0 -urllib3 >= 1.15.1 \ No newline at end of file diff --git a/github-action/src/swagger_client/__init__.py b/github-action/src/swagger_client/__init__.py deleted file mode 100644 index eeeff34..0000000 --- a/github-action/src/swagger_client/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# coding: utf-8 - -# flake8: noqa - -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -from __future__ import absolute_import - -# import apis into sdk package -from swagger_client.api.environment_api import EnvironmentApi - -# import ApiClient -from swagger_client.api_client import ApiClient -from swagger_client.configuration import Configuration - -# import models into sdk package -from swagger_client.models.inline_response200 import InlineResponse200 -from swagger_client.models.inline_response2001 import InlineResponse2001 -from swagger_client.models.inline_response2001_data import InlineResponse2001Data -from swagger_client.models.inline_response2001_data_attributes import ( - InlineResponse2001DataAttributes, -) -from swagger_client.models.inline_response2001_data_attributes_projects import ( - InlineResponse2001DataAttributesProjects, -) -from swagger_client.models.inline_response2001_data_links import ( - InlineResponse2001DataLinks, -) \ No newline at end of file diff --git a/github-action/src/swagger_client/api_client.py b/github-action/src/swagger_client/api_client.py deleted file mode 100644 index 34eb9f0..0000000 --- a/github-action/src/swagger_client/api_client.py +++ /dev/null @@ -1,705 +0,0 @@ -# coding: utf-8 -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" -from __future__ import absolute_import - -import datetime -import json -import mimetypes -from multiprocessing.pool import ThreadPool -import os -import re -import tempfile - -# python 2 and python 3 compatibility library -import six -from six.moves.urllib.parse import quote - -from swagger_client.configuration import Configuration -import swagger_client.models -from swagger_client import rest - - -class ApiClient(object): - """Generic API client for Swagger client library builds. - - Swagger generic API client. This client handles the client- - server communication, and is invariant across implementations. Specifics of - the methods and models for each application are generated from the Swagger - templates. - - NOTE: This class is auto generated by the swagger code generator program. - Ref: https://github.com/swagger-api/swagger-codegen - Do not edit the class manually. - - :param configuration: .Configuration object for this client - :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to - the API. - :param cookie: a cookie to include in the header when making calls - to the API - """ - - PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types - NATIVE_TYPES_MAPPING = { - "int": int, - "long": int if six.PY3 else long, # noqa: F821 - "float": float, - "str": str, - "bool": bool, - "date": datetime.date, - "datetime": datetime.datetime, - "object": object, - } - - def __init__( - self, configuration=None, header_name=None, header_value=None, cookie=None - ): - if configuration is None: - configuration = Configuration() - self.configuration = configuration - - self.pool = ThreadPool() - self.rest_client = rest.RESTClientObject(configuration) - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.cookie = cookie - # Set default User-Agent. - self.user_agent = "Swagger-Codegen/1.0.0/python" - - def __del__(self): - self.pool.close() - self.pool.join() - - @property - def user_agent(self): - """User agent for this API client""" - return self.default_headers["User-Agent"] - - @user_agent.setter - def user_agent(self, value): - self.default_headers["User-Agent"] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - def __call_api( - self, - resource_path, - method, - path_params=None, - query_params=None, - header_params=None, - body=None, - post_params=None, - files=None, - response_type=None, - auth_settings=None, - _return_http_data_only=None, - collection_formats=None, - _preload_content=True, - _request_timeout=None, - ): - - config = self.configuration - - # header parameters - header_params = header_params or {} - header_params.update(self.default_headers) - if self.cookie: - header_params["Cookie"] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - header_params = dict( - self.parameters_to_tuples(header_params, collection_formats) - ) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, collection_formats) - for k, v in path_params: - # specified safe chars, encode everything - resource_path = resource_path.replace( - "{%s}" % k, quote(str(v), safe=config.safe_chars_for_path_param) - ) - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = self.parameters_to_tuples(query_params, collection_formats) - - # post parameters - if post_params or files: - post_params = self.prepare_post_parameters(post_params, files) - post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, collection_formats) - - # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings) - - # body - if body: - body = self.sanitize_for_serialization(body) - - # request url - url = self.configuration.host + resource_path - - # perform request and return response - response_data = self.request( - method, - url, - query_params=query_params, - headers=header_params, - post_params=post_params, - body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - ) - - self.last_response = response_data - - return_data = response_data - if _preload_content: - # deserialize response data - if response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None - - if _return_http_data_only: - return return_data - else: - return (return_data, response_data.status, response_data.getheaders()) - - def sanitize_for_serialization(self, obj): - """Builds a JSON POST object. - - If obj is None, return None. - If obj is str, int, long, float, bool, return directly. - If obj is datetime.datetime, datetime.date - convert to string in iso8601 format. - If obj is list, sanitize each element in the list. - If obj is dict, return the dict. - If obj is swagger model, return the properties dict. - - :param obj: The data to serialize. - :return: The serialized form of data. - """ - if obj is None: - return None - elif isinstance(obj, self.PRIMITIVE_TYPES): - return obj - elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] - elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj) - elif isinstance(obj, (datetime.datetime, datetime.date)): - return obj.isoformat() - - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `swagger_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = { - obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in six.iteritems(obj.swagger_types) - if getattr(obj, attr) is not None - } - - return { - key: self.sanitize_for_serialization(val) - for key, val in six.iteritems(obj_dict) - } - - def deserialize(self, response, response_type): - """Deserializes response into an object. - - :param response: RESTResponse object to be deserialized. - :param response_type: class literal for - deserialized object, or string of class name. - - :return: deserialized object. - """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) - - # fetch data from response object - try: - data = json.loads(response.data) - except ValueError: - data = response.data - - return self.__deserialize(data, response_type) - - def __deserialize(self, data, klass): - """Deserializes dict, list, str into an object. - - :param data: dict, list or str. - :param klass: class literal, or string of class name. - - :return: object. - """ - if data is None: - return None - - if type(klass) == str: - if klass.startswith("list["): - sub_kls = re.match(r"list\[(.*)\]", klass).group(1) - return [self.__deserialize(sub_data, sub_kls) for sub_data in data] - - if klass.startswith("dict("): - sub_kls = re.match(r"dict\(([^,]*), (.*)\)", klass).group(2) - return { - k: self.__deserialize(v, sub_kls) for k, v in six.iteritems(data) - } - - # convert str to class - if klass in self.NATIVE_TYPES_MAPPING: - klass = self.NATIVE_TYPES_MAPPING[klass] - else: - klass = getattr(swagger_client.models, klass) - - if klass in self.PRIMITIVE_TYPES: - return self.__deserialize_primitive(data, klass) - elif klass == object: - return self.__deserialize_object(data) - elif klass == datetime.date: - return self.__deserialize_date(data) - elif klass == datetime.datetime: - return self.__deserialize_datatime(data) - else: - return self.__deserialize_model(data, klass) - - def call_api( - self, - resource_path, - method, - path_params=None, - query_params=None, - header_params=None, - body=None, - post_params=None, - files=None, - response_type=None, - auth_settings=None, - async_req=None, - _return_http_data_only=None, - collection_formats=None, - _preload_content=True, - _request_timeout=None, - ): - """Makes the HTTP request (synchronous) and returns deserialized data. - - To make an async request, set the async_req parameter. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. - :param async_req bool: execute request asynchronously - :param _return_http_data_only: response data without head status code - and headers - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: - If async_req parameter is True, - the request will be called asynchronously. - The method will return the request thread. - If parameter async_req is False or missing, - then the method will return the response directly. - """ - if not async_req: - return self.__call_api( - resource_path, - method, - path_params, - query_params, - header_params, - body, - post_params, - files, - response_type, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - ) - else: - thread = self.pool.apply_async( - self.__call_api, - ( - resource_path, - method, - path_params, - query_params, - header_params, - body, - post_params, - files, - response_type, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - ), - ) - return thread - - def request( - self, - method, - url, - query_params=None, - headers=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return self.rest_client.GET( - url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers, - ) - elif method == "HEAD": - return self.rest_client.HEAD( - url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers, - ) - elif method == "OPTIONS": - return self.rest_client.OPTIONS( - url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - elif method == "POST": - return self.rest_client.POST( - url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - elif method == "PUT": - return self.rest_client.PUT( - url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - elif method == "PATCH": - return self.rest_client.PATCH( - url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - elif method == "DELETE": - return self.rest_client.DELETE( - url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - else: - raise ValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - - def parameters_to_tuples(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. - - :param params: Parameters as dict or list of two-tuples - :param dict collection_formats: Parameter collection formats - :return: Parameters as list of tuples, collections formatted - """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in ( - six.iteritems(params) if isinstance(params, dict) else params - ): # noqa: E501 - if k in collection_formats: - collection_format = collection_formats[k] - if collection_format == "multi": - new_params.extend((k, value) for value in v) - else: - if collection_format == "ssv": - delimiter = " " - elif collection_format == "tsv": - delimiter = "\t" - elif collection_format == "pipes": - delimiter = "|" - else: # csv is the default - delimiter = "," - new_params.append((k, delimiter.join(str(value) for value in v))) - else: - new_params.append((k, v)) - return new_params - - def prepare_post_parameters(self, post_params=None, files=None): - """Builds form parameters. - - :param post_params: Normal form parameters. - :param files: File parameters. - :return: Form parameters with files. - """ - params = [] - - if post_params: - params = post_params - - if files: - for k, v in six.iteritems(files): - if not v: - continue - file_names = v if type(v) is list else [v] - for n in file_names: - with open(n, "rb") as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = ( - mimetypes.guess_type(filename)[0] - or "application/octet-stream" - ) - params.append(tuple([k, tuple([filename, filedata, mimetype])])) - - return params - - def select_header_accept(self, accepts): - """Returns `Accept` based on an array of accepts provided. - - :param accepts: List of headers. - :return: Accept (e.g. application/json). - """ - if not accepts: - return - - accepts = [x.lower() for x in accepts] - - if "application/json" in accepts: - return "application/json" - else: - return ", ".join(accepts) - - def select_header_content_type(self, content_types): - """Returns `Content-Type` based on an array of content_types provided. - - :param content_types: List of content-types. - :return: Content-Type (e.g. application/json). - """ - if not content_types: - return "application/json" - - content_types = [x.lower() for x in content_types] - - if "application/json" in content_types or "*/*" in content_types: - return "application/json" - else: - return content_types[0] - - def update_params_for_auth(self, headers, querys, auth_settings): - """Updates header and query params based on authentication setting. - - :param headers: Header parameters dict to be updated. - :param querys: Query parameters tuple list to be updated. - :param auth_settings: Authentication setting identifiers list. - """ - if not auth_settings: - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - if not auth_setting["value"]: - continue - elif auth_setting["in"] == "header": - headers[auth_setting["key"]] = auth_setting["value"] - elif auth_setting["in"] == "query": - querys.append((auth_setting["key"], auth_setting["value"])) - else: - raise ValueError( - "Authentication token must be in `query` or `header`" - ) - - def __deserialize_file(self, response): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - :param response: RESTResponse. - :return: file path. - """ - fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - content_disposition = response.getheader("Content-Disposition") - if content_disposition: - filename = re.search( - r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition - ).group(1) - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "wb") as f: - f.write(response.data) - - return path - - def __deserialize_primitive(self, data, klass): - """Deserializes string to primitive type. - - :param data: str. - :param klass: class literal. - - :return: int, long, float, str, bool. - """ - try: - return klass(data) - except UnicodeEncodeError: - return six.text_type(data) - except TypeError: - return data - - def __deserialize_object(self, value): - """Return a original value. - - :return: object. - """ - return value - - def __deserialize_date(self, string): - """Deserializes string to date. - - :param string: str. - :return: date. - """ - try: - from dateutil.parser import parse - - return parse(string).date() - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, reason="Failed to parse `{0}` as date object".format(string) - ) - - def __deserialize_datatime(self, string): - """Deserializes string to datetime. - - The string should be in iso8601 datetime format. - - :param string: str. - :return: datetime. - """ - try: - from dateutil.parser import parse - - return parse(string) - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason=("Failed to parse `{0}` as datetime object".format(string)), - ) - - def __hasattr(self, object, name): - return name in object.__class__.__dict__ - - def __deserialize_model(self, data, klass): - """Deserializes list or dict to model. - - :param data: dict, list. - :param klass: class literal. - :return: model object. - """ - - if not klass.swagger_types and not self.__hasattr( - klass, "get_real_child_model" - ): - return data - - kwargs = {} - if klass.swagger_types is not None: - for attr, attr_type in six.iteritems(klass.swagger_types): - if ( - data is not None - and klass.attribute_map[attr] in data - and isinstance(data, (list, dict)) - ): - value = data[klass.attribute_map[attr]] - kwargs[attr] = self.__deserialize(value, attr_type) - - instance = klass(**kwargs) - - if ( - isinstance(instance, dict) - and klass.swagger_types is not None - and isinstance(data, dict) - ): - for key, value in data.items(): - if key not in klass.swagger_types: - instance[key] = value - if self.__hasattr(instance, "get_real_child_model"): - klass_name = instance.get_real_child_model(data) - if klass_name: - instance = self.__deserialize(data, klass_name) - return instance \ No newline at end of file diff --git a/github-action/src/swagger_client/configuration.py b/github-action/src/swagger_client/configuration.py deleted file mode 100644 index 6ba565e..0000000 --- a/github-action/src/swagger_client/configuration.py +++ /dev/null @@ -1,251 +0,0 @@ -# coding: utf-8 - -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -from __future__ import absolute_import - -import copy -import logging -import multiprocessing -import sys -import urllib3 - -import six -from six.moves import http_client as httplib - - -class TypeWithDefault(type): - def __init__(cls, name, bases, dct): - super(TypeWithDefault, cls).__init__(name, bases, dct) - cls._default = None - - def __call__(cls): - if cls._default is None: - cls._default = type.__call__(cls) - return copy.copy(cls._default) - - def set_default(cls, default): - cls._default = copy.copy(default) - - -class Configuration(six.with_metaclass(TypeWithDefault, object)): - """NOTE: This class is auto generated by the swagger code generator program. - - Ref: https://github.com/swagger-api/swagger-codegen - Do not edit the class manually. - """ - - def __init__(self): - """Constructor""" - # Default Base url - self.host = "https://shipyard.build" - # Temp file folder for downloading files - self.temp_folder_path = None - - # Authentication Settings - # dict to store API key(s) - self.api_key = {} - # dict to store API prefix (e.g. Bearer) - self.api_key_prefix = {} - # function to refresh API key if expired - self.refresh_api_key_hook = None - # Username for HTTP basic authentication - self.username = "" - # Password for HTTP basic authentication - self.password = "" - # Logging Settings - self.logger = {} - self.logger["package_logger"] = logging.getLogger("swagger_client") - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - # Log format - self.logger_format = "%(asctime)s %(levelname)s %(message)s" - # Log stream handler - self.logger_stream_handler = None - # Log file handler - self.logger_file_handler = None - # Debug file location - self.logger_file = None - # Debug switch - self.debug = False - - # SSL/TLS verification - # Set this to false to skip verifying SSL certificate when calling API - # from https server. - self.verify_ssl = True - # Set this to customize the certificate file to verify the peer. - self.ssl_ca_cert = None - # client certificate file - self.cert_file = None - # client key file - self.key_file = None - # Set this to True/False to enable/disable SSL hostname verification. - self.assert_hostname = None - - # urllib3 connection pool's maximum number of connections saved - # per pool. urllib3 uses 1 connection as default value, but this is - # not the best value when you are making a lot of possibly parallel - # requests to the same host, which is often the case here. - # cpu_count * 5 is used as default value to increase performance. - self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - - # Proxy URL - self.proxy = None - # Safe chars for path_param - self.safe_chars_for_path_param = "" - - @property - def logger_file(self): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - return self.__logger_file - - @logger_file.setter - def logger_file(self, value): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - self.__logger_file = value - if self.__logger_file: - # If set logging file, - # then add file handler and remove stream handler. - self.logger_file_handler = logging.FileHandler(self.__logger_file) - self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in six.iteritems(self.logger): - logger.addHandler(self.logger_file_handler) - if self.logger_stream_handler: - logger.removeHandler(self.logger_stream_handler) - else: - # If not set logging file, - # then add stream handler and remove file handler. - self.logger_stream_handler = logging.StreamHandler() - self.logger_stream_handler.setFormatter(self.logger_formatter) - for _, logger in six.iteritems(self.logger): - logger.addHandler(self.logger_stream_handler) - if self.logger_file_handler: - logger.removeHandler(self.logger_file_handler) - - @property - def debug(self): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - return self.__debug - - @debug.setter - def debug(self, value): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - self.__debug = value - if self.__debug: - # if debug status is True, turn on debug logging - for _, logger in six.iteritems(self.logger): - logger.setLevel(logging.DEBUG) - # turn on httplib debug - httplib.HTTPConnection.debuglevel = 1 - else: - # if debug status is False, turn off debug logging, - # setting log level to default `logging.WARNING` - for _, logger in six.iteritems(self.logger): - logger.setLevel(logging.WARNING) - # turn off httplib debug - httplib.HTTPConnection.debuglevel = 0 - - @property - def logger_format(self): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - return self.__logger_format - - @logger_format.setter - def logger_format(self, value): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - self.__logger_format = value - self.logger_formatter = logging.Formatter(self.__logger_format) - - def get_api_key_with_prefix(self, identifier): - """Gets API key (with prefix if set). - - :param identifier: The identifier of apiKey. - :return: The token for api key authentication. - """ - if self.refresh_api_key_hook: - self.refresh_api_key_hook(self) - - key = self.api_key.get(identifier) - if key: - prefix = self.api_key_prefix.get(identifier) - if prefix: - return "%s %s" % (prefix, key) - else: - return key - - def get_basic_auth_token(self): - """Gets HTTP basic authentication header (string). - - :return: The token for basic HTTP authentication. - """ - return urllib3.util.make_headers( - basic_auth=self.username + ":" + self.password - ).get("authorization") - - def auth_settings(self): - """Gets Auth Settings dict for api client. - - :return: The Auth Settings information dict. - """ - return { - "ApiKeyAuth": { - "type": "api_key", - "in": "header", - "key": "x-api-token", - "value": self.get_api_key_with_prefix("x-api-token"), - }, - } - - def to_debug_report(self): - """Gets the essential information for debugging. - - :return: The report for debugging. - """ - return ( - "Python SDK Debug Report:\n" - "OS: {env}\n" - "Python Version: {pyversion}\n" - "Version of the API: 0.1\n" - "SDK Package Version: 1.0.0".format(env=sys.platform, pyversion=sys.version) - ) \ No newline at end of file diff --git a/github-action/src/swagger_client/models/__init__.py b/github-action/src/swagger_client/models/__init__.py deleted file mode 100644 index 59a3257..0000000 --- a/github-action/src/swagger_client/models/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -# coding: utf-8 - -# flake8: noqa -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -from __future__ import absolute_import - -# import models into model package -from swagger_client.models.inline_response200 import InlineResponse200 -from swagger_client.models.inline_response2001 import InlineResponse2001 -from swagger_client.models.inline_response2001_data import InlineResponse2001Data -from swagger_client.models.inline_response2001_data_attributes import ( - InlineResponse2001DataAttributes, -) -from swagger_client.models.inline_response2001_data_attributes_projects import ( - InlineResponse2001DataAttributesProjects, -) -from swagger_client.models.inline_response2001_data_links import ( - InlineResponse2001DataLinks, -) \ No newline at end of file diff --git a/github-action/src/swagger_client/rest.py b/github-action/src/swagger_client/rest.py deleted file mode 100644 index e8d544f..0000000 --- a/github-action/src/swagger_client/rest.py +++ /dev/null @@ -1,414 +0,0 @@ -# coding: utf-8 - -""" - Shipyard API - - The official OpenAPI spec for the Shipyard API. # noqa: E501 - - OpenAPI spec version: 0.1 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -from __future__ import absolute_import - -import io -import json -import logging -import re -import ssl - -import certifi - -# python 2 and python 3 compatibility library -import six -from six.moves.urllib.parse import urlencode - -try: - import urllib3 -except ImportError: - raise ImportError("Swagger python client requires urllib3.") - - -logger = logging.getLogger(__name__) - - -class RESTResponse(io.IOBase): - def __init__(self, resp): - self.urllib3_response = resp - self.status = resp.status - self.reason = resp.reason - self.data = resp.data - - def getheaders(self): - """Returns a dictionary of the response headers.""" - return self.urllib3_response.getheaders() - - def getheader(self, name, default=None): - """Returns a given response header.""" - return self.urllib3_response.getheader(name, default) - - -class RESTClientObject(object): - def __init__(self, configuration, pools_size=4, maxsize=None): - # urllib3.PoolManager will pass all kw parameters to connectionpool - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 - # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 - # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 - - # cert_reqs - if configuration.verify_ssl: - cert_reqs = ssl.CERT_REQUIRED - else: - cert_reqs = ssl.CERT_NONE - - # ca_certs - if configuration.ssl_ca_cert: - ca_certs = configuration.ssl_ca_cert - else: - # if not set certificate file, use Mozilla's root certificates. - ca_certs = certifi.where() - - addition_pool_args = {} - if configuration.assert_hostname is not None: - addition_pool_args[ - "assert_hostname" - ] = configuration.assert_hostname # noqa: E501 - - if maxsize is None: - if configuration.connection_pool_maxsize is not None: - maxsize = configuration.connection_pool_maxsize - else: - maxsize = 4 - - # https pool manager - if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=ca_certs, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - **addition_pool_args - ) - else: - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=ca_certs, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - **addition_pool_args - ) - - def request( - self, - method, - url, - query_params=None, - headers=None, - body=None, - post_params=None, - _preload_content=True, - _request_timeout=None, - ): - """Perform requests. - - :param method: http request method - :param url: http request url - :param query_params: query parameters in the url - :param headers: http request headers - :param body: request json body, for `application/json` - :param post_params: request post parameters, - `application/x-www-form-urlencoded` - and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - """ - method = method.upper() - assert method in ["GET", "HEAD", "DELETE", "POST", "PUT", "PATCH", "OPTIONS"] - - if post_params and body: - raise ValueError( - "body parameter cannot be used with post_params parameter." - ) - - post_params = post_params or {} - headers = headers or {} - - timeout = None - if _request_timeout: - if isinstance( - _request_timeout, (int,) if six.PY3 else (int, long) - ): # noqa: E501,F821 - timeout = urllib3.Timeout(total=_request_timeout) - elif isinstance(_request_timeout, tuple) and len(_request_timeout) == 2: - timeout = urllib3.Timeout( - connect=_request_timeout[0], read=_request_timeout[1] - ) - - if "Content-Type" not in headers: - headers["Content-Type"] = "application/json" - - try: - # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` - if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]: - if query_params: - url += "?" + urlencode(query_params) - if re.search("json", headers["Content-Type"], re.IGNORECASE): - request_body = "{}" - if body is not None: - request_body = json.dumps(body) - r = self.pool_manager.request( - method, - url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - elif ( - headers["Content-Type"] == "application/x-www-form-urlencoded" - ): # noqa: E501 - r = self.pool_manager.request( - method, - url, - fields=post_params, - encode_multipart=False, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - elif headers["Content-Type"] == "multipart/form-data": - # must del headers['Content-Type'], or the correct - # Content-Type which generated by urllib3 will be - # overwritten. - del headers["Content-Type"] - r = self.pool_manager.request( - method, - url, - fields=post_params, - encode_multipart=True, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is - # provided in serialized form - elif isinstance(body, str): - request_body = body - r = self.pool_manager.request( - method, - url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - else: - # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided - arguments. Please check that your arguments match - declared content type.""" - raise ApiException(status=0, reason=msg) - # For `GET`, `HEAD` - else: - r = self.pool_manager.request( - method, - url, - fields=query_params, - preload_content=_preload_content, - timeout=timeout, - headers=headers, - ) - except urllib3.exceptions.SSLError as e: - msg = "{0}\n{1}".format(type(e).__name__, str(e)) - raise ApiException(status=0, reason=msg) - - if _preload_content: - r = RESTResponse(r) - - # In the python 3, the response.data is bytes. - # we need to decode it to string. - if six.PY3: - r.data = r.data.decode("utf8") - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - raise ApiException(http_resp=r) - - return r - - def GET( - self, - url, - headers=None, - query_params=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "GET", - url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params, - ) - - def HEAD( - self, - url, - headers=None, - query_params=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "HEAD", - url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params, - ) - - def OPTIONS( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "OPTIONS", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def DELETE( - self, - url, - headers=None, - query_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "DELETE", - url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def POST( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "POST", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def PUT( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "PUT", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - def PATCH( - self, - url, - headers=None, - query_params=None, - post_params=None, - body=None, - _preload_content=True, - _request_timeout=None, - ): - return self.request( - "PATCH", - url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body, - ) - - -class ApiException(Exception): - def __init__(self, status=None, reason=None, http_resp=None): - if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data - self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None - - def __str__(self): - """Custom error messages for exception""" - error_message = "({0})\n" "Reason: {1}\n".format(self.status, self.reason) - if self.headers: - error_message += "HTTP response headers: {0}\n".format(self.headers) - - if self.body: - error_message += "HTTP response body: {0}\n".format(self.body) - - return error_message \ No newline at end of file diff --git a/pkg/requests/uri/uri.go b/pkg/requests/uri/uri.go index 3c36281..2a3a43a 100644 --- a/pkg/requests/uri/uri.go +++ b/pkg/requests/uri/uri.go @@ -8,7 +8,7 @@ import ( ) func CreateResourceURI(action, resource, id, subresource string, params map[string]string) string { - baseURL := "https://shipyard.build/api/v1" + baseURL := "https://shipyard.khulnasoft.com/api/v1" if value := os.Getenv("SHIPYARD_BUILD_URL"); value != "" { baseURL = value } diff --git a/pkg/requests/uri/uri_test.go b/pkg/requests/uri/uri_test.go index 21d0d0b..5befcab 100644 --- a/pkg/requests/uri/uri_test.go +++ b/pkg/requests/uri/uri_test.go @@ -21,48 +21,48 @@ func TestCreateResourceURI(t *testing.T) { { name: "Get all environments", action: "", resource: "environment", id: "", subresource: "", params: nil, - want: "https://shipyard.build/api/v1/environment", + want: "https://shipyard.khulnasoft.com/api/v1/environment", }, { name: "Get all environments in a specific org", action: "", resource: "environment", id: "", subresource: "", params: map[string]string{"org": "myorg"}, - want: "https://shipyard.build/api/v1/environment?org=myorg", + want: "https://shipyard.khulnasoft.com/api/v1/environment?org=myorg", }, { name: "Get all environments with filters applied", action: "", resource: "environment", id: "", subresource: "", params: map[string]string{"branch": "newfeature", "repo_name": "shipyard", "page_size": "9"}, - want: "https://shipyard.build/api/v1/environment?branch=newfeature&page_size=9&repo_name=shipyard", + want: "https://shipyard.khulnasoft.com/api/v1/environment?branch=newfeature&page_size=9&repo_name=shipyard", }, { name: "Get a single environment", action: "", resource: "environment", id: "123abc", subresource: "", - want: "https://shipyard.build/api/v1/environment/123abc", + want: "https://shipyard.khulnasoft.com/api/v1/environment/123abc", }, { name: "Get a single environment in a specific org", action: "", resource: "environment", id: "123abc", subresource: "", params: map[string]string{"org": "myorg"}, - want: "https://shipyard.build/api/v1/environment/123abc?org=myorg", + want: "https://shipyard.khulnasoft.com/api/v1/environment/123abc?org=myorg", }, { name: "Get a kubeconfig for a single environment", action: "", resource: "environment", id: "123abc", subresource: "kubeconfig", params: nil, - want: "https://shipyard.build/api/v1/environment/123abc/kubeconfig", + want: "https://shipyard.khulnasoft.com/api/v1/environment/123abc/kubeconfig", }, { name: "Get a kubeconfig for a single environment in a specific org", action: "", resource: "environment", id: "123abc", subresource: "kubeconfig", params: map[string]string{"org": "myorg"}, - want: "https://shipyard.build/api/v1/environment/123abc/kubeconfig?org=myorg", + want: "https://shipyard.khulnasoft.com/api/v1/environment/123abc/kubeconfig?org=myorg", }, { name: "Stop a single environment", action: "stop", resource: "environment", id: "123abc", subresource: "", params: nil, - want: "https://shipyard.build/api/v1/environment/123abc/stop", + want: "https://shipyard.khulnasoft.com/api/v1/environment/123abc/stop", }, { name: "Stop a single environment in a specific org", action: "stop", resource: "environment", id: "123abc", subresource: "", params: map[string]string{"org": "myorg"}, - want: "https://shipyard.build/api/v1/environment/123abc/stop?org=myorg", + want: "https://shipyard.khulnasoft.com/api/v1/environment/123abc/stop?org=myorg", }, } diff --git a/actions/action/src/fetch_shipyard_env.py b/src/fetch_shipyard_env.py similarity index 100% rename from actions/action/src/fetch_shipyard_env.py rename to src/fetch_shipyard_env.py diff --git a/actions/action/src/requirements.txt b/src/requirements.txt similarity index 100% rename from actions/action/src/requirements.txt rename to src/requirements.txt diff --git a/actions/action/src/swagger_client/__init__.py b/src/swagger_client/__init__.py similarity index 100% rename from actions/action/src/swagger_client/__init__.py rename to src/swagger_client/__init__.py diff --git a/actions/action/src/swagger_client/api/__init__.py b/src/swagger_client/api/__init__.py similarity index 100% rename from actions/action/src/swagger_client/api/__init__.py rename to src/swagger_client/api/__init__.py diff --git a/actions/action/src/swagger_client/api/environment_api.py b/src/swagger_client/api/environment_api.py similarity index 100% rename from actions/action/src/swagger_client/api/environment_api.py rename to src/swagger_client/api/environment_api.py diff --git a/actions/action/src/swagger_client/api_client.py b/src/swagger_client/api_client.py similarity index 100% rename from actions/action/src/swagger_client/api_client.py rename to src/swagger_client/api_client.py diff --git a/actions/action/src/swagger_client/configuration.py b/src/swagger_client/configuration.py similarity index 99% rename from actions/action/src/swagger_client/configuration.py rename to src/swagger_client/configuration.py index 1dbeed1..a42d848 100644 --- a/actions/action/src/swagger_client/configuration.py +++ b/src/swagger_client/configuration.py @@ -46,7 +46,7 @@ class Configuration(six.with_metaclass(TypeWithDefault, object)): def __init__(self): """Constructor""" # Default Base url - self.host = "https://shipyard.build" + self.host = "https://shipyard.khulnasoft.com" # Temp file folder for downloading files self.temp_folder_path = None diff --git a/actions/action/src/swagger_client/models/__init__.py b/src/swagger_client/models/__init__.py similarity index 100% rename from actions/action/src/swagger_client/models/__init__.py rename to src/swagger_client/models/__init__.py diff --git a/actions/action/src/swagger_client/models/inline_response200.py b/src/swagger_client/models/inline_response200.py similarity index 100% rename from actions/action/src/swagger_client/models/inline_response200.py rename to src/swagger_client/models/inline_response200.py diff --git a/actions/action/src/swagger_client/models/inline_response2001.py b/src/swagger_client/models/inline_response2001.py similarity index 100% rename from actions/action/src/swagger_client/models/inline_response2001.py rename to src/swagger_client/models/inline_response2001.py diff --git a/actions/action/src/swagger_client/models/inline_response2001_data.py b/src/swagger_client/models/inline_response2001_data.py similarity index 100% rename from actions/action/src/swagger_client/models/inline_response2001_data.py rename to src/swagger_client/models/inline_response2001_data.py diff --git a/actions/action/src/swagger_client/models/inline_response2001_data_attributes.py b/src/swagger_client/models/inline_response2001_data_attributes.py similarity index 100% rename from actions/action/src/swagger_client/models/inline_response2001_data_attributes.py rename to src/swagger_client/models/inline_response2001_data_attributes.py diff --git a/actions/action/src/swagger_client/models/inline_response2001_data_attributes_projects.py b/src/swagger_client/models/inline_response2001_data_attributes_projects.py similarity index 100% rename from actions/action/src/swagger_client/models/inline_response2001_data_attributes_projects.py rename to src/swagger_client/models/inline_response2001_data_attributes_projects.py diff --git a/actions/action/src/swagger_client/models/inline_response2001_data_links.py b/src/swagger_client/models/inline_response2001_data_links.py similarity index 100% rename from actions/action/src/swagger_client/models/inline_response2001_data_links.py rename to src/swagger_client/models/inline_response2001_data_links.py diff --git a/actions/action/src/swagger_client/rest.py b/src/swagger_client/rest.py similarity index 100% rename from actions/action/src/swagger_client/rest.py rename to src/swagger_client/rest.py