def link_to_deploy_target(valid_token=None): term = get_term() if not valid_token: raise ValueError("A valid token is required!") project_id = get_value(VALUE_PROJECT_ID, print_warnings=False) if not project_id: puts( term.red("Error: ") + "No application found. Please create or link an application first" ) return target = pick_target(valid_token, project_id) if not target: return wercker_url = get_value(VALUE_WERCKER_URL) link = "{wercker_url}/deploytarget/{target}".format( wercker_url=wercker_url, target=target ) puts("Opening link: {link}".format(link=link)) import webbrowser webbrowser.open(link)
def link_to_deploy_target(valid_token=None): term = get_term() if not valid_token: raise ValueError("A valid token is required!") project_id = get_value(VALUE_PROJECT_ID, print_warnings=False) if not project_id: puts( term.red("Error: ") + "No application found. Please create or link an application first") return target = pick_target(valid_token, project_id) if not target: return wercker_url = get_value(VALUE_WERCKER_URL) link = "{wercker_url}/deploytarget/{target}".format( wercker_url=wercker_url, target=target) puts("Opening link: {link}".format(link=link)) import webbrowser webbrowser.open(link)
def test_get_value_wercker_url(self): os.environ[ENV_KEY_WERCKER_URL] = self.wercker_url result = config.get_value(config.VALUE_WERCKER_URL) self.assertEqual(result, self.wercker_url) del os.environ[ENV_KEY_WERCKER_URL] result = config.get_value(config.VALUE_WERCKER_URL) self.assertEqual(result, config.DEFAULT_WERCKER_URL)
def test_get_value_user_token(self): with mock.patch("werckercli.config.puts", mock.Mock()): # reload(config) result = config.get_value(config.VALUE_USER_TOKEN) self.assertEqual(result, "'1234567890123456789912345678901234567890'")
def test_set_value_user_token(self): with mock.patch("werckercli.config.puts", mock.Mock()): # reload(config) config.set_value(config.VALUE_USER_TOKEN, "test@password") self.assertEqual(config.get_value(config.VALUE_USER_TOKEN), 'test@password')
def puts(content, level=INFO): if level == INFO: terminal_file_handle.write(content.encode("utf-8") + '\n') elif level == DEBUG: from werckercli import config if config.get_value(config.VALUE_DISPLAY_DEBUG): terminal_file_handle.write("debug:: " + content.encode("utf-8") + '\n')
def test_set_value_user_token(self): with mock.patch("werckercli.config.puts", mock.Mock()): # reload(config) config.set_value(config.VALUE_USER_TOKEN, "test@password") self.assertEqual( config.get_value(config.VALUE_USER_TOKEN), 'test@password' )
def puts(content, level=INFO): if level == INFO: terminal_file_handle.write( content.encode("utf-8") + '\n' ) elif level == DEBUG: from werckercli import config if config.get_value(config.VALUE_DISPLAY_DEBUG): terminal_file_handle.write( "debug:: " + content.encode("utf-8") + '\n' )
def project_list_queue(valid_token=None): term = get_term() if not valid_token: raise ValueError("A valid token is required!") project_id = get_value(VALUE_PROJECT_ID, print_warnings=False) if not project_id: puts( term.red("Error: ") + "No application found. Please create or link an application first" ) return term = get_term() puts("Retrieving list of unfinished builds.") result = get_builds(valid_token, project_id) unknowns = filter(lambda r: r['result'] == "unknown", result) print_builds(unknowns) # print unknowns result = get_targets(valid_token, project_id) for target in result['data']: # print target['id'] c = Client() code, deploys = c.get_deploys(valid_token, target['id']) # print result # puts("Target: " + term.yellow(target['name'])) if 'data' in deploys: unknowns = filter( lambda d: d['result'] == 'unknown', deploys['data'] ) puts(("\nFound {amount} scheduled deploys for {target}").format( amount=len(unknowns), target=term.white(target['name']) )) print_deploys(unknowns) else: puts("\nNo scheduled deploys found.")
def get_access_token(): token = get_value(VALUE_USER_TOKEN) if not token: token = do_login() if not token: return set_value(VALUE_USER_TOKEN, token) return token
def project_open(): project_id = get_value(VALUE_PROJECT_ID, print_warnings=False) term = get_term() if not project_id: puts( term.red("Error: ") + "No application found. Please create or link an application first" ) return wercker_url = get_value(VALUE_WERCKER_URL) link = "{wercker_url}/#project/{project_id}".format( wercker_url=wercker_url, project_id=project_id ) puts("Opening link: {link}".format(link=link)) import webbrowser webbrowser.open(link)
def test_get_value_heroku_token(self): with mock.patch("werckercli.config.puts", mock.Mock()) as puts: # reload(config) result = config.get_value(config.VALUE_HEROKU_TOKEN) self.assertEqual(puts.call_count, 1) calls = puts.call_args_list self.assertTrue('0600' in calls[0][0][0]) self.assertEqual(result, '1234567890123456789912345678901234567890') os.environ.pop('HOME') self.assertRaises(IOError, config.get_value, config.VALUE_HEROKU_TOKEN)
def list_by_project(valid_token=None): term = get_term() if not valid_token: raise ValueError("A valid token is required!") project_id = get_value(VALUE_PROJECT_ID, print_warnings=False) if not project_id: puts( term.red("Error: ") + "No application found. Please create or link an application first") return targets = get_targets(valid_token, project_id) print_targets(targets)
def list_by_project(valid_token=None): term = get_term() if not valid_token: raise ValueError("A valid token is required!") project_id = get_value(VALUE_PROJECT_ID, print_warnings=False) if not project_id: puts( term.red("Error: ") + "No application found. Please create or link an application first" ) return targets = get_targets(valid_token, project_id) print_targets(targets)
def add(valid_token=None): term = get_term() if not valid_token: raise ValueError("A valid token is required!") project_id = get_value(VALUE_PROJECT_ID, print_warnings=False) if not project_id: puts( term.red("Error: ") + "No application found. Please create or link an application first") return options = git.find_heroku_sources(os.curdir) if len(options) == 0: puts(term.red("Error: ") + "No heroku remotes found") elif len(options) == 1: _add_heroku_by_git(valid_token, project_id, options[0].url)
def build_list(valid_token=None, limit=5): term = get_term() if not valid_token: raise ValueError("A valid token is required!") projectId = get_value(VALUE_PROJECT_ID, print_warnings=False) if not projectId: puts( term.red("Error: ") + "No application found. Please create or link an application first") return builds = get_builds(valid_token, projectId) print_builds(builds, limit=limit)
def add(valid_token=None): term = get_term() if not valid_token: raise ValueError("A valid token is required!") project_id = get_value(VALUE_PROJECT_ID, print_warnings=False) if not project_id: puts( term.red("Error: ") + "No application found. Please create or link an application first" ) return options = git.find_heroku_sources(os.curdir) if len(options) == 0: puts(term.red("Error: ") + "No heroku remotes found") elif len(options) == 1: _add_heroku_by_git(valid_token, project_id, options[0].url)
def build_list(valid_token=None, limit=5): term = get_term() if not valid_token: raise ValueError("A valid token is required!") projectId = get_value(VALUE_PROJECT_ID, print_warnings=False) if not projectId: puts( term.red("Error: ") + "No application found. Please create or link an application first" ) return builds = get_builds(valid_token, projectId) print_builds(builds, limit=limit)
def clear_settings(): term = get_term() # home = get_global_wercker_path() # print home if config.get_value(config.VALUE_USER_TOKEN): puts("""About to clear the wercker settings \ for the current user on this machine""") sure = prompt.yn("Are you sure you want to do this?", default="n") if sure: # shutil.rmtree(get_global_wercker_path()) config.set_value(config.VALUE_USER_TOKEN, None) puts( term.green("Success: ") + "wercker settings removed succesfully.") return True else: puts(term.yellow("Warning: ") + "Cancelled.") else: puts(term.yellow("Warning: ") + "No settings found.")
def clear_settings(): term = get_term() # home = get_global_wercker_path() # print home if config.get_value(config.VALUE_USER_TOKEN): puts( """About to clear the wercker settings \ for the current user on this machine""" ) sure = prompt.yn("Are you sure you want to do this?", default="n") if sure: # shutil.rmtree(get_global_wercker_path()) config.set_value(config.VALUE_USER_TOKEN, None) puts(term.green("Success: ") + "wercker settings removed succesfully.") return True else: puts(term.yellow("Warning: ") + "Cancelled.") else: puts(term.yellow("Warning: ") + "No settings found.")
def project_build(valid_token=None): if not valid_token: raise ValueError("A valid token is required!") term = get_term() puts("Triggering a new build.") c = Client() code, response = c.trigger_build(valid_token, get_value(VALUE_PROJECT_ID)) if response['success'] is False: if "errorMessage" in response: puts(term.red("Error: ") + response['errorMessage']) else: puts("Unable to trigger a build on the default/master branch") return False else: puts("done.") return True
def project_build(valid_token=None): if not valid_token: raise ValueError("A valid token is required!") term = get_term() puts("Triggering build") c = Client() code, response = c.trigger_build(valid_token, get_value(VALUE_PROJECT_ID)) if response['success'] is False: if "errorMessage" in response: puts(term.red("Error: ") + response['errorMessage']) else: puts("Unable to trigger a build on the default/master branch") return False else: puts("A new build has been created") return True
def __init__(self): self.wercker_url = get_value(VALUE_WERCKER_URL)
class Client(LegacyClient): wercker_url = get_value(VALUE_WERCKER_URL) def do_get(self, path, data, display_warnings=True): url = self.wercker_url + "/api/" + path puts("communicating with %s ..." % url, level=DEBUG) result = requests.get(url, params=data) puts("done...", level=DEBUG) status = result.status_code result_json = {} try: result_json = result.json() except ValueError: if display_warnings: term = get_term() puts( term.yellow("Warning: ") + "Invalid response for api call: {url}".format(url=url)) return status, result_json def get_applications(self, token): return self.do_get(PATH_GET_APPLICATIONS, {'token': token}) def get_builds(self, token, project): return self.do_get(PATH_GET_BUILDS.format(projectId=project), {'token': token}) def check_permissions(self, token, project): return self.do_get(PATH_CHECK_PERMISSIONS.format(projectId=project), {'token': token}) def get_deploys(self, token, deploy_target_id): return self.do_get( PATH_GET_DEPLOYS.format(deployTargetId=deploy_target_id), {'token': token}) def get_profile(self, token): return self.do_get(PATH_GET_PROFILE, {'token': token}) def get_profile_detailed(self, token, username): return self.do_get(PATH_GET_DETAILED_PROFILE.format(username=username), {'token': token}) def get_boxes(self): return self.do_get(PATH_SEARCH_BOXES, {}) def get_checkout_key(self): return self.do_post(PATH_CREATE_CHECKOUTKEY, {}) def get_box_releases(self, name, display_warnings=False): return self.do_get(PATH_BOX_INFO_RELEASES.format(name=name), {}, display_warnings=display_warnings) def get_box(self, name, version=0, display_warnings=False): return self.do_get(PATH_BOX_INFO_AT_VERSION.format(name=name, version=version), {}, display_warnings=display_warnings) def create_project(self, token, owner, name, source_control, checkout_key_id): return self.do_post( self.wercker_url + '/api/' + PATH_CREATE_PROJECT.format(token=token), { 'scmOwner': owner, 'scmName': name, 'scmProvider': source_control, 'privacy': 'private', 'checkoutKeyId': checkout_key_id, 'token': token, }) def create_checkout_key(self): return self.do_post( self.wercker_url + '/api/' + PATH_CREATE_CHECKOUTKEY, {}) def link_checkout_key(self, token, checkout_key_id, username, project, scm_provider): return self.do_post( self.wercker_url + '/api/' + PATH_LINK_CHECKOUT_KEY.format( checkoutKeyId=checkout_key_id, token=token), { 'scmProvider': scm_provider, 'scmOwner': username, 'scmName': project, })
def test_get_value_project_id(self): os.chdir(self.get_git_path()) result = config.get_value(config.VALUE_PROJECT_ID) self.assertEqual(result, None)
def create(path='.', valid_token=None): if not valid_token: raise ValueError("A valid token is required!") term = get_term() if get_value(VALUE_PROJECT_ID, print_warnings=False): puts("A .wercker file was found.") run_create = prompt.yn( "Are you sure you want to run `wercker create`?", default="n") if run_create is False: puts("Aborting.") return else: puts("") if project_link( valid_token=valid_token, puts_result=False, auto_link=False ): puts("A matching application was found on wercker.") use_link = prompt.yn("Do you want to run 'wercker link' instead of\ `wercker create`?") puts("") if use_link is True: project_link(valid_token=valid_token) return path = find_git_root(path) if path: options = get_remote_options(path) heroku_options = filter_heroku_sources(options) else: options = [] heroku_options = [] if not path: return False puts('''About to create an application on wercker. This consists of the following steps: 1. Validate permissions and create an application 2. Add a deploy target ({heroku_options} heroku targets detected) 3. Trigger initial build'''.format( wercker_url=get_value(VALUE_WERCKER_URL), heroku_options=len(heroku_options)) ) if not path: puts( term.red("Error:") + " Could not find a repository." + " wercker create requires a git repository. Create/clone a\ repository first." ) return options = [o for o in options if o not in heroku_options] options = [o for o in options if o.priority > 1] count = len(options) puts(''' Step ''' + term.white('1') + '''. ------------- ''') puts( "Found %s repository location(s)...\n" % term.white(str(count)) ) url = pick_url(options) url = convert_to_url(url) source = get_preferred_source_type(url) puts("\n%s repository detected..." % source) puts("Selected repository url is %s\n" % url) client = Client() code, profile = client.get_profile(valid_token) source_type = get_source_type(url) if source_type == SOURCE_BITBUCKET: if profile.get('hasBitbucketToken', False) is False: puts("No Bitbucket account linked with your profile. Wercker uses\ this connection to linkup some events for your repository on Bitbucket to our\ service.") provider_url = get_value( VALUE_WERCKER_URL ) + '/provider/add/cli/bitbucket' puts("Launching {url} to start linking.".format( url=provider_url )) from time import sleep sleep(5) import webbrowser webbrowser.open(provider_url) raw_input("Press enter to continue...") elif source_type == SOURCE_GITHUB: if profile.get('hasGithubToken', False) is False: puts("No GitHub account linked with your profile. Wercker uses\ this connection to linkup some events for your repository on GitHub to our\ service.") provider_url = get_value( VALUE_WERCKER_URL ) + '/provider/add/cli/github' puts("Launching {url} to start linking.".format( url=provider_url )) from time import sleep sleep(5) import webbrowser webbrowser.open(provider_url) raw_input("Press enter to continue...") puts("Creating a new application") status, response = client.create_project( url, source, valid_token ) if response['success']: puts("a new application has been created.") set_value(VALUE_PROJECT_ID, response['projectId']) puts("In the root of this repository a .wercker file has been created\ which enables the link between the source code and wercker.\n") site_url = None if source_type == SOURCE_GITHUB: site_url = "https://github.com/" + \ get_username(url) + \ "/" + \ get_project(url) elif source_type == SOURCE_BITBUCKET: site_url = "https://bitbucket.org/" + \ get_username(url) + \ "/" + \ get_project(url) project_check_repo( valid_token=valid_token, failure_confirmation=True, site_url=site_url ) # puts("\nSearching for deploy target information (for \ # platforms such as Heroku).") puts(''' Step ''' + term.white('2') + '''. ------------- ''') target_options = heroku_options nr_targets = len(target_options) puts("%s automatic supported target(s) found." % str(nr_targets)) if nr_targets: target_add(valid_token=valid_token) puts(''' Step ''' + term.white('3') + '''. ------------- ''') project_build(valid_token=valid_token) # if project_build(valid_token=valid_token): # puts("To trigger a build") # puts("") puts(''' Done. ------------- You are all set up to for using wercker. You can trigger new builds by committing and pushing your latest changes. Happy coding!''') else: puts( term.red("Error: ") + "Unable to create project. \n\nResponse: %s\n" % (response.get('errorMessage')) ) puts(''' Note: only repository where the wercker's user has permissions on can be added. This is because some event hooks for wercker need to be registered on the repository. If you want to test a public repository and don't have permissions on it: fork it. You can add the forked repository to wercker''')
def create(path='.', valid_token=None): if not valid_token: raise ValueError("A valid token is required!") term = get_term() if get_value(VALUE_PROJECT_ID, print_warnings=False): puts("A .wercker file was found.") run_create = prompt.yn( "Are you sure you want to run `wercker create`?", default="n") if run_create is False: puts("Aborting.") return else: puts("") if project_link( valid_token=valid_token, puts_result=False, auto_link=False ): puts("A matching application was found on wercker.") use_link = prompt.yn("Do you want to run 'wercker link' instead of\ `wercker create`?") puts("") if use_link is True: project_link(valid_token=valid_token) return path = find_git_root(path) if path: options = get_remote_options(path) heroku_options = filter_heroku_sources(options) else: options = [] heroku_options = [] if not path: return False puts('''About to create an application on wercker. This consists of the following steps: 1. Configure application 2. Setup keys 3. Add a deploy target ({heroku_options} heroku targets detected) 4. Trigger initial build'''.format( wercker_url=get_value(VALUE_WERCKER_URL), heroku_options=len(heroku_options)) ) if not path: puts( term.red("Error:") + " Could not find a repository." + " wercker create requires a git repository. Create/clone a\ repository first." ) return options = [o for o in options if o not in heroku_options] options = [o for o in options if o.priority > 1] count = len(options) puts(''' Step ''' + term.white('1') + '''. Configure application ------------- ''') puts( "%s repository location(s) found...\n" % term.bold(str(count)) ) url = pick_url(options) url = convert_to_url(url) source = get_preferred_source_type(url) puts("\n%s repository detected..." % source) puts("Selected repository url is %s\n" % url) client = Client() code, profile = client.get_profile(valid_token) source_type = get_source_type(url) if source_type == SOURCE_BITBUCKET: if profile.get('hasBitbucketToken', False) is False: puts("No Bitbucket account linked with your profile. Wercker uses\ this connection to linkup some events for your repository on Bitbucket to our\ service.") provider_url = get_value( VALUE_WERCKER_URL ) + '/provider/add/cli/bitbucket' puts("Launching {url} to start linking.".format( url=provider_url )) from time import sleep sleep(5) import webbrowser webbrowser.open(provider_url) raw_input("Press enter to continue...") elif source_type == SOURCE_GITHUB: if profile.get('hasGithubToken', False) is False: puts("No GitHub account linked with your profile. Wercker uses\ this connection to linkup some events for your repository on GitHub to our\ service.") provider_url = get_value( VALUE_WERCKER_URL ) + '/provider/add/cli/github' puts("Launching {url} to start linking.".format( url=provider_url )) from time import sleep sleep(5) import webbrowser webbrowser.open(provider_url) raw_input("Press enter to continue...") username = get_username(url) project = get_project(url) puts(''' Step {t.white}2{t.normal}. ------------- In order to clone the repository on wercker, an ssh key is needed. A new/unique key can be generated for each repository. There 3 ways of using ssh keys on wercker: {t.green}1. Automatically add a deploy key [recommended]{t.normal} 2. Use the checkout key, wercker uses for public projects. 3. Let wercker generate a key, but allow add it manually to github/bitbucket. (needed when using git submodules) For more information on this see: http://etc... '''.format(t=term)) key_method = None while(True): result = prompt.get_value_with_default( "Options:", '1' ) valid_values = [str(i + 1) for i in range(3)] if result in valid_values: key_method = valid_values.index(result) break else: puts(term.red("warning: ") + " invalid build selected.") checkout_key_id = None checkout_key_publicKey = None if(key_method != 1): puts('''Retrieving a new ssh-key.''') status, response = client.create_checkout_key() puts("done.") if status == 200: checkout_key_id = response['id'] checkout_key_publicKey = response['publicKey'] if key_method == 0: puts('Adding deploy key to repository:') status, response = client.link_checkout_key(valid_token, checkout_key_id, username, project, source_type) if status != 200: puts(term.red("Error:") + " uanble to add key to repository.") sys.exit(1) elif key_method == 2: profile_username = profile.get('username') status, response = client.get_profile_detailed( valid_token, profile_username) username = response[source_type + 'Username'] url = None if source_type == SOURCE_GITHUB: url = "https://github.com/settings/ssh" elif source_type == SOURCE_BITBUCKET: url = "http://bitbucket.org/account/user/{username}/\ ssh-keys/" if status == 200: formatted_key = "\n".join( textwrap.wrap(checkout_key_publicKey)) puts('''Please add the following public key: {publicKey} You can add the key here: {url}\n'''.format(publicKey=formatted_key, url=url.format( username=username))) raw_input("Press enter to continue...") else: puts(term.red("Error:") + " unable to load wercker profile information.") sys.exit(1) else: puts(term.red("Error:") + 'unable to retrieve an ssh key.') sys.exit(1) puts("Creating a new application") status, response = client.create_project( valid_token, username, project, source, checkout_key_id, ) if response['success']: puts("done.\n") set_value(VALUE_PROJECT_ID, response['data']['id']) puts("In the root of this repository a .wercker file has been created\ which enables the link between the source code and wercker.\n") site_url = None if source_type == SOURCE_GITHUB: site_url = "https://github.com/" + \ username + \ "/" + \ project elif source_type == SOURCE_BITBUCKET: site_url = "https://bitbucket.org/" + \ username + \ "/" + \ project puts(''' Step ''' + term.white('3') + '''. ------------- ''') target_options = heroku_options nr_targets = len(target_options) puts("%s automatic supported target(s) found." % str(nr_targets)) if nr_targets: target_add(valid_token=valid_token) puts(''' Step ''' + term.white('4') + '''. ------------- ''') project_build(valid_token=valid_token) puts(''' Done. ------------- You are all set up to for using wercker. You can trigger new builds by committing and pushing your latest changes. Happy coding!''') else: puts( term.red("Error: ") + "Unable to create project. \n\nResponse: %s\n" % (response.get('errorMessage')) ) puts(''' Note: only repository where the wercker's user has permissions on can be added. This is because some event hooks for wercker need to be registered on the repository. If you want to test a public repository and don't have permissions on it: fork it. You can add the forked repository to wercker''')
def build_deploy(valid_token=None): if not valid_token: raise ValueError("A valid token is required!") term = get_term() projectId = get_value(VALUE_PROJECT_ID, print_warnings=False) if not projectId: puts( term.red("Error: ") + "No application found. Please create or link an application first") return builds = get_builds(valid_token, projectId) if type(builds) is not list or len(builds) == 0: puts(term.yellow("warning: ") + "No builds found.") return passed_builds = [build for build in builds if build['result'] == "passed"] if len(passed_builds) == 0: puts("No passed deploys found.") print_builds(passed_builds, print_index=True) deploy_index = -1 target_index = -1 while (True): result = get_value_with_default("Select which build to deploy", '1') valid_values = [str(i + 1) for i in range(len(passed_builds))] # valid_values = range(1, len(passed_builds) + 1) # print valid_values, result if result in valid_values: deploy_index = valid_values.index(result) break else: puts(term.red("warning: ") + " invalid build selected.") target_index = pick_target(valid_token, projectId) c = Client() code, result = c.do_deploy(valid_token, passed_builds[deploy_index]['id'], target_index) if "success" in result and result['success'] is True: puts( term.green("Success: ") + """ Build scheduled for deploy. You can monitor the scheduled deploy in your browser using: {command_targets_deploy} Or query the queue for this application using: {command_queue}""".format(command_targets_deploy=term.white( "wercker targets deploy"), command_queue=term.white("wercker queue"))) else: puts(term.red("Error: ") + "Unable to schedule deploy")
def create(path=".", valid_token=None): if not valid_token: raise ValueError("A valid token is required!") term = get_term() if get_value(VALUE_PROJECT_ID, print_warnings=False): puts("A .wercker file was found.") run_create = prompt.yn("Are you sure you want to run `wercker create`?", default="n") if run_create is False: puts("Aborting.") return else: puts("") if project_link(valid_token=valid_token, puts_result=False, auto_link=False): puts("A matching application was found on wercker.") use_link = prompt.yn( "Do you want to run 'wercker link' instead of\ `wercker create`?" ) puts("") if use_link is True: project_link(valid_token=valid_token) return path = find_git_root(path) if path: options = get_remote_options(path) heroku_options = filter_heroku_sources(options) else: options = [] heroku_options = [] if not path: return False puts( """About to create an application on wercker. This consists of the following steps: 1. Configure application 2. Setup keys 3. Add a deploy target ({heroku_options} heroku targets detected) 4. Trigger initial build""".format( wercker_url=get_value(VALUE_WERCKER_URL), heroku_options=len(heroku_options) ) ) if not path: puts( term.red("Error:") + " Could not find a repository." + " wercker create requires a git repository. Create/clone a\ repository first." ) return options = [o for o in options if o not in heroku_options] options = [o for o in options if o.priority > 1] count = len(options) puts( """ Step """ + term.white("1") + """. Configure application ------------- """ ) puts("%s repository location(s) found...\n" % term.bold(str(count))) url = pick_url(options) url = convert_to_url(url) source = get_preferred_source_type(url) puts("\n%s repository detected..." % source) puts("Selected repository url is %s\n" % url) client = Client() code, profile = client.get_profile(valid_token) source_type = get_source_type(url) if source_type == SOURCE_BITBUCKET: if profile.get("hasBitbucketToken", False) is False: puts( "No Bitbucket account linked with your profile. Wercker uses\ this connection to linkup some events for your repository on Bitbucket to our\ service." ) provider_url = get_value(VALUE_WERCKER_URL) + "/provider/add/cli/bitbucket" puts("Launching {url} to start linking.".format(url=provider_url)) from time import sleep sleep(5) import webbrowser webbrowser.open(provider_url) raw_input("Press enter to continue...") elif source_type == SOURCE_GITHUB: if profile.get("hasGithubToken", False) is False: puts( "No GitHub account linked with your profile. Wercker uses\ this connection to linkup some events for your repository on GitHub to our\ service." ) provider_url = get_value(VALUE_WERCKER_URL) + "/provider/add/cli/github" puts("Launching {url} to start linking.".format(url=provider_url)) from time import sleep sleep(5) import webbrowser webbrowser.open(provider_url) raw_input("Press enter to continue...") username = get_username(url) project = get_project(url) puts( """ Step {t.white}2{t.normal}. ------------- In order to clone the repository on wercker, an ssh key is needed. A new/unique key can be generated for each repository. There 3 ways of using ssh keys on wercker: {t.green}1. Automatically add a deploy key [recommended]{t.normal} 2. Use the checkout key, wercker uses for public projects. 3. Let wercker generate a key, but allow add it manually to github/bitbucket. (needed when using git submodules) For more information on this see: http://etc... """.format( t=term ) ) key_method = None while True: result = prompt.get_value_with_default("Options:", "1") valid_values = [str(i + 1) for i in range(3)] if result in valid_values: key_method = valid_values.index(result) break else: puts(term.red("warning: ") + " invalid build selected.") checkout_key_id = None checkout_key_publicKey = None if key_method != 1: puts("""Retrieving a new ssh-key.""") status, response = client.create_checkout_key() puts("done.") if status == 200: checkout_key_id = response["id"] checkout_key_publicKey = response["publicKey"] if key_method == 0: puts("Adding deploy key to repository:") status, response = client.link_checkout_key( valid_token, checkout_key_id, username, project, source_type ) if status != 200: puts(term.red("Error:") + " uanble to add key to repository.") sys.exit(1) elif key_method == 2: profile_username = profile.get("username") status, response = client.get_profile_detailed(valid_token, profile_username) username = response[source_type + "Username"] url = None if source_type == SOURCE_GITHUB: url = "https://github.com/settings/ssh" elif source_type == SOURCE_BITBUCKET: url = "http://bitbucket.org/account/user/{username}/\ ssh-keys/" if status == 200: formatted_key = "\n".join(textwrap.wrap(checkout_key_publicKey)) puts( """Please add the following public key: {publicKey} You can add the key here: {url}\n""".format( publicKey=formatted_key, url=url.format(username=username) ) ) raw_input("Press enter to continue...") else: puts(term.red("Error:") + " unable to load wercker profile information.") sys.exit(1) else: puts(term.red("Error:") + "unable to retrieve an ssh key.") sys.exit(1) puts("Creating a new application") status, response = client.create_project(valid_token, username, project, source, checkout_key_id) if response["success"]: puts("done.\n") set_value(VALUE_PROJECT_ID, response["data"]["id"]) puts( "In the root of this repository a .wercker file has been created\ which enables the link between the source code and wercker.\n" ) site_url = None if source_type == SOURCE_GITHUB: site_url = "https://github.com/" + username + "/" + project elif source_type == SOURCE_BITBUCKET: site_url = "https://bitbucket.org/" + username + "/" + project puts( """ Step """ + term.white("3") + """. ------------- """ ) target_options = heroku_options nr_targets = len(target_options) puts("%s automatic supported target(s) found." % str(nr_targets)) if nr_targets: target_add(valid_token=valid_token) puts( """ Step """ + term.white("4") + """. ------------- """ ) project_build(valid_token=valid_token) puts( """ Done. ------------- You are all set up to for using wercker. You can trigger new builds by committing and pushing your latest changes. Happy coding!""" ) else: puts(term.red("Error: ") + "Unable to create project. \n\nResponse: %s\n" % (response.get("errorMessage"))) puts( """ Note: only repository where the wercker's user has permissions on can be added. This is because some event hooks for wercker need to be registered on the repository. If you want to test a public repository and don't have permissions on it: fork it. You can add the forked repository to wercker""" )
def build_deploy(valid_token=None): if not valid_token: raise ValueError("A valid token is required!") term = get_term() projectId = get_value(VALUE_PROJECT_ID, print_warnings=False) if not projectId: puts( term.red("Error: ") + "No application found. Please create or link an application first" ) return builds = get_builds(valid_token, projectId) if type(builds) is not list or len(builds) == 0: puts(term.yellow("warning: ") + "No builds found.") return passed_builds = [build for build in builds if build['result'] == "passed"] if len(passed_builds) == 0: puts("No passed deploys found.") print_builds(passed_builds, print_index=True) deploy_index = -1 target_index = -1 while(True): result = get_value_with_default("Select which build to deploy", '1') valid_values = [str(i + 1) for i in range(len(passed_builds))] # valid_values = range(1, len(passed_builds) + 1) # print valid_values, result if result in valid_values: deploy_index = valid_values.index(result) break else: puts(term.red("warning: ") + " invalid build selected.") target_index = pick_target(valid_token, projectId) c = Client() code, result = c.do_deploy( valid_token, passed_builds[deploy_index]['id'], target_index ) if "success" in result and result['success'] is True: puts(term.green("Success: ") + """ Build scheduled for deploy. You can monitor the scheduled deploy in your browser using: {command_targets_deploy} Or query the queue for this application using: {command_queue}""".format( command_targets_deploy=term.white("wercker targets deploy"), command_queue=term.white("wercker queue"))) else: puts(term.red("Error: ") + "Unable to schedule deploy")
class LegacyClient(): wercker_url = get_value(VALUE_WERCKER_URL) api_version = '1.0' def __init__(self): self.wercker_url = get_value(VALUE_WERCKER_URL) def do_post(self, url, data): """Make the request to the server.""" data_string = json.dumps(data) puts("communicating with %s ..." % url, level=DEBUG) result = requests.post(url, data=data_string, headers={'Content-Type': 'application/json'}) puts("done...", level=DEBUG) return result.status_code, json.loads(result.text) def build_versioned_url(self, path, api_version=None): if api_version is None: api_version = self.api_version return self.wercker_url + '/api/' + api_version + '/' + path def request_oauth_token(self, username, password, scope='cli'): """Request oauth token""" return self.do_post(self.build_versioned_url(PATH_BASIC_ACCESS_TOKEN), { 'username': username, 'password': password, 'oauthScope': scope }) def create_deploy_target(self, token, project, deploy_name, heroku_token): return self.do_post( self.build_versioned_url(PATH_CREATE_DEPLOYTARGET), { 'token': token, 'projectId': project, 'appName': deploy_name, 'apiKey': heroku_token, }) def get_deploy_targets_by_project(self, token, project): return self.do_post( self.build_versioned_url(PATH_DEPLOY_TARGETS_BY_PROJECT), { 'token': token, 'projectId': project }) def trigger_build(self, token, project): return self.do_post(self.build_versioned_url(PATH_BUILD_PROJECT), { 'token': token, 'projectId': project }) def do_deploy(self, token, build, deploy_target): return self.do_post(self.build_versioned_url(PATH_DEPLOY), { 'token': token, 'targetId': deploy_target, 'buildId': build })
def project_check_repo( valid_token=None, failure_confirmation=False, site_url=None ): if not valid_token: raise ValueError("A valid token is required!") term = get_term() puts("Checking werckerbot permissions on the repository...") while(True): c = Client() code, response = c.check_permissions( valid_token, get_value(VALUE_PROJECT_ID) ) if response['success'] is True: if response['data']['hasAccess'] is True: puts("Werckerbot has access") break else: puts("") # empty line... if "details" in response['data']: # puts puts( term.yellow("Error: ") + response['data']['details'] ) else: puts( term.red("Error: ") + "wercker's werckerbot has no access to this\ repository." ) if failure_confirmation is True: puts("werckerbot needs pull/read access to the repository \ to get the code.") puts("Without access to the repository, builds and tests\ will fail.\n") if(site_url): puts("Go to {url} and add wercker as a collaborator\ ".format(url=site_url)) exit = not prompt.yn( "Do you want wercker to check the permissions again?", default="y" ) else: exit = True if exit: break else: puts(term.red("Error: ") + "Could not validate access...") if failure_confirmation is True: puts("werckerbot needs pull/read access to the repository \ to get the code.") puts("Without access to the repository, builds and tests\ will fail.\n") if(site_url): puts("Go to {url} and add wercker as a collaborator\ ".format(url=site_url)) exit = not prompt.yn( "Do you want wercker to check the permissions again?", default="y" ) else: break