How to use fzf method in refurb

Best Python code snippet using refurb_python

fuzzy.py

Source:fuzzy.py Github

copy

Full Screen

...204 fzf_path205 )206 )207 sys.exit(1)208 def get_fzf():209 return find_executable("fzf", os.path.join(fzf_path, "bin"))210 if os.path.isdir(fzf_path):211 if update:212 ret = run_cmd(["git", "pull"], cwd=fzf_path)213 if ret:214 print("Update fzf failed.")215 sys.exit(1)216 run_fzf_install_script(fzf_path)217 return get_fzf()218 fzf_bin = get_fzf()219 if not fzf_bin or should_force_fzf_update(fzf_bin):220 return fzf_bootstrap(update=True)221 return fzf_bin222 if not update:223 install = input("Could not detect fzf, install it now? [y/n]: ")224 if install.lower() != "y":225 return226 if not find_executable("git"):227 print("Git not found.")228 print(FZF_INSTALL_FAILED)229 sys.exit(1)230 cmd = ["git", "clone", "--depth", "1", "https://github.com/junegunn/fzf.git"]231 if subprocess.call(cmd, cwd=os.path.dirname(fzf_path)):232 print(FZF_INSTALL_FAILED)233 sys.exit(1)234 run_fzf_install_script(fzf_path)235 print("Installed fzf to {}".format(fzf_path))236 return get_fzf()237def format_header():238 shortcuts = []239 for action, key in fzf_header_shortcuts:240 shortcuts.append(241 "{t.white}{action}{t.normal}: {t.yellow}<{key}>{t.normal}".format(242 t=terminal, action=action, key=key243 )244 )245 return FZF_HEADER.format(shortcuts=", ".join(shortcuts), t=terminal)246def run_fzf(cmd, tasks):247 env = dict(os.environ)248 env.update(249 {"PYTHONPATH": os.pathsep.join([p for p in sys.path if "requests" in p])}250 )251 proc = subprocess.Popen(252 cmd,253 stdout=subprocess.PIPE,254 stdin=subprocess.PIPE,255 env=ensure_subprocess_env(env),256 universal_newlines=True,257 )258 out = proc.communicate("\n".join(tasks))[0].splitlines()259 selected = []260 query = None261 if out:262 query = out[0]263 selected = out[1:]264 return query, selected265def run(266 update=False,267 query=None,268 intersect_query=None,269 try_config=None,270 full=False,271 parameters=None,272 save_query=False,273 push=True,274 message="{msg}",275 test_paths=None,276 exact=False,277 closed_tree=False,278 show_estimates=False,279 disable_target_task_filter=False,280):281 fzf = fzf_bootstrap(update)282 if not fzf:283 print(FZF_NOT_FOUND)284 return 1285 check_working_directory(push)286 tg = generate_tasks(287 parameters, full=full, disable_target_task_filter=disable_target_task_filter288 )289 all_tasks = sorted(tg.tasks.keys())290 # graph_Cache created by generate_tasks, recreate the path to that file.291 cache_dir = os.path.join(get_state_dir(srcdir=True), "cache", "taskgraph")292 if full:293 graph_cache = os.path.join(cache_dir, "full_task_graph")294 dep_cache = os.path.join(cache_dir, "full_task_dependencies")295 target_set = os.path.join(cache_dir, "full_task_set")296 else:297 graph_cache = os.path.join(cache_dir, "target_task_graph")298 dep_cache = os.path.join(cache_dir, "target_task_dependencies")299 target_set = os.path.join(cache_dir, "target_task_set")300 if show_estimates:301 download_task_history_data(cache_dir=cache_dir)302 make_trimmed_taskgraph_cache(graph_cache, dep_cache, target_file=target_set)303 if not full and not disable_target_task_filter:304 # Put all_tasks into a list because it's used multiple times, and "filter()"305 # returns a consumable iterator.306 all_tasks = list(filter(filter_by_uncommon_try_tasks, all_tasks))307 if test_paths:308 all_tasks = filter_tasks_by_paths(all_tasks, test_paths)309 if not all_tasks:310 return 1311 key_shortcuts = [k + ":" + v for k, v in six.iteritems(fzf_shortcuts)]312 base_cmd = [313 fzf,314 "-m",315 "--bind",316 ",".join(key_shortcuts),317 "--header",318 format_header(),319 "--preview-window=right:30%",320 "--print-query",321 ]322 if show_estimates:323 base_cmd.extend(324 [325 "--preview",326 '{} {} -g {} -s -c {} -t "{{+f}}"'.format(327 sys.executable, PREVIEW_SCRIPT, dep_cache, cache_dir328 ),329 ]330 )331 else:332 base_cmd.extend(333 [334 "--preview",335 '{} {} -t "{{+f}}"'.format(sys.executable, PREVIEW_SCRIPT),336 ]337 )338 if exact:339 base_cmd.append("--exact")340 selected = set()341 queries = []342 def get_tasks(query_arg=None, candidate_tasks=all_tasks):343 cmd = base_cmd[:]344 if query_arg and query_arg != "INTERACTIVE":345 cmd.extend(["-f", query_arg])346 query_str, tasks = run_fzf(cmd, sorted(candidate_tasks))347 queries.append(query_str)348 return set(tasks)349 for q in query or []:350 selected |= get_tasks(q)351 for q in intersect_query or []:352 if not selected:353 tasks = get_tasks(q)354 selected |= tasks355 else:356 tasks = get_tasks(q, selected)357 selected &= tasks358 if not queries:359 selected = get_tasks()360 if not selected:...

