def _stash_remove(cmd_key, title): commands = keep_utils.read_commands() if commands is not None and cmd_key in commands: keep_utils.remove_command(cmd_key) print(f'\n{BOLD}{GREEN}"{title}" removed from stash{END_FORMAT}\n') else: print(f'\n{BOLD}{RED}"{title}" not found in stash{END_FORMAT}\n')
def cli(ctx, pattern): """Deletes a saved command.""" matches = utils.grep_commands(pattern) if matches: click.echo("\n\n") for idx, match in enumerate(matches): cmd, desc = match click.secho(" " + str(idx + 1) + "\t", nl=False, fg='yellow') click.secho("$ {} :: {}".format(cmd, desc), fg='green') click.echo("\n\n") val = 1 while True and len(matches) > 1: val = click.prompt( "Choose command to remove [1-{}] (0 to cancel)".format( len(matches)), type=int) if val in range(len(matches) + 1): break click.echo("Number is not in range") if val > 0: cmd, desc = matches[val - 1] command = "$ {} :: {}".format(cmd, desc) if click.confirm("Remove\n\t{}\n\n?".format(command), default=True): commands = utils.read_commands() del commands[cmd] utils.write_commands(commands) click.echo('Command successfully removed!') elif matches == []: click.echo('No saved commands matches the pattern {}'.format(pattern)) else: click.echo("No commands to remove, Add one by 'keep new'. ")
def command_line_runner(): parser = get_parser() args = vars(parser.parse_args()) if args['version']: _print_ok(__version__) return if args['clear_cache']: if _clear_cache(): _print_ok('Cache cleared successfully') else: _print_err('Clearing cache failed') if args[STASH_VIEW]: print_stash() return if args[STASH_EMPTY]: os.system('keep init') return if args[STASH_REMOVE] and len(args['query']) == 0: commands = keep_utils.read_commands() if commands is None or len(commands.items()) == 0: print( 'No commands found in stash. Add a command with "howdoi --{stash_save} <query>".' .format(stash_save=STASH_SAVE)) return stash_list = [{ 'command': cmd, 'fields': field } for cmd, field in commands.items()] prompt_stash_remove(args, stash_list) return if not args['query']: parser.print_help() return if os.getenv('HOWDOI_COLORIZE'): args['color'] = True if not args['search_engine'] in SUPPORTED_SEARCH_ENGINES: _print_err('Unsupported engine.\nThe supported engines are: %s' % ', '.join(SUPPORTED_SEARCH_ENGINES)) return elif args['search_engine'] != 'google': os.environ['HOWDOI_SEARCH_ENGINE'] = args['search_engine'] utf8_result = howdoi(args).encode('utf-8', 'ignore') if sys.version < '3': print(utf8_result) else: # Write UTF-8 to stdout: https://stackoverflow.com/a/3603160 sys.stdout.buffer.write(utf8_result) # close the session to release connection howdoi_session.close()
def command_line_runner(): # pylint: disable=too-many-return-statements,too-many-branches parser = get_parser() args = vars(parser.parse_args()) if args['version']: print(__version__) return if args['explain']: logging.getLogger().setLevel(logging.INFO) logging.info('Version: %s', __version__) if args['sanity_check']: sys.exit(perform_sanity_check()) if args['clear_cache']: if _clear_cache(): print(f'{GREEN}Cache cleared successfully{END_FORMAT}') else: logging.error('%sClearing cache failed%s', RED, END_FORMAT) if args[STASH_VIEW]: print_stash() return if args[STASH_EMPTY]: os.system('keep init') return if args[STASH_REMOVE] and len(args['query']) == 0: commands = keep_utils.read_commands() if commands is None or len(commands.items()) == 0: logging.error( '%sNo commands found in stash. ' 'Add a command with "howdoi --%s <query>".%s', RED, STASH_SAVE, END_FORMAT) return stash_list = [{ 'command': cmd, 'fields': field } for cmd, field in commands.items()] prompt_stash_remove(args, stash_list) return if not args['query']: parser.print_help() return if os.getenv('HOWDOI_COLORIZE'): args['color'] = True utf8_result = howdoi(args).encode('utf-8', 'ignore') # Write UTF-8 to stdout: https://stackoverflow.com/a/3603160 sys.stdout.buffer.write(utf8_result) # close the session to release connection howdoi_session.close()
def cli(ctx, shell): """Completion helpers for keep""" commands = utils.read_commands() if shell == 'zsh': for cmd, fields in commands.items(): print("{cmd}:{desc}".format(cmd=cmd, desc=fields['desc'])) elif shell == 'bash': for cmd in commands.keys(): print(quote(cmd))
def print_stash(stash_list = []): if len(stash_list) == 0: stash_list = ['\nSTASH LIST:'] commands = keep_utils.read_commands() if commands is None or len(commands.items()) == 0: print('No commands found in stash. Add a command with "howdoi --{stash_save} <query>".'.format(stash_save=STASH_SAVE)) return for cmd, fields in commands.items(): stash_list.append(format_stash_item(fields)) else: stash_list = [format_stash_item(x['fields'], i) for i, x in enumerate(stash_list)] print(build_splitter('#').join(stash_list))
def _stash_remove(cmd_key, title): commands = keep_utils.read_commands() if commands is not None and cmd_key in commands: keep_utils.remove_command(cmd_key) print('\n{bold}{green}"{title}" removed from stash.{end_format}\n'. format(bold=BOLD, green=GREEN, title=title, end_format=END_FORMAT)) else: print( '\n{bold}{red}"{title}" not found in stash.{end_format}\n'.format( bold=BOLD, red=RED, title=title, end_format=END_FORMAT))
def print_stash(stash_list=None): if not stash_list or len(stash_list) == 0: stash_list = ['\nSTASH LIST:'] commands = keep_utils.read_commands() if commands is None or len(commands.items()) == 0: logging.error('%sNo commands found in stash. ' 'Add a command with "howdoi --%s <query>".%s', RED, STASH_SAVE, END_FORMAT) return for _, fields in commands.items(): stash_list.append(format_stash_item(fields)) else: stash_list = [format_stash_item(x['fields'], i) for i, x in enumerate(stash_list)] print(build_splitter('#').join(stash_list))
def cli(ctx, editor): """Edit saved commands.""" commands = utils.read_commands() if commands is []: click.echo("No commands to edit, Add one by 'keep new'. ") else: edit_header = "# Unchanged file will abort the operation\n" new_commands = utils.edit_commands(commands, editor, edit_header) if new_commands and new_commands != commands: click.echo("Replace:\n") click.secho("\t{}".format('\n\t'.join( utils.format_commands(commands))), fg="green") click.echo("With:\n\t") click.secho("\t{}".format('\n\t'.join( utils.format_commands(new_commands))), fg="green") if click.confirm("", default=False): utils.write_commands(new_commands)
def cli(ctx): """Push commands to a secret GitHub gist.""" token = utils.get_github_token() if not token: return gist_url = f"https://gist.github.com/{token['gist']}" prompt_str = f"[CRITICAL] Overwrite upstream gist with local commands?\nGist URL : {gist_url}" click.confirm(prompt_str, abort=True) commands = utils.read_commands() if not commands: click.echo("No commands to push. Add one by 'keep new'. ") else: hub = Github(token['token']) gist = hub.get_gist(token['gist']) gist.edit(files={'commands.json': InputFileContent(json.dumps(commands))}) click.echo("Done!")
def cli(ctx, editor): """Edit saved commands.""" commands = utils.read_commands() if commands is None: click.echo("No commands to edit, Add one by 'keep new'. ") else: edit_header = "# Unchanged file will abort the operation\n" new_commands = utils.edit_commands(commands, editor, edit_header) if new_commands and new_commands != commands: click.echo("Replace:\n") click.secho("\t{}".format('\n\t'.join(utils.format_commands(commands))), fg="green") click.echo("With:\n\t") click.secho("\t{}".format('\n\t'.join(utils.format_commands(new_commands))), fg="green") if click.confirm("", default=False): utils.write_commands(new_commands) elif new_commands == {}: dir_path = os.path.join(os.path.expanduser('~'), '.keep') json_path = os.path.join(dir_path, 'commands.json') if click.confirm('Delete all commands ?', abort=True): os.remove(json_path)