def select_contact(choice=None, config=None): contact_dict = compute_contact_dict(config) if choice is None: number = iterfzf.iterfzf(contact_dict.keys()) channel = contact_dict[number] else: choices = [ name for name in contact_dict.keys() if name.startswith(choice) ] if len(choices) > 1: name = iterfzf.iterfzf(choices) channel = contact_dict[name] elif len(choices) == 1: name = choices[0] channel = contact_dict[name] else: channel = choice try: is_group = True channel = codecs.decode(channel, 'hex') except binascii.Error: is_group = False return channel, is_group
def get_pid_via_fzf(exact=True): try: # FIXME: This is a bug from iterfzf. The fzf may not be executable selected_line = iterfzf(iter_ps(), multi=False, exact=exact) except PermissionError as e: try: os.chmod(e.filename, os.stat(e.filename).st_mode | stat.S_IEXEC) except PermissionError: logger.error( f"Please make {e.filename} executable(e.g `chmod a+x {e.filename}`)." ) return None else: selected_line = iterfzf(iter_ps(), multi=False, exact=exact) return get_pid_from_line(selected_line)
def main(): parser = argparse.ArgumentParser(description='AWS Instant Ids') parser.add_argument('-instances', action='store_true', help="Returns a list of instance ids") parser.add_argument('-loggroups', action='store_true', help="Returns a list of log groups") args = parser.parse_args() aws = Aws(boto3.client('ec2'), boto3.client('logs')) results = {} if args.instances: results = aws.get_list_of_instances() elif args.loggroups: results = aws.get_list_of_log_groups() selection = iterfzf.iterfzf(results.keys()) try: instance_id = results[selection] except KeyError: instance_id = "" print(instance_id)
def user_start(): desc_list = get_data() if len(argv) > 1: query, desc = '', argv[1] consume(desc_list) else: from iterfzf import iterfzf query, desc = iterfzf(desc_list, print_query=True, extended=True) try: proj = desc_list.timers[desc]['pid'] except KeyError: print('Unkown description! Abort.') exit(1) if desc: cur = begin_timer_raw(desc, proj) print(f"'{desc}'ing since {datetime.now().strftime('%H:%M:%S')}") else: return # TODO: collect project information, allow creating new time entries set_data(desc_list, desc, pid=proj, start=datetime.now(), color=cur.project.hex_color) return cur
def handle(self, *args, **options): string_to_item = {} for item in Item.objects.all(): item_string = str(item) if item_string in string_to_item: print(f"WARNING: Duplicate item: {item_string}", file=sys.stderr) i = 2 while True: new_string = f"{item_string} ({i})" if new_string in string_to_item: i += 1 continue item_string = new_string break string_to_item[str(item)] = item item_strings = sorted(string_to_item.keys()) while True: selected_string = iterfzf(item_strings, case_sensitive=False) if not selected_string: return print() print(selected_string) item = string_to_item[selected_string] item.barcode = input("Barcode: ") item.save()
def selectDirectory(config, cwd): directories = listDirectories(config) directory = iterfzf(directories) if directory: print(directory) else: print(cwd)
def do_fzf(ctx, kwargs, instances): sel = iterfzf(instances) if sel is None: return name, ip, account, tags = sel.split('\t') if kwargs['key'] != "''": key = f"-i {kwargs['key']}" else: key = '' if kwargs['user'] != "''": user = f"-l {kwargs['user']}" else: user = '' ssh_command = f"ssh {key} {user} {ip}" ctx.vlog("Executing:") ctx.vlog(ssh_command) subprocess.call(ssh_command, shell=True, executable=os.getenv('SHELL', '/bin/bash'))
def execute(self): select = iterfzf(self.fm.commands.commands) self.fm.execute_console(f'console {select}') # 刷新 self.fm.execute_console('redraw_window') # self.fm.dump_commands() # for cmd_name in sorted(self.fm.commands.commands): # cmd = self.commands.commands[cmd_name] # self.fm.notify(cmd_name) # def callback(answer): # if answer == "q": # return # elif answer == "m": # self.fm.display_help() # elif answer == "c": # self.fm.dump_commands() # elif answer == "k": # self.fm.dump_keybindings() # elif answer == "s": # self.fm.dump_settings() # self.fm.ui.console.ask( # "View [m]an page, [k]ey bindings, [c]ommands or [s]ettings? (press q to abort)", # callback, # list("mqkcs") # ) return
def execute(self): select = iterfzf(self.fm.ui.console.history.history) self.fm.execute_console(f'console {select}') self.fm.cd(self.fm.thisdir) # 刷新 self.fm.execute_console('redraw_window')
def search_conversations(self): convos = self.list() print("Convos is " + str(convos)) selection = iterfzf(iter_conversations(convos.keys()), multi=False) # Fetch thread messages print(self.fetch_messages(convos[selection]))
def prompt_user(iterable_data, **prompt_options): """ Display the selection option (iterable_data) :param iterable_data: :param prompt_options: :return: The user selected data """ return iterfzf(iterable_data, **prompt_options)
def theme_selector(theme_dicts: dict) -> str: """ Use fzf to select a theme """ os.environ['FZF_DEFAULT_OPTS'] += '--ansi' selected = iterfzf(theme_name_iter(theme_dicts)) if selected is None: return None return name_from_selection(selected)
def main(): args = docopt(USAGE, version=VERSION) if args['help']: print(USAGE) return True if args['--verbose']: print(args) # print banner banner() # init noder noder = Noder(debug=args['--verbose'], sortsize=args['--sortsize'], arc=args['--archive']) # init catalog catalog = Catalog(args['--catalog'], debug=args['--verbose'], force=args['--force']) # init top node top = catalog.restore() if not top: top = noder.new_top_node() # handle the meta node meta = noder.update_metanode(top) catalog.set_metanode(meta) # parse command if args['index']: cmd_index(args, noder, catalog, top) if args['update']: cmd_update(args, noder, catalog, top) elif args['find']: cmd_find(args, noder, top) elif args['tree']: cmd_tree(args, noder, top) elif args['ls']: cmd_ls(args, noder, top) elif args['rm']: cmd_rm(args, noder, catalog, top) elif args['graph']: cmd_graph(args, noder, top) elif args['rename']: cmd_rename(args, noder, catalog, top) elif args['edit']: cmd_edit(args, noder, catalog, top) elif args['fzf']: r = cmd_fzf(args, noder, top) # iterfzf(r[0].iter_path_reverse()) for file in iterfzf(map(lambda x: x.relpath, r[0].leaves), exact=True, multi=True): print(file) # import IPython; IPython.embed() # import sys; sys.exit(1) # iterfzf(map(lambda x: x.name, r[0].leaves)) return True
def sort_files(flist, dlist, delete=False, single=False): """ Loops over the given file list, playing back each file in mpv whilst prompting the user for a target directory choice using fzf. The user is prompted multiple times for the same file, to copy it into multiple directories, until they cancel the fzf call for it to return None. Each prompt also includes the QUIT_CHOICE to give the user the option to abort sorting for now. If the delete flag is set, files are deleted after the user moves on to the next file. """ total_count = len(flist) flist = list(flist) player = mpv.MPV(input_vo_keyboard=True) player['loop-file'] = 'inf' player['mute'] = True for fil in flist: player.playlist_append(fil) player.playlist_pos = 0 while flist: cur_file = player.playlist[player.playlist_pos]['filename'] cur_dirs = list(dlist) cur_dirs.append(QUIT_CHOICE) print('Progress: {}/{}'.format(len(flist), total_count)) choice = True while cur_dirs and choice != None: choice = iterfzf(cur_dirs, multi=True) if choice: if QUIT_CHOICE in choice: print('Quitting manually.') player.quit() del player return for cho in choice: shutil.copy(cur_file, cho) print('Copied: {} -> {}'.format(cur_file, cho)) cur_dirs.remove(cho) if single: break player.playlist_remove() del flist[0] if delete: os.remove(cur_file) print('Removed: {}'.format(cur_file)) player.quit() del player print('Done sorting all files.')
def go(args): """Select a remote and SSH to it at once (in interactive way).""" client = get_client() remotes = client.remotes chosen = iterfzf(align_remote_list(remotes)) if chosen is None: return alias = chosen.split()[0] ssh.call(args, alias=alias)
def fzf_select_transaction() -> str: result = iterfzf(trc.get_list_of_transaction_rcs()) if not result: print( 'No transaction selected via args, and FZF selection interface failed!' ) exit(1) path = Path(result) return path
def main(): package_file_path = find_nearest_package_file() with open(package_file_path) as file: scripts = json.load(file)["scripts"] script_keys = list(scripts.keys()) chosen_script = iterfzf(script_keys) if chosen_script: call([f"npm run {chosen_script}"], shell=True)
def main(): data = load_config() databases = {d['id']: d for d in data['databases']} if (len(sys.argv) > 1): selected = sys.argv[1] else: selected = iterfzf(databases.keys()) connect(databases[selected])
def single_or_fzf(options): """ If there are more than one element in options make the user specify one using fzf, otherwise return the single element. """ if len(options) == 1: return options[0] else: return iterfzf(options)
def main(): config = _get_config() instances = _get_instances(config.region, config.ttl) instances = sorted( instances, reverse=True) # instances should be alphabetically sorted result = iterfzf(_format_data(instances, config.template), multi=False) instance_id = _extract_instance_id(result) target_instance = list(filter(lambda i: i.id == instance_id, instances))[0] ssh_target = target_instance.public_ip if config.use_ip else target_instance.public_dns _ssh(ssh_target) exit()
def execute(self): list1 = [] for k, v in iter(self.fm.bookmarks): list1.append(str(v)) self.fm.notify(list1[0]) select = iterfzf(list1) self.fm.cd(select) # 刷新 self.fm.execute_console('redraw_window')
def asi_update(self): statslist = [self.stats[x] for x in self.stats.keys()] asi_stats = iterfzf(self.stats, multi=True, prompt=str(statslist)) try: if (len(asi_stats)) == 1: self.stats[asi_stats[0]] = self.stats[asi_stats[0]] + 2 elif (len(asi_stats)) == 2: self.stats[asi_stats[0]] = self.stats[asi_stats[0]] + 1 self.stats[asi_stats[1]] = self.stats[asi_stats[1]] + 1 except: pass
def main(): d = { '1': 'foo', '2': 'bar', '3': 'spam', '4': 'egg', } print(iterfzf(d.values())) keys = fzf_dict(d, multi=True) for key in keys: print(repr(key), '=>', repr(d[key]))
def _(event): document = event.current_buffer.document line = document.current_line history = reversed(event.current_buffer.history) gen = map(lambda s: s.replace('\n', '\\n'), history) hist_line = iterfzf(gen, exact=True, query=line) if hist_line is not None: hist_line = hist_line.replace('\n', '\n\n') new_doc = Document(hist_line.replace('\\n', '\n')) event.current_buffer.set_document(new_doc)
def choose_files(downloadfiles): """prompt the user to choose files""" if not downloadfiles: print("NO FILES YET") sys.exit(0) items_to_download_names = iterfzf( downloadfiles.get_descriptions(), multi=True) files_to_download = DownloadList() for item in downloadfiles.list: for name in items_to_download_names: if item.discreption == name: files_to_download.list.append(item) return files_to_download
def execute(self): self.fm.execute_console('unmark *') if self.arg(1) == 'atime': time_command = 'filename.stat().st_atime' self.fm.notify('atime') elif self.arg(1) == 'ctime': time_command = 'filename.stat().st_ctime' self.fm.notify('ctime') else: time_command = 'filename.stat().st_mtime' self.fm.notify('mtime') cwd = self.fm.thisdir # 时区 tz = timezone(timedelta(hours=+8)) # {filename : filetime, ...} filetime_dict = {} thisdir = pathlib.Path(str(cwd)).iterdir() for i in thisdir: filename = pathlib.Path(i) unixtime = eval(time_command) filetime_dict |= { str(filename.name): datetime.fromtimestamp(unixtime, tz=tz).strftime("%Y-%m-%d_%H:%M:%S") } # ['filename filetime', ...] filetime_list = [] for k, v in filetime_dict.items(): kv = f'{k} {v}' filetime_list.append(kv) select = iterfzf(filetime_list) select = select.split()[1] self.fm.notify(select) # 刷新 self.fm.execute_console('redraw_window') for k, v in filetime_dict.items(): if v == select: self.fm.execute_console(f'mark {k}') # The refresh problem is not yet resolved # self.fm.ui.win.refresh() return
def choose_files(downloadfiles): """prompt the user to choose files""" if not downloadfiles: sys.exit(0) back = downloadfiles.get_descriptions() back.insert(0, BACK) items_to_download_names = iterfzf(back, multi=True) if items_to_download_names[0] == BACK: return BACK files_to_download = DownloadList() for item in downloadfiles.list: for name in items_to_download_names: if item.discreption == name: files_to_download.list.append(item) return files_to_download
def getSpells(self): try: print("Getting Spells... from file " + 'spells/' + self.className) spellfile = open('spells/' + self.className) print("SUCCESS") spells = spellfile.readlines() spellfile.close() spellsdict = { item.split(',')[0].strip(): item.split(',')[1].strip() for item in spells } out = iterfzf(spellsdict, multi=True) or [] return out except: return []
def _get( self, func, *args, prompt="", ): prompt += "> " objs = func(*args) if not objs: return oname = iterfzf.iterfzf( sorted([ob.name for ob in objs]), prompt=prompt) if not oname: raise ChoiceceError("You need to choose a " + prompt) return [o for o in objs if o.name == oname][0]
def get_ow_stacks(client: boto3.client) -> dict: """ Get a list of opsworks stacks """ output = {} response: dict = client.describe_stacks() for stack in response["Stacks"]: output[stack["Name"]] = stack["StackId"] owstack = iterfzf(output) try: return output[owstack] except KeyError: exit(0)
def find_doi(db, config, category=None): # show all text if category: article_list = [ (config['listStyle'] + ' {doi}').format(**db.get_info(doi)) for doi in db.db.keys() if db.get_info(doi)['category'] == category ] else: article_list = [ (config['listStyle'] + ' {doi}').format(**db.get_info(doi)) for doi in db.db.keys() ] ret = iterfzf(article_list, multi=False, encoding='utf-8') if ret: doi = ret.split()[-1] return doi else: return None
def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, the menu items will not be displayed [default: False]. - returns (str) - Controls what part of the menu entry is returned, 'func' returns function result [default: name]. - limit (int) - If set, limits the number of menu entries show at a time [default: None]. - fzf (bool) - If true, can enter FCHR at the menu prompt to search menu. """ global _AUTO hdr = kwargs.get('hdr', "") note = kwargs.get('note', "") dft = kwargs.get('dft', "") fzf = kwargs.pop('fzf', True) compact = kwargs.get('compact', False) returns = kwargs.get('returns', "name") limit = kwargs.get('limit', None) dft = kwargs.get('dft', None) msg = [] if limit: return show_limit(entries, **kwargs) def show_banner(): banner = "-- MENU" if hdr: banner += ": " + hdr banner += " --" msg.append(banner) if _AUTO: return for i in entries: msg.append(" (%s) %s" % (i.name, i.desc)) valid = [i.name for i in entries] if type(dft) == int: dft = str(dft) if dft not in valid: dft = None if not compact: show_banner() if note and not _AUTO: msg.append("[!] " + note) if fzf: valid.append(FCHR) msg.append(QSTR + kwargs.get('msg', "Enter menu selection")) msg = os.linesep.join(msg) entry = None while entry not in entries: choice = ask(msg, vld=valid, dft=dft, qstr=False) if choice == FCHR and fzf: try: from iterfzf import iterfzf choice = iterfzf(reversed(["%s\t%s" % (i.name, i.desc) for i in entries])).strip("\0").split("\t", 1)[0] except: warn("Issue encountered during fzf search.") match = [i for i in entries if i.name == choice] if match: entry = match[0] if entry.func: fresult = run_func(entry) if "func" == returns: return fresult try: return getattr(entry, returns) except: return getattr(entry, "name")