-
-
Save Pyrestone/105c837f8aab14bd833d5807b2c43751 to your computer and use it in GitHub Desktop.
Initialize zoxide history from `cd` commands in .bash_history
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import shlex | |
# save our current directory so we know where to write the file in the end | |
INITIAL_CWD=os.path.abspath(os.getcwd()) | |
home_dir=os.environ["HOME"] | |
dirs=[] | |
# get all the paths we cd'd to in the past | |
with open(f"{home_dir}/.bash_history") as file: | |
for line in file: | |
try: | |
tokens=shlex.split(line.strip()) | |
except: | |
continue | |
if("cd" in tokens): | |
save_next=False | |
for t in tokens: | |
if t=="cd": | |
save_next=True | |
continue | |
if save_next: | |
dirs.append(t) | |
save_next=False | |
visited_dirs=[] | |
# get absolute paths | |
os.chdir(home_dir) | |
cwd=os.path.abspath(os.getcwd()) | |
last_cwd=cwd | |
for dir in dirs: | |
try: | |
# try to read it as an absolute path | |
if(os.path.isabs(dir)): | |
os.chdir(dir) | |
last_cwd=cwd | |
cwd=os.path.abspath(os.getcwd()) | |
if(cwd!=last_cwd): | |
visited_dirs.append(cwd) | |
# try to read it relative to CWD (unless CWD is ~) | |
if(os.path.abspath(home_dir)!=os.path.abspath(cwd) and os.path.isdir(dir)): | |
os.chdir(dir) | |
last_cwd=cwd | |
cwd=os.path.abspath(os.getcwd()) | |
if(cwd!=last_cwd): | |
visited_dirs.append(cwd) | |
# try to read it relative to CWD (unless we're just going up one dir) | |
if(os.path.isdir(os.path.join(home_dir,dir))) and dir!="..": | |
os.chdir(os.path.join(home_dir,dir)) | |
last_cwd=cwd | |
cwd=os.path.abspath(os.getcwd()) | |
if(cwd!=last_cwd): | |
visited_dirs.append(cwd) | |
except: | |
pass | |
for dir in visited_dirs: | |
assert(os.path.isdir(dir) and os.path.isabs(dir)) | |
os.chdir(INITIAL_CWD) | |
# build one long zoxide add command: | |
cmd=["zoxide","add"]+visited_dirs | |
command=shlex.join(cmd) | |
with open("add_command.bash","w") as file: | |
file.write(command) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment