def complete(index): try: completed = self._todos[index - 1] completed.complete() clip.echo('Marked todo "{}" as completed'.format(completed._item)) except IndexError: clip.exit('Invalid todo index given', True)
def dump_yaml(path, config): contents = yaml.dump(config, default_flow_style=False) clip.echo('\nAbout to write to {}:\n'.format(os.path.join(os.getcwd(), path))) clip.echo(contents) clip.confirm('Is this okay?', default='yes', abort=True) with open(path, 'w') as f: f.write(contents)
def complete(index): try: completed = self._todos[index - 1] completed.complete() clip.echo('Marked todo "{}" as completed'.format( completed._item)) except IndexError: clip.exit('Invalid todo index given', True)
def download_url(uri, dest): path = uri.split('/')[-1] clip.echo('Downloading file "{}" to "{}"...'.format(path, dest)) res = requests.get(uri, stream=True) with open(os.path.join(dest, path), 'wb') as f: for chunk in res.iter_content(): f.write(chunk) return [path]
def dump_yaml(path, config): contents = yaml.dump(config, default_flow_style=False) clip.echo('\nAbout to write to {}:\n'.format( os.path.join(os.getcwd(), path))) clip.echo(contents) clip.confirm('Is this okay?', default='yes', abort=True) with open(path, 'w') as f: f.write(contents)
def download_gist(uri, dest): gid = GitURL(uri).repo clip.echo('Downloading Gist "{}" to "{}"...'.format(gid, dest)) ret = [] req = requests.get('https://api.github.com/gists/{}'.format(gid)) res = req.json() for k, v in utils.iteritems(res['files']): ret.append(k) with open(os.path.join(dest, k), 'w') as f: f.write(v['content']) return ret
def main(args=None): err = None try: app.run(args) except clip.ClipExit: # Parser-level exception, such as help/version or unrecognized argument pass except Exception as e: err = e clip.echo(e, err=True) finally: # Do any last-minute cleanup pass
def grep(pattern, file, only_matching, ignore_case): inpt = open(file) if file else sys.stdin inpt = inpt.read().splitlines() for line in inpt: if ignore_case: s = re.search(pattern, line, flags=re.IGNORECASE) else: s = re.search(pattern, line) if s is not None: if only_matching: clip.echo(s.group(0)) else: clip.echo(line)
def run(): config = LambdaConfig().load_from_cwd() clip.echo(PROMPT) user_input = { 'FunctionName': clip.prompt('Function name: ', skip=True), 'Handler': clip.prompt('Handler: ', skip=True), 'Description': clip.prompt('Description: ', skip=True), 'Runtime': clip.prompt('Runtime', default='nodejs'), 'Timeout': clip.prompt('Timeout: ', type=int, skip=True), 'MemorySize': clip.prompt('Memory size: ', type=int, skip=True) } config.update_config({k: v for k, v in utils.iteritems(user_input) if v}) install_task = clip.prompt('Install task: ', skip=True) if install_task is not None: config.update({'install': install_task}) config.dump_to_cwd()
def run(uri, kwargs): # Create a temporary working directory tmpdir = None try: tmpdir = tempfile.mkdtemp() uri_type = utils.uri_type(uri) handler = uri_type if uri_type in ['directory', 'file'] else 'download' globals()['handle_{}'.format(handler)](uri, tmpdir, kwargs) except Exception as e: clip.echo('Deployment failed.', err=True) raise e else: clip.echo('Lambda function successfully deployed!') finally: # Clean up our temporary working directory if tmpdir: utils.delete_resource(tmpdir)
def run(): config = LambdaConfig().load_from_cwd() clip.echo(PROMPT) user_input = { 'FunctionName': clip.prompt('Function name: ', skip=True), 'Handler': clip.prompt('Handler: ', skip=True), 'Description': clip.prompt('Description: ', skip=True), 'Runtime': clip.prompt('Runtime', default='nodejs'), 'Timeout': clip.prompt('Timeout: ', type=int, skip=True), 'MemorySize': clip.prompt('Memory size: ', type=int, skip=True) } config.update_config({k: v for k, v in utils.iteritems(user_input) if v}) install_task = clip.prompt('Install task: ', skip=True) if install_task is not None: config.update({ 'install': install_task }) config.dump_to_cwd()
def download_s3(uri, dest): path = uri[3:] clip.echo('Downloading S3 resources at "{}" to "{}"...'.format(path, dest)) ret = [] bucket, subpath = path.split('/', 1) if '/' in path else (path, '') for e in boto3.resource('s3').Bucket(bucket).objects.all(): if e.key.startswith(subpath): if e.key != subpath: resource = e.key.replace(subpath, '', 1) # Strip leading slash, if any if resource.startswith('/'): resource = resource[1:] else: resource = e.key ret.append(resource) body = e.get()['Body'] with open(os.path.join(dest, resource), 'wb') as f: for chunk in iter(lambda: body.read(4096), b''): f.write(chunk) return ret
def run(path, kwargs): # Create a temporary working directory tmpdir = None try: tmpdir = tempfile.mkdtemp() g = GitURL(path) if g.valid: # Git repo url = g.to_ssh() dest = os.path.join(tmpdir, g.repo) clip.echo('Cloning git repo "{}" to "{}"...'.format(url, dest)) git.Repo.clone_from(url, dest) deploy_dir(dest, kwargs) elif os.path.isdir(path): # Directory dest = os.path.join(tmpdir, os.path.basename(path)) clip.echo('Copying directory "{}" to "{}"...'.format(path, dest)) shutil.copytree(path, dest) deploy_dir(dest, kwargs) else: # File dest = os.path.join(tmpdir, os.path.basename(path)) parsed = frontmatter.load(path) clip.echo('Copying file "{}" to "{}"...'.format(path, dest)) with open(dest, 'w') as f: f.write(parsed.content) deploy_file(dest, kwargs, parsed.metadata) finally: # Clean up our temporary working directory if tmpdir: utils.delete_resource(tmpdir)
def test_embedding(self): # Multiple apps (slightly modified for testing) out1 = Stream() out2 = Stream() app1 = clip.App(stdout=out1, name='app1') app2 = clip.App(stdout=out2, name='app2') clip.echo('App 1 via name', app='app1') clip.echo('App 2 via name', app='app2') app1.echo('App 1 directly') app2.echo('App 2 directly') clip.echo('Broadcast!') self.assertEqual( out1._writes, ['App 1 via name\n', 'App 1 directly\n', 'Broadcast!\n']) self.assertEqual( out2._writes, ['App 2 via name\n', 'App 2 directly\n', 'Broadcast!\n'])
def test_embedding(self): # Multiple apps (slightly modified for testing) out1 = Stream() out2 = Stream() app1 = clip.App(stdout=out1, name='app1') app2 = clip.App(stdout=out2, name='app2') clip.echo('App 1 via name', app='app1') clip.echo('App 2 via name', app='app2') app1.echo('App 1 directly') app2.echo('App 2 directly') clip.echo('Broadcast!') self.assertEqual(out1._writes, [ 'App 1 via name\n', 'App 1 directly\n', 'Broadcast!\n' ]) self.assertEqual(out2._writes, [ 'App 2 via name\n', 'App 2 directly\n', 'Broadcast!\n' ])
def x(b): clip.echo('b in x: {}'.format(b))
def view(sorted): clip.echo('This is your {}sorted list'.format('' if sorted else 'un'))
def multiply(numbers, silent): if not silent: clip.echo('Wa-hoo, let\'s-a multiply these numbers!') clip.echo(reduce(lambda x, y: x * y, numbers) if numbers else 0)
def f(numbers): clip.echo(sum(numbers))
def f(needed): clip.echo('Ahh, I needed that.')
def handle_directory(uri, dest, kwargs): clip.echo('Copying directory "{}" to "{}"...'.format(uri, dest)) dir_util.copy_tree(uri, dest) deploy_dir(dest, kwargs)
def f(stuff): clip.echo('You entered: {}'.format(stuff))
def by_short(boop): clip.echo("short " + str(boop))
def f(): clip.echo('Should not be called')
def y(flag): clip.echo(flag, err=True)
def by_name(boop): clip.echo("name " + str(boop))
def f(flag): clip.echo(flag)
def x(): clip.echo('x invoked!')
def f(name): if name: clip.echo('Hello {}!'.format(name))
def z(a, b, c, d): clip.echo('All together now: {}'.format((a, b, c, d)))
def f(t): clip.echo(t)
def fn(): clip.echo('No name provided')
def sub(s, t): clip.echo(s, err=True) clip.echo(t, err=True)
import clip import sys class Stream(object): def __init__(self, f): self._f = f def write(self, message): self._f(message) def stream_a(message): sys.stdout.write('From stream A: {}'.format(message)) def stream_b(message): sys.stdout.write('From stream B: {}'.format(message)) app1 = clip.App(stdout=Stream(stream_a), name='app1') app2 = clip.App(stdout=Stream(stream_b), name='app2') clip.echo('App 1 via name', app='app1') clip.echo('App 2 via name', app='app2') app1.echo('App 1 directly') app2.echo('App 2 directly') clip.echo('Broadcast!')
def f(to_out, to_err): if to_out is not None: clip.echo(to_out) if to_err is not None: clip.echo(to_err, err=True)
def f(name): clip.echo('Hello {}!'.format(name))
def test_echo(self): _, out, _ = self.embed() # Make sure Unicode works properly clip.echo(u'你好') self.assertEqual(out._writes, [u'你好\n'])
def add(item, quantity): clip.echo('Added "{} - {}" to the list'.format(item, quantity))
def upload(params): zipfile = params['FunctionName'] utils.make_zip(zipfile) # Zip up directory with open(zipfile + ".zip", 'rb') as f: zip_bytes = f.read() # Now we're ready to upload! clip.echo('Deploying function "{}"...'.format(zipfile)) client = boto3.client('lambda') upsert = params.pop('upsert', False) try: if upsert: # We can override an existing function, check if we need to try: client.get_function_configuration(FunctionName=zipfile) # If we made it here, we need to update response = client.update_function_code(FunctionName=zipfile, ZipFile=zip_bytes) clip.echo('Update code response: {}'.format( response['ResponseMetadata']['HTTPStatusCode'])) params.pop('Runtime', None) response = client.update_function_configuration(**params) clip.echo('Update configuration response: {}'.format( response['ResponseMetadata']['HTTPStatusCode'])) clip.echo('ARN: {}'.format(response['FunctionArn'])) return except Exception as e: if 'ResourceNotFoundException' not in str(e): raise e # Create the function from scratch params['Code'] = {'ZipFile': zip_bytes} response = client.create_function(**params) clip.echo('Create response: {}'.format( response['ResponseMetadata']['HTTPStatusCode'])) clip.echo('ARN: {}'.format(response['FunctionArn'])) except Exception as e: clip.exit(e, err=True)
def shout(value): clip.echo(' '.join(value).upper())
def sort(sort_type): clip.echo('You selected {}'.format(sort_type))
def add(numbers, silent): if not silent: clip.echo('Add these numbers? Okay, here we gooooo!') clip.echo(sum(numbers))
def x(num): clip.echo('I was invoked with the number {}!'.format(num))
def w(a): clip.echo('a in w: {}'.format(a))
def handle_file(uri, dest, kwargs): dest = os.path.join(dest, os.path.basename(uri)) clip.echo('Copying file "{}" to "{}"...'.format(uri, dest)) shutil.copyfile(uri, dest) deploy_file(dest, kwargs)
def y(a, c): clip.echo('a in y: {}'.format(a)) clip.echo('c in y: {}'.format(c))
def report_field (self, field, value, err = False): if not self.conf.quiet: clip.echo ("%s: %s" % ( self.colourise (field, COLOUR_FIELDNAME), self.colourise (value, COLOUR_VALUE if not err else COLOUR_ERROR),))
def option_version(opt): # pylint: disable=unused-argument clip.echo("Version: %s" % __version__) sys.exit(0)
def f(number): clip.echo('Hey there {}'.format(number)) return 42 * number
def echo(words): clip.echo(' '.join(words))
def warn (self, msg): if not self.conf.quiet and not self.conf.only: clip.echo (self.colourise ("WARNING: " + msg, COLOUR_WARN))
def by_long(boop): clip.echo("long " + str(boop))
def report (self, msg, err = False): if not self.conf.quiet: clip.echo (self.colourise (msg, COLOUR_REPORT if not err else COLOUR_ERROR))