Beispiel #1
0
		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)
Beispiel #2
0
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)
Beispiel #3
0
 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)
Beispiel #4
0
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]
Beispiel #5
0
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]
Beispiel #6
0
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)
Beispiel #7
0
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
Beispiel #8
0
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
Beispiel #9
0
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
Beispiel #10
0
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
Beispiel #11
0
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)
Beispiel #12
0
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)
Beispiel #13
0
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()
Beispiel #14
0
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)
Beispiel #15
0
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)
Beispiel #16
0
Datei: init.py Projekt: T2BE/lfm
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()
Beispiel #17
0
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
Beispiel #18
0
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
Beispiel #19
0
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)
Beispiel #20
0
 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'])
Beispiel #21
0
	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'
		])
Beispiel #22
0
		def x(b):
			clip.echo('b in x: {}'.format(b))
Beispiel #23
0
		def view(sorted):
			clip.echo('This is your {}sorted list'.format('' if sorted else 'un'))
Beispiel #24
0
		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)
Beispiel #25
0
		def f(numbers):
			clip.echo(sum(numbers))
Beispiel #26
0
		def f(needed):
			clip.echo('Ahh, I needed that.')
Beispiel #27
0
def handle_directory(uri, dest, kwargs):
    clip.echo('Copying directory "{}" to "{}"...'.format(uri, dest))
    dir_util.copy_tree(uri, dest)
    deploy_dir(dest, kwargs)
Beispiel #28
0
		def f(stuff):
			clip.echo('You entered: {}'.format(stuff))
Beispiel #29
0
 def by_short(boop):
     clip.echo("short " + str(boop))
Beispiel #30
0
 def f():
     clip.echo('Should not be called')
Beispiel #31
0
 def y(flag):
     clip.echo(flag, err=True)
Beispiel #32
0
 def by_name(boop):
     clip.echo("name " + str(boop))
Beispiel #33
0
 def f(flag):
     clip.echo(flag)
Beispiel #34
0
 def x():
     clip.echo('x invoked!')
Beispiel #35
0
 def f(name):
     if name:
         clip.echo('Hello {}!'.format(name))
Beispiel #36
0
		def z(a, b, c, d):
			clip.echo('All together now: {}'.format((a, b, c, d)))
Beispiel #37
0
 def f(t):
     clip.echo(t)
Beispiel #38
0
 def fn():
     clip.echo('No name provided')
Beispiel #39
0
 def sub(s, t):
     clip.echo(s, err=True)
     clip.echo(t, err=True)
Beispiel #40
0
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!')
Beispiel #41
0
 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)
Beispiel #42
0
		def f(name):
			clip.echo('Hello {}!'.format(name))
Beispiel #43
0
 def test_echo(self):
     _, out, _ = self.embed()
     # Make sure Unicode works properly
     clip.echo(u'你好')
     self.assertEqual(out._writes, [u'你好\n'])
Beispiel #44
0
		def add(item, quantity):
			clip.echo('Added "{} - {}" to the list'.format(item, quantity))
Beispiel #45
0
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)
Beispiel #46
0
		def shout(value):
			clip.echo(' '.join(value).upper())
Beispiel #47
0
		def sort(sort_type):
			clip.echo('You selected {}'.format(sort_type))
Beispiel #48
0
		def add(numbers, silent):
			if not silent:
				clip.echo('Add these numbers? Okay, here we gooooo!')
			clip.echo(sum(numbers))
Beispiel #49
0
		def x(num):
			clip.echo('I was invoked with the number {}!'.format(num))
Beispiel #50
0
		def w(a):
			clip.echo('a in w: {}'.format(a))
Beispiel #51
0
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)
Beispiel #52
0
		def y(a, c):
			clip.echo('a in y: {}'.format(a))
			clip.echo('c in y: {}'.format(c))
Beispiel #53
0
 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),))
Beispiel #54
0
def option_version(opt):  # pylint: disable=unused-argument
    clip.echo("Version: %s" % __version__)
    sys.exit(0)
Beispiel #55
0
 def f(number):
     clip.echo('Hey there {}'.format(number))
     return 42 * number
Beispiel #56
0
		def echo(words):
			clip.echo(' '.join(words))
Beispiel #57
0
 def warn (self, msg):
   if not self.conf.quiet and not self.conf.only:
     clip.echo (self.colourise ("WARNING: " + msg, COLOUR_WARN))
Beispiel #58
0
 def by_long(boop):
     clip.echo("long " + str(boop))
Beispiel #59
0
 def report (self, msg, err = False):
   if not self.conf.quiet:
     clip.echo (self.colourise (msg, COLOUR_REPORT if not err
                                else COLOUR_ERROR))