Full Screen

Full Screen

commands.py

Source:commands.py Github

copy

Full Screen

1# This is a sample commands.py. You can add your own commands here.2#3# Please refer to commands_full.py for all the default commands and a complete4# documentation. Do NOT add them all here, or you may end up with defunct5# commands when upgrading ranger.6# A simple command for demonstration purposes follows.7# -----------------------------------------------------------------------------8from __future__ import (absolute_import, division, print_function)9# You can import any python module as needed.10import os11# You always need to import ranger.api.commands here to get the Command class:12from ranger.api.commands import Command13from collections import deque14class fzf_select(Command):15 """16 :fzf_select17 Find a file using fzf.18 With a prefix argument to select only directories.19 See: https://github.com/junegunn/fzf20 """21 def execute(self):22 import subprocess23 from ranger.ext.get_executables import get_executables24 if 'fzf' not in get_executables():25 self.fm.notify('Could not find fzf in the PATH.', bad=True)26 return27 fd = None28 if 'fdfind' in get_executables():29 fd = 'fdfind'30 elif 'fd' in get_executables():31 fd = 'fd'32 if fd is not None:33 hidden = ('--hidden' if self.fm.settings.show_hidden else '')34 exclude = "--no-ignore-vcs --exclude '.git' --exclude '*.py[co]' --exclude '__pycache__'"35 only_directories = ('--type directory' if self.quantifier else '')36 fzf_default_command = '{} --follow {} {} {} --color=always'.format(37 fd, hidden, exclude, only_directories38 )39 else:40 hidden = ('-false' if self.fm.settings.show_hidden else r"-path '*/\.*' -prune")41 exclude = r"\( -name '\.git' -o -iname '\.*py[co]' -o -fstype 'dev' -o -fstype 'proc' \) -prune"42 only_directories = ('-type d' if self.quantifier else '')43 fzf_default_command = 'find -L . -mindepth 1 {} -o {} -o {} -print | cut -b3-'.format(44 hidden, exclude, only_directories45 )46 env = os.environ.copy()47 env['FZF_DEFAULT_COMMAND'] = fzf_default_command48 env['FZF_DEFAULT_OPTS'] = '--height=40% --layout=reverse --ansi --preview="{}"'.format('''49 (50 batcat --color=always {} ||51 bat --color=always {} ||52 cat {} ||53 tree -ahpCL 3 -I '.git' -I '*.py[co]' -I '__pycache__' {}54 ) 2>/dev/null | head -n 10055 ''')56 fzf = self.fm.execute_command('fzf --no-multi', env=env,57 universal_newlines=True, stdout=subprocess.PIPE)58 stdout, _ = fzf.communicate()59 if fzf.returncode == 0:60 selected = os.path.abspath(stdout.strip())61 if os.path.isdir(selected):62 self.fm.cd(selected)63 else:64 self.fm.select_file(selected)65class fzf_locate(Command):66 """67 :fzf_locate68 Find a file using fzf.69 With a prefix argument select only directories.70 See: https://github.com/junegunn/fzf71 """72 def execute(self):73 import subprocess74 if self.quantifier:75 command="locate home media | fzf -e -i"76 else:77 command="locate home media | fzf -e -i"78 fzf = self.fm.execute_command(command, stdout=subprocess.PIPE)79 stdout, stderr = fzf.communicate()80 if fzf.returncode == 0:81 fzf_file = os.path.abspath(stdout.decode('utf-8').rstrip('\n'))82 if os.path.isdir(fzf_file):83 self.fm.cd(fzf_file)84 else:85 self.fm.select_file(fzf_file)86class fd_search(Command):87 """88 :fd_search [-d<depth>] <query>89 Executes "fd -d<depth> <query>" in the current directory and focuses the90 first match. <depth> defaults to 1, i.e. only the contents of the current91 directory.92 See https://github.com/sharkdp/fd93 """94 SEARCH_RESULTS = deque()95 def execute(self):96 import re97 import subprocess98 from ranger.ext.get_executables import get_executables99 self.SEARCH_RESULTS.clear()100 if 'fdfind' in get_executables():101 fd = 'fdfind'102 elif 'fd' in get_executables():103 fd = 'fd'104 else:105 self.fm.notify("Couldn't find fd in the PATH.", bad=True)106 return107 if self.arg(1):108 if self.arg(1)[:2] == '-d':109 depth = self.arg(1)110 target = self.rest(2)111 else:112 depth = '-d1'113 target = self.rest(1)114 else:115 self.fm.notify(":fd_search needs a query.", bad=True)116 return117 hidden = ('--hidden' if self.fm.settings.show_hidden else '')118 exclude = "--no-ignore-vcs --exclude '.git' --exclude '*.py[co]' --exclude '__pycache__'"119 command = '{} --follow {} {} {} --print0 {}'.format(120 fd, depth, hidden, exclude, target121 )122 fd = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE)123 stdout, _ = fd.communicate()124 if fd.returncode == 0:125 results = filter(None, stdout.split('\0'))126 if not self.fm.settings.show_hidden and self.fm.settings.hidden_filter:127 hidden_filter = re.compile(self.fm.settings.hidden_filter)128 results = filter(lambda res: not hidden_filter.search(os.path.basename(res)), results)129 results = map(lambda res: os.path.abspath(os.path.join(self.fm.thisdir.path, res)), results)130 self.SEARCH_RESULTS.extend(sorted(results, key=str.lower))131 if len(self.SEARCH_RESULTS) > 0:132 self.fm.notify('Found {} result{}.'.format(len(self.SEARCH_RESULTS),133 ('s' if len(self.SEARCH_RESULTS) > 1 else '')))134 self.fm.select_file(self.SEARCH_RESULTS[0])135 else:136 self.fm.notify('No results found.')137class fd_next(Command):138 """139 :fd_next140 Selects the next match from the last :fd_search.141 """142 def execute(self):143 if len(fd_search.SEARCH_RESULTS) > 1:144 fd_search.SEARCH_RESULTS.rotate(-1) # rotate left145 self.fm.select_file(fd_search.SEARCH_RESULTS[0])146 elif len(fd_search.SEARCH_RESULTS) == 1:147 self.fm.select_file(fd_search.SEARCH_RESULTS[0])148class fd_prev(Command):149 """150 :fd_prev151 Selects the next match from the last :fd_search.152 """153 def execute(self):154 if len(fd_search.SEARCH_RESULTS) > 1:155 fd_search.SEARCH_RESULTS.rotate(1) # rotate right156 self.fm.select_file(fd_search.SEARCH_RESULTS[0])157 elif len(fd_search.SEARCH_RESULTS) == 1:158 self.fm.select_file(fd_search.SEARCH_RESULTS[0])159class fzf_rga_documents_search(Command):160 """161 :fzf_rga_search_documents162 Search in PDFs, E-Books and Office documents in current directory.163 Allowed extensions: .epub, .odt, .docx, .fb2, .ipynb, .pdf.164 Usage: fzf_rga_search_documents <search string>165 """166 def execute(self):167 if self.arg(1):168 search_string = self.rest(1)169 else:170 self.fm.notify("Usage: fzf_rga_search_documents <search string>", bad=True)171 return172 import subprocess173 import os.path174 from ranger.container.file import File175 command="rga '%s' . --rga-adapters=pandoc,poppler | fzf +m | awk -F':' '{print $1}'" % search_string176 fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE)177 stdout, stderr = fzf.communicate()178 if fzf.returncode == 0:179 fzf_file = os.path.abspath(stdout.rstrip('\n'))180 self.fm.execute_file(File(fzf_file))181class show_files_in_finder(Command):182 """183 :show_files_in_finder184 Present selected files in finder185 """186 def execute(self):187 import subprocess188 files = ",".join(['"{0}" as POSIX file'.format(file.path) for file in self.fm.thistab.get_selection()])189 reveal_script = "tell application \"Finder\" to reveal {{{0}}}".format(files)190 activate_script = "tell application \"Finder\" to set frontmost to true"191 script = "osascript -e '{0}' -e '{1}'".format(reveal_script, activate_script)192 self.fm.notify(script)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run refurb automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful