Python click.edit() Examples
The following are 30
code examples of click.edit().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
click
, or try the search function
.
Example #1
Source File: cmd_addfeed.py From blogger-cli with MIT License | 6 votes |
def load_editor(): marker = ( "# Everything below this line is ignored\n" "Write title in first line, then content in next paragraph\n" ) message = click.edit("\n\n" + marker) try: message = message.split(marker, 1)[0].rstrip("\n") if not message: raise ValueError except Exception: click.secho(":: ERROR empty file. Aborting...", bold=True, fg="bright_red") raise SystemExit() title_content = message.split("\n\n", maxsplit=1) title = title_content[0] content = "" if len(title_content) > 1: content = title_content[1] title, content = [i.strip() for i in (title, content)] return title, content
Example #2
Source File: cloud.py From Paradrop with Apache License 2.0 | 6 votes |
def edit_node_description(ctx, name): """ Interactively edit the node description and save. NAME must be the name of a node that you own. Open the text editor specified by the EDITOR environment variable with the current node description. If you save and exit, the changes will be applied to the node. """ client = ControllerClient() node = client.find_node(name) if node is None: click.echo("Node {} was not found.".format(name)) return description = click.edit(node.get('description', '')) if description is None: click.echo("No change made.") else: node['description'] = description result = client.save_node(node) click.echo(util.format_result(result)) return result
Example #3
Source File: cli.py From eastern with MIT License | 6 votes |
def deploy(ctx, file, namespace, edit, wait, timeout, **kwargs): manifest = format_yaml(file, namespace, edit=edit, extra=kwargs["set"]) result = deploy_from_manifest(ctx, namespace, manifest) if not wait or result != 0: sys.exit(result) if timeout == 0: timeout = None try: wait_for_rolling_deploy(ctx, namespace, manifest, timeout) except subprocess.CalledProcessError as e: print_error("Improper exit with code " + str(e.returncode) + ", exiting...") sys.exit(3) except subprocess.TimeoutExpired: print_error("Rollout took too long, exiting...") sys.exit(2)
Example #4
Source File: cli.py From eastern with MIT License | 6 votes |
def format_yaml(file, namespace, edit=False, print=True, extra=[]): env = {"NAMESPACE": namespace} env.update(**dict(extra)) manifest = formatter.format(file, env) if edit: manifest = click.edit(manifest) if manifest is None: click.echo("File not saved, aborting") return elif print: click.echo(manifest) return manifest
Example #5
Source File: freight_cli.py From freight-cli with Apache License 2.0 | 6 votes |
def app_edit(api, app): data = api.get(f"/apps/{app}/") # id isn't editable data.pop("id") rv = click.edit(json.dumps(data, indent=2) + "\n") if rv is None: return rv = json.loads(rv) params = {} for k, v in rv.items(): if isinstance(v, (list, dict)): params[k] = json.dumps(v) else: params[k] = v api.put(f"/apps/{app}/", params) click.echo(f"App {app} was updated.")
Example #6
Source File: gtd.py From gtd.py with BSD 3-Clause "New" or "Revised" License | 6 votes |
def add_card(ctx, title, message, edit, listname): '''Add a new card. If no title is provided, $EDITOR will be opened so you can write one.''' connection = ctx.connection if listname is None: inbox = connection.inbox_list() else: pattern = re.compile(listname, flags=re.I) target_lists = filter(lambda x: pattern.search(x.name), ctx.board.get_lists('open')) try: inbox = next(target_lists) except StopIteration: click.secho(f'No list names matched by {listname}', fg='red') raise GTDException(1) if not title: title = click.edit(require_save=True, text='<Title here>') if title is None: # No changes were made in $EDITOR click.secho('No title entered for the new card!', fg='red') raise GTDException(1) else: title = title.strip() returned = inbox.add_card(name=title, desc=message) if edit: ctx.card_repl(returned) else: click.secho(f'Successfully added card "{returned.name}"!', fg='green')
Example #7
Source File: wmla120.py From power-up with Apache License 2.0 | 5 votes |
def prep_post(self, eval_ver=False, non_int=False): # write software-vars file. try: if 'ana_powerup_repo_channels' in self.sw_vars: chan_list = [] for chan in ('free', 'main', 'ibmai'): for item in self.sw_vars['ana_powerup_repo_channels']: if chan in item: chan_list.append(item) # prepend any remaining which are not in ('free', 'main', 'ibmai') for item in self.sw_vars['ana_powerup_repo_channels']: if item not in chan_list: chan_list = [item] + chan_list self.sw_vars['ana_powerup_repo_channels'] = chan_list except: pass if not os.path.exists(GEN_SOFTWARE_PATH): os.mkdir(GEN_SOFTWARE_PATH) if self.eval_ver: with open(GEN_SOFTWARE_PATH + f'{self.sw_vars_file_name}', 'w') as f: f.write('# Do not edit this file. This file is autogenerated.\n') with open(GEN_SOFTWARE_PATH + f'{self.sw_vars_file_name}', 'a') as f: yaml.dump(self.sw_vars, f, default_flow_style=False) else: with open(GEN_SOFTWARE_PATH + f'{self.sw_vars_file_name}', 'w') as f: f.write('# Do not edit this file. This file is autogenerated.\n') with open(GEN_SOFTWARE_PATH + f'{self.sw_vars_file_name}', 'a') as f: yaml.dump(self.sw_vars, f, default_flow_style=False)
Example #8
Source File: iocommands.py From athenacli with BSD 3-Clause "New" or "Revised" License | 5 votes |
def open_external_editor(filename=None, sql=None): """Open external editor, wait for the user to type in their query, return the query. :return: list with one tuple, query as first element. """ message = None filename = filename.strip().split(' ', 1)[0] if filename else None sql = sql or '' MARKER = '# Type your query above this line.\n' # Populate the editor buffer with the partial sql (if available) and a # placeholder comment. query = click.edit(u'{sql}\n\n{marker}'.format(sql=sql, marker=MARKER), filename=filename, extension='.sql') if filename: try: with open(filename, encoding='utf-8') as f: query = f.read() except IOError: message = 'Error reading file: %s.' % filename if query is not None: query = query.split(MARKER, 1)[0].rstrip('\n') else: # Don't return None for the caller to deal with. # Empty string is ok. query = sql return (query, message)
Example #9
Source File: paie111.py From power-up with Apache License 2.0 | 5 votes |
def __del__(self): if not os.path.exists(GEN_SOFTWARE_PATH): os.mkdir(GEN_SOFTWARE_PATH) if self.eval_ver: with open(GEN_SOFTWARE_PATH + 'software-vars-eval.yml', 'w') as f: f.write('# Do not edit this file. This file is autogenerated.\n') with open(GEN_SOFTWARE_PATH + 'software-vars-eval.yml', 'a') as f: yaml.dump(self.sw_vars, f, default_flow_style=False) else: with open(GEN_SOFTWARE_PATH + 'software-vars.yml', 'w') as f: f.write('# Do not edit this file. This file is autogenerated.\n') with open(GEN_SOFTWARE_PATH + 'software-vars.yml', 'a') as f: yaml.dump(self.sw_vars, f, default_flow_style=False) if os.path.isfile(self.vault_pass_file): os.remove(self.vault_pass_file)
Example #10
Source File: paie112.py From power-up with Apache License 2.0 | 5 votes |
def __del__(self): if not os.path.exists(GEN_SOFTWARE_PATH): os.mkdir(GEN_SOFTWARE_PATH) if self.eval_ver: with open(GEN_SOFTWARE_PATH + 'software-vars-eval.yml', 'w') as f: f.write('# Do not edit this file. This file is autogenerated.\n') with open(GEN_SOFTWARE_PATH + 'software-vars-eval.yml', 'a') as f: yaml.dump(self.sw_vars, f, default_flow_style=False) else: with open(GEN_SOFTWARE_PATH + 'software-vars.yml', 'w') as f: f.write('# Do not edit this file. This file is autogenerated.\n') with open(GEN_SOFTWARE_PATH + 'software-vars.yml', 'a') as f: yaml.dump(self.sw_vars, f, default_flow_style=False) if os.path.isfile(self.vault_pass_file): os.remove(self.vault_pass_file)
Example #11
Source File: files.py From core with GNU General Public License v3.0 | 5 votes |
def edit(path): """Open a file in your default editor.""" try: with open(path, "r") as f: out = click.edit(f.read()) if out: with open(path, "w") as f: f.write(out) logger.info('ctl:files:edit', 'File saved to {0}'.format(path)) else: logger.info('ctl:files:edit', 'File not saved') except Exception as e: raise CLIException(str(e))
Example #12
Source File: card.py From gtd.py with BSD 3-Clause "New" or "Revised" License | 5 votes |
def change_description(self): old_desc = self.card_json['desc'] new_desc = click.edit(text=old_desc) if new_desc is not None and new_desc != old_desc: self.connection.trello.fetch_json( '/cards/' + self.id + '/desc', http_method='PUT', post_args={'value': new_desc} ) return new_desc
Example #13
Source File: gtd.py From gtd.py with BSD 3-Clause "New" or "Revised" License | 5 votes |
def config(edit): '''Show or modify user configuration''' if edit: try: click.edit(filename=Configuration.find_config_file()) except GTDException: # There is no configuration file click.secho("Could not find config file! Please run onboard if you haven't already", fg='red') else: print(Configuration.from_file()) # onboard {{{
Example #14
Source File: utils.py From keep with MIT License | 5 votes |
def edit_commands(commands, editor=None, edit_header=""): edit_msg = [edit_header] for cmd, fields in commands.items(): desc, alias = fields['desc'], fields['alias'] cmd = json.dumps(cmd) desc = json.dumps(desc) alias = json.dumps(alias) edit_msg.append("{} :: {} :: {}".format(cmd, alias, desc)) edited = click.edit('\n'.join(edit_msg), editor=editor) command_regex = re.compile(r'(\".*\")\s*::\s*(\".*\")\s*::\s*(\".*\")') new_commands = {} if edited: for line in edited.split('\n'): if (line.startswith('#') or line == ""): continue re_match = command_regex.search(line) if re_match and len(re_match.groups()) == 3: cmd, alias, desc = re_match.groups() try: cmd = json.loads(cmd) desc = json.loads(desc) alias = json.loads(alias) except ValueError: click.echo("Error parsing json from edit file.") return None new_commands[cmd] = {'desc': desc, 'alias': alias} else: click.echo("Could not read line '{}'".format(line)) return new_commands
Example #15
Source File: cli.py From passpie with MIT License | 5 votes |
def add(db, fullname, password, random, pattern, interactive, comment, force, copy): if random or pattern: pattern = pattern if pattern else db.config['genpass_pattern'] password = genpass(pattern=pattern) elif not password: password = click.prompt('Password [empty]', hide_input=True, confirmation_prompt=True, show_default=False, default="") found = db.credential(fullname=fullname) if found and not force: message = u"Credential {} already exists. --force to overwrite".format( fullname) raise click.ClickException(click.style(message, fg='yellow')) encrypted = encrypt(password, recipient=db.config['recipient'], homedir=db.config['homedir']) db.add(fullname=fullname, password=encrypted, comment=comment) if interactive: click.edit(filename=db.filename(fullname)) if copy: clipboard.copy(password) click.secho('Password copied to clipboard', fg='yellow') message = u'Added {}{}'.format(fullname, ' [--force]' if force else '') db.repo.commit(message=message)
Example #16
Source File: cli.py From passpie with MIT License | 5 votes |
def update(db, fullname, name, login, password, random, interactive, pattern, comment): credential = db.credential(fullname) if not credential: message = u"Credential '{}' not found".format(fullname) raise click.ClickException(click.style(message, fg='red')) if random or pattern: pattern = pattern if pattern else db.config['genpass_pattern'] password = genpass(pattern=pattern) values = credential.copy() if any([name, login, password, random, comment]): values["name"] = name if name else credential["name"] values["login"] = login if login else credential["login"] values["password"] = password if password else credential["password"] values["comment"] = comment if comment else credential["comment"] else: values["name"] = click.prompt("Name", default=credential["name"]) values["login"] = click.prompt("Login", default=credential["login"]) values["password"] = click.prompt("Password", hide_input=True, default=credential["password"], confirmation_prompt=True, show_default=False, prompt_suffix=" [*****]: ") values["comment"] = click.prompt("Comment", default=credential["comment"]) if values != credential: if values["password"] != credential["password"]: encrypted = encrypt(values["password"], recipient=db.config['recipient'], homedir=db.config['homedir']) values['password'] = encrypted db.update(fullname=fullname, values=values) if interactive: click.edit(filename=db.filename(fullname)) db.repo.commit(u'Updated {}'.format(credential['fullname']))
Example #17
Source File: commands.py From mssql-cli with BSD 3-Clause "New" or "Revised" License | 5 votes |
def open_external_editor(filename=None, sql=None): """ Open external editor, wait for the user to type in his query, return the query. :return: list with one tuple, query as first element. """ message = None filename = filename.strip().split(' ', 1)[0] if filename else None sql = sql or '' MARKER = '# Type your query above this line.\n' # Populate the editor buffer with the partial sql (if available) and a # placeholder comment. query = click.edit(u'{sql}\n\n{marker}'.format(sql=sql, marker=MARKER), filename=filename, extension='.sql') if filename: try: query = read_from_file(filename) except IOError: message = 'Error reading file: %s.' % filename if query is not None: query = query.split(MARKER, 1)[0].rstrip('\n') else: # Don't return None for the caller to deal with. # Empty string is ok. query = sql return (query, message)
Example #18
Source File: __main__.py From click-man with MIT License | 5 votes |
def commit(repo, files, message): """Commits outstanding changes. Commit changes to the given files into the repository. You will need to "repo push" to push up your changes to other repositories. If a list of files is omitted, all changes reported by "repo status" will be committed. """ if not message: marker = '# Files to be committed:' hint = ['', '', marker, '#'] for file in files: hint.append('# U %s' % file) message = click.edit('\n'.join(hint)) if message is None: click.echo('Aborted!') return msg = message.split(marker)[0].rstrip() if not msg: click.echo('Aborted! Empty commit message') return else: msg = '\n'.join(message) click.echo('Files to be committed: %s' % (files,)) click.echo('Commit message:\n' + msg)
Example #19
Source File: util.py From guildai with Apache License 2.0 | 5 votes |
def editor(s): import click try: edited = click.edit(s, _try_editor()) except click.UsageError as e: raise ValueError(e) else: if edited is not None: return edited return s
Example #20
Source File: filehelpers.py From releasetool with Apache License 2.0 | 5 votes |
def open_editor(filename: str, return_contents: bool = False) -> Optional[str]: click.edit(filename=filename) if return_contents: with open(filename, "r") as fh: return fh.read() else: return None
Example #21
Source File: cli.py From cronyo with MIT License | 5 votes |
def configure(): if not config: logger.info('generating new config {}'.format(config_filename)) generate_config(config_filename) click.edit(filename=config_filename)
Example #22
Source File: cli.py From twtxt with MIT License | 5 votes |
def config(ctx, key, value, remove, edit): """Get or set config item.""" conf = ctx.obj["conf"] if not edit and not key: raise click.BadArgumentUsage("You have to specify either a key or use --edit.") if edit: return click.edit(filename=conf.config_file) if remove: try: conf.cfg.remove_option(key[0], key[1]) except Exception as e: logger.debug(e) else: conf.write_config() return if not value: try: click.echo(conf.cfg.get(key[0], key[1])) except Exception as e: logger.debug(e) return if not conf.cfg.has_section(key[0]): conf.cfg.add_section(key[0]) conf.cfg.set(key[0], key[1], value) conf.write_config()
Example #23
Source File: pkg.py From marvin-python-toolbox with Apache License 2.0 | 5 votes |
def bumpversion(ctx, part, allow_dirty, force, yes): args = [part] allow_dirty = allow_dirty or force is_clean = is_git_clean(ctx.obj['base_path']) if not is_clean and not allow_dirty: print('') print('ERROR: Git working directory is not clean.') print('') print('You can use --allow-dirty or --force if you know what ' 'you\'re doing.') exitcode = 1 else: if allow_dirty: args.append('--allow-dirty') command = ['bumpversion'] + args old_version = get_version(ctx.obj['package_path']) exitcode = subprocess.call(command, cwd=ctx.obj['base_path']) new_version = get_version(ctx.obj['package_path']) if exitcode == 0: print('Bump version from {old} to {new}'.format( old=old_version, new=new_version)) if yes or click.confirm('Do you want to edit CHANGES.md?'): click.edit(filename=os.path.join(ctx.obj['base_path'], 'CHANGES.md')) sys.exit(exitcode)
Example #24
Source File: cli.py From PyCon2019-Click-Tutorial with Mozilla Public License 2.0 | 5 votes |
def editor(): """Launch an editor.""" message = click.edit("Prepopulated text") click.echo("Your message: {}".format(message))
Example #25
Source File: grpc_shell.py From SROS-grpc-services with BSD 3-Clause "New" or "Revised" License | 5 votes |
def edit_config(config_file): if config_file: click.edit(filename=config_file)
Example #26
Source File: cli.py From gimel with MIT License | 5 votes |
def configure(): if not config: logger.info('generating new config {}'.format(config_filename)) generate_config(config_filename) click.edit(filename=config_filename)
Example #27
Source File: __main__.py From passpy with GNU General Public License v3.0 | 5 votes |
def edit(ctx, pass_name): """Insert a new password or edit an existing one using the editor specified by either EDITOR or VISUAL or falling back on the platform default if both are not set. """ try: data = ctx.obj.get_key(pass_name) except StoreNotInitialisedError: click.echo(MSG_STORE_NOT_INITIALISED_ERROR) return 1 except FileNotFoundError: data = '' except PermissionError: click.echo(MSG_PERMISSION_ERROR) return 1 if 'EDITOR' in os.environ: data = click.edit(text=data, editor=os.environ['EDITOR']) else: data = click.edit(text=data) if data is None: click.echo('Password unchanged.') return 1 ctx.obj.set_key(pass_name, data, force=True)
Example #28
Source File: iocommands.py From litecli with BSD 3-Clause "New" or "Revised" License | 5 votes |
def open_external_editor(filename=None, sql=None): """Open external editor, wait for the user to type in their query, return the query. :return: list with one tuple, query as first element. """ message = None filename = filename.strip().split(" ", 1)[0] if filename else None sql = sql or "" MARKER = "# Type your query above this line.\n" # Populate the editor buffer with the partial sql (if available) and a # placeholder comment. query = click.edit( "{sql}\n\n{marker}".format(sql=sql, marker=MARKER), filename=filename, extension=".sql", ) if filename: try: with open(filename, encoding="utf-8") as f: query = f.read() except IOError: message = "Error reading file: %s." % filename if query is not None: query = query.split(MARKER, 1)[0].rstrip("\n") else: # Don't return None for the caller to deal with. # Empty string is ok. query = sql return (query, message)
Example #29
Source File: wmla121.py From power-up with Apache License 2.0 | 5 votes |
def write_sw_vars_to_file(self): with open(GEN_SOFTWARE_PATH + f'{self.sw_vars_file_name}', 'w') as f: f.write('# Do not edit this file. This file is autogenerated.\n') with open(GEN_SOFTWARE_PATH + f'{self.sw_vars_file_name}', 'a') as f: yaml.dump(self.sw_vars, f, default_flow_style=False)
Example #30
Source File: iocommands.py From pgspecial with BSD 3-Clause "New" or "Revised" License | 5 votes |
def open_external_editor(filename=None, sql=None): """ Open external editor, wait for the user to type in his query, return the query. :return: list with one tuple, query as first element. """ message = None filename = filename.strip().split(' ', 1)[0] if filename else None sql = sql or '' MARKER = '# Type your query above this line.\n' # Populate the editor buffer with the partial sql (if available) and a # placeholder comment. query = click.edit(u'{sql}\n\n{marker}'.format(sql=sql, marker=MARKER), filename=filename, extension='.sql') if filename: try: query = read_from_file(filename) except IOError: message = 'Error reading file: %s.' % filename if query is not None: query = query.split(MARKER, 1)[0].rstrip('\n') else: # Don't return None for the caller to deal with. # Empty string is ok. query = sql return (query, message)