def show_bookmarks(bookmarks): names = [x["name"] for x in bookmarks] idx = search(names) if idx == -1: sys.exit(0) bookmark = bookmarks[idx] if "kw" in bookmark: search_code_and_goto(bookmark["kw"], path=bookmark["path"]) else: open_in_vscode(bookmark["path"])
def search_code_and_goto(text, path): print2(str(path)) result = [] if os.path.isdir(path): # directory result += search_code(text=text, search_path=path) else: # file or glob if "/**/" in path: dir_path, file_name = path.split("/**/") else: dir_path = os.path.dirname(path) file_name = os.path.basename(path) result += search_code(text=text, search_path=dir_path, extra_params=["-g", file_name]) if len(result) == 1: open_in_vscode(result[0][0], line_number=result[0][1]) elif len(result) > 1: indices = search([f"{x[0]}:{x[1]}" for x in result]) i = indices[0] open_in_vscode(result[i][0], line_number=result[i][1])
def edit_myscript_script(file): if os.path.splitext(file)[1] == ".link": file = open(file, "r", encoding="utf-8").read().strip() project_folder = os.path.realpath(os.path.dirname(__file__) + "/../") open_in_vscode([project_folder, file])
"overlay", "record", "screencap", "screenshot", "tmp", "video", ]: os.makedirs(os.path.join(proj_dir, d), exist_ok=True) # HACK: prepend_to_path(os.path.expandvars("%LOCALAPPDATA%\\ocenaudio")) jsconfig = os.path.join(proj_dir, "jsconfig.json") if not os.path.exists(jsconfig): with open(jsconfig, "w") as f: json.dump( { "compilerOptions": { "module": "commonjs", "target": "es2016", "jsx": "preserve", "baseUrl": os.path.abspath("movy/src").replace("\\", "/"), }, "exclude": ["node_modules", "**/node_modules/*"], }, f, indent=4, ) open_in_vscode([proj_dir, os.path.join(proj_dir, "index.md")])
def open_vscode(): open_in_vscode(os.getcwd())
from _shutil import * from _script import * from _editor import open_in_vscode mkdir("~/Projects") chdir("~/Projects") folder = os.path.basename("{{GIT_URL}}") folder = re.sub(".git$", "", folder) if not exists(folder): call("git clone %s --depth=1" % "{{GIT_URL}}") set_variable("GIT_REPO", os.path.realpath(folder)) open_in_vscode(folder)
def execute( self, args=None, new_window=None, restart_instance=None, close_on_exit=None, change_work_dir=True, ): script_path = ( self.real_script_path if self.real_script_path else self.script_path ) ext = self.real_ext if self.real_ext else self.ext # Save last executed script with open(_get_script_history_file(), "w") as f: json.dump({"file": script_path}, f) if ext == ".md": # with open(script_path, "r", encoding="utf-8") as f: # set_clip(f.read()) open_in_vscode(script_path) return if type(args) == str: args = [args] elif type(args) == list: args = args else: args = [] env = {} creationflags = 0 shell = False # Install packages if self.meta["packages"] is not None: packages = self.meta["packages"].split() for pkg in packages: get_executable(pkg) if "node" in packages: print("node package is required.") setup_nodejs(install=False) # HACK: pass current folder if "_CUR_DIR" in os.environ: env["_CUR_DIR"] = os.environ["_CUR_DIR"] if change_work_dir: cwd = os.path.abspath( os.path.join(os.getcwd(), os.path.dirname(script_path)) ) else: cwd = None if ext == ".ps1": if os.name == "nt": if self.meta["template"]: ps_path = write_temp_file(self.render(), ".ps1") else: ps_path = os.path.realpath(script_path) args = [ "PowerShell.exe", "-NoProfile", "-ExecutionPolicy", "unrestricted", ps_path, ] elif ext == ".ahk": if os.name == "nt": # HACK: add python path to env var env["PYTHONPATH"] = os.path.dirname(__file__) if self.meta["template"]: script_path = write_temp_file( self.render(), os.path.join( "GeneratedAhkScript/", os.path.basename(self.script_path) ), ) else: script_path = os.path.abspath(script_path) args = [get_ahk_exe(), script_path] self.meta["background"] = True if self.meta["runAsAdmin"]: args = ["start"] + args # Disable console window for ahk self.meta["newWindow"] = False # Avoid WinError 740: The requested operation requires elevation for AutoHotkeyU64_UIA.exe shell = True elif ext == ".cmd" or ext == ".bat": if os.name == "nt": if self.meta["template"]: batch_file = write_temp_file(self.render(), ".cmd") else: batch_file = os.path.realpath(script_path) args = ["cmd.exe", "/c", batch_file] + args # # HACK: change working directory # if platform.system() == 'Windows' and self.meta['runAsAdmin']: # args = ['cmd', '/c', # 'cd', '/d', cwd, '&'] + args else: print("OS does not support script: %s" % script_path) return elif ext == ".js": # TODO: if self.meta['template']: setup_nodejs() args = ["node", script_path] + args elif ext == ".sh": if self.meta["template"]: bash_cmd = self.render() else: bash_cmd = _args_to_str( [convert_to_unix_path(script_path, wsl=self.meta["wsl"])] + args ) args = wrap_bash_commands(bash_cmd, wsl=self.meta["wsl"], env=env) elif ext == ".py" or ext == ".ipynb": python_exec = sys.executable if self.meta["template"] and ext == ".py": python_file = write_temp_file(self.render(), ".py") else: python_file = os.path.realpath(script_path) if sys.platform == "win32" and self.meta["wsl"]: python_file = convert_to_unix_path(python_file, wsl=self.meta["wsl"]) python_exec = "python3" python_path = get_python_path(script_path) env["PYTHONPATH"] = os.pathsep.join(python_path) # env["PYTHONDONTWRITEBYTECODE"] = "1" # Conda / venv support args_activate = [] if self.meta["conda"] is not None: assert sys.platform == "win32" import _conda env_name = self.meta["conda"] conda_path = _conda.get_conda_path() activate = conda_path + "\\Scripts\\activate.bat" if env_name != "base" and not exists( conda_path + "\\envs\\" + env_name ): call_echo( 'call "%s" & conda create --name %s python=3.6' % (activate, env_name) ) args_activate = ["cmd", "/c", "call", activate, env_name, "&"] elif self.meta["venv"]: assert sys.platform == "win32" venv_path = os.path.expanduser("~\\venv\\%s" % self.meta["venv"]) if not exists(venv_path): call_echo(["python", "-m", "venv", venv_path]) args_activate = [ "cmd", "/c", "call", "%s\\Scripts\\activate.bat" % venv_path, "&", ] if ext == ".py": run_py = os.path.abspath( os.path.dirname(__file__) + "/../bin/run_python.py" ) # TODO: make it more general if sys.platform == "win32" and self.meta["wsl"]: run_py = convert_to_unix_path(run_py, wsl=self.meta["wsl"]) args = args_activate + [python_exec, run_py, python_file,] + args elif ext == ".ipynb": args = args_activate + ["jupyter", "notebook", python_file] + args # HACK: always use new window for jupyter notebook self.meta["newWindow"] = True else: assert False if self.meta["wsl"]: args = wrap_wsl(args) elif ext == ".vbs": assert os.name == "nt" script_abs_path = os.path.join(os.getcwd(), script_path) args = ["cscript", "//nologo", script_abs_path] else: print("Not supported script:", ext) # Run commands if args is not None and len(args) > 0: # Check if new window is needed if new_window is None: new_window = self.meta["newWindow"] if restart_instance is None: restart_instance = self.meta["restartInstance"] if restart_instance and new_window: # Only works on windows for now if platform.system() == "Windows": exec_ahk( "SetTitleMatchMode RegEx\nWinClose, ^" + re.escape(self.get_console_title()) + ", , , .*?- Visual Studio Code", wait=True, ) if new_window: # HACK: python wrapper: activate console window once finished # TODO: extra console window will be created when runAsAdmin & newWindow if sys.platform == "win32" and (not self.meta["runAsAdmin"]): # TODO: if not self.meta["wsl"] and False: args = [ sys.executable, "-c", ( "import subprocess;" "import ctypes;" 'import sys;sys.path.append(r"' + os.path.dirname(__file__) + '");' "import _script as s;" 's.set_console_title(r"' + self.get_console_title() + '");' "ret = subprocess.call(" + args + ");" "hwnd = ctypes.windll.kernel32.GetConsoleWindow();" "ctypes.windll.user32.SetForegroundWindow(hwnd);" 's.set_console_title(s.get_console_title() + " (Finished)");' "sys.exit(ret)" ), ] # Create new terminal using Windows Terminal try: if self.meta["terminal"] is None: args = wt_wrap_args( args, cwd=cwd, title=self.get_console_title(), wsl=self.meta["wsl"], close_on_exit=( close_on_exit if close_on_exit is not None else self.meta["closeOnExit"] ), ) elif self.meta["terminal"] == "conemu": args = conemu_wrap_args( args, cwd=cwd, title=self.get_console_title(), wsl=self.meta["wsl"], always_on_top=True, ) else: raise Exception( "Non-supported terminal: %s" % self.meta["terminal"] ) except Exception as e: print("Error on Windows Terminal:", e) if os.path.exists(r"C:\Program Files\Git\usr\bin\mintty.exe"): args = [ r"C:\Program Files\Git\usr\bin\mintty.exe", "--hold", "always", ] + args elif sys.platform == "linux": args = ["tmux", "split-window"] + args # args = ["x-terminal-emulator", "-e"] + args else: creationflags = subprocess.CREATE_NEW_CONSOLE # raise Exception( # "newWindow flag is not supported on target platform." # ) # Check if run as admin if platform.system() == "Windows" and self.meta["runAsAdmin"]: # Set environment variables through command lines bin_path = os.path.abspath(os.path.dirname(__file__) + "/../bin") set_env_var = [] for k, v in env.items(): set_env_var += ["set", "%s=%s" % (k, v), "&"] args = ( ["cmd", "/c"] + ( ["title", self.get_console_title(), "&"] if ext != ".ahk" else [] ) + ["cd", "/d", cwd, "&"] + ["set", "PATH=" + bin_path + ";%PATH%", "&"] + set_env_var + args ) print2("Run elevated:") print2(_args_to_str(args), color="cyan") run_elevated(args, wait=(not new_window)) else: if new_window or self.meta["background"]: # Check whether or not hide window startupinfo = None if self.meta["background"]: if platform.system() == "Windows": SW_HIDE = 0 startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW startupinfo.wShowWindow = SW_HIDE creationflags = subprocess.CREATE_NEW_CONSOLE print(args) subprocess.Popen( args, env={**os.environ, **env}, cwd=cwd, startupinfo=startupinfo, creationflags=creationflags, close_fds=True, shell=shell, ) else: subprocess.check_call(args, env={**os.environ, **env}, cwd=cwd)