Skip to content

Commit

Permalink
Working on my config
Browse files Browse the repository at this point in the history
  • Loading branch information
tdeebswihart committed Jul 24, 2020
1 parent bf12a9d commit 8d9e83e
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 53 deletions.
4 changes: 0 additions & 4 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,6 @@
"destination": "~/Documents/Projects/doom-emacs"
},
"https://github.com/larkery/zsh-histdb.git": "~/.zsh-histdb/",
"https://github.com/asdf-vm/asdf.git": {
"destination": "~/.asdf",
"post-install": "cd ~/.asdf && git checkout \"$(git describe --abbrev=0 --tags)\""
},
"https://github.com/tarjoilija/zgen": {
"symlinks": {
"zgen.zsh": "~/.zgen.zsh",
Expand Down
6 changes: 1 addition & 5 deletions dots/.zshrc
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ if ! source "${HOME}/.zgen/init.zsh"; then
# Load zgen
source "${HOME}/.zgen.zsh"
echo "Creating a zgen save"

#zgen oh-my-zsh
zgen load hlissner/zsh-autopair
#zgen load zsh-users/zsh-syntax-highlighting
# Save it to an init script
zgen save
Expand All @@ -14,6 +13,3 @@ fpath=(~/.zsh $fpath)

# load built files
source ~/.config/zsh/config.sh

test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh"

102 changes: 60 additions & 42 deletions install.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from contextlib import contextmanager
from glob import glob
import json
import platform
from subprocess import check_output, STDOUT
from tempfile import NamedTemporaryFile
import sys
Expand All @@ -12,26 +11,29 @@
def is_str(s):
return isinstance(s, str)


def getpath(source):
if '@' in source:
if "@" in source:
# SSH
chunks = source.split(':')[-1].split('/')
site = source.split('@')[-1].split(':')[0]
chunks = source.split(":")[-1].split("/")
site = source.split("@")[-1].split(":")[0]
user = chunks[0]
repo = chunks[-1].replace('.git', '')
repo = chunks[-1].replace(".git", "")
else:
url = source.split('://')[-1]
chunks = url.split('/')
url = source.split("://")[-1]
chunks = url.split("/")
site, user, repo = chunks[:3]
return site, user, repo


@contextmanager
def chdir(path):
current = os.getcwd()
os.chdir(path)
yield
os.chdir(current)


def mkdir(path):
try:
os.makedirs(path)
Expand All @@ -45,19 +47,24 @@ def mkdir(path):

def runcmd(cmd):
out = check_output(cmd, shell=True, stderr=STDOUT)
return out.strip().decode(errors='ignore')
return out.strip().decode(errors="ignore")


def install_sources(sources):
# TODO: install from git if necessary under ~/.config/shell/SOURCE/NAME/repo
# TODO: handle the rest as normal
mkdir(os.path.expanduser('~/.config/zsh/repos'))
mkdir(os.path.expanduser("~/.config/zsh/repos"))
for source, config in sources.items():
if isinstance(config, str):
config = {"destination": config}
if isinstance(config, dict):
site, user, repo = getpath(source)
repo_dir = os.path.expanduser(config.get('destination', "~/.config/zsh/repos/{}/{}-{}".format(site, user, repo)))
repo_dir = os.path.expanduser(
config.get(
"destination",
"~/.config/zsh/repos/{}/{}-{}".format(site, user, repo),
)
)
if not os.path.isdir(repo_dir):
print("Cloning {}".format(source))
runcmd("git clone {} {}".format(source, repo_dir))
Expand All @@ -66,7 +73,10 @@ def install_sources(sources):
with chdir(repo_dir):
runcmd("git pull origin master")
# Add the repo dir
symlinks = {'{}/{}'.format(repo_dir, k): v for k, v in config.get('symlinks', {}).items()}
symlinks = {
"{}/{}".format(repo_dir, k): v
for k, v in config.get("symlinks", {}).items()
}
install_symlinks(symlinks)
post_install(config)
else:
Expand All @@ -76,116 +86,124 @@ def install_sources(sources):
def install_symlinks(config):
for src, dst in config.items():
# TODO: install
if not (src.startswith('/') or src.startswith('~')):
if not (src.startswith("/") or src.startswith("~")):
# relative paths are made absolute here
src = os.path.join(os.getcwd(), src)
sources = sorted(glob(os.path.expanduser(src)))
if not sources:
continue
if dst.endswith('/'):
if dst.endswith("/"):
# Its a directory. each file should be copied
for path in sources:
mkdir(os.path.expanduser(dst))
ldst = os.path.expanduser('{}{}'.format(dst, os.path.basename(path)))
ldst = os.path.expanduser("{}{}".format(dst, os.path.basename(path)))
if os.path.islink(ldst):
os.unlink(ldst)
elif os.path.exists(ldst):
raise RuntimeError('{} already exists and is not controlled by us!'.format(ldst))
raise RuntimeError(
"{} already exists and is not controlled by us!".format(ldst)
)
assert not os.path.islink(ldst)
path = os.path.expanduser(path)
os.symlink(path, ldst, target_is_directory=os.path.isdir(path))
elif os.path.isfile(sources[0]):
# Combine/link into file
dst = os.path.expanduser(dst)
mkdir(os.path.dirname(dst))
with open(dst, 'w') as outf:
outf.write('# AUTOMATICALLY GENERATED DO NOT EDIT! \n')
with open(dst, "w") as outf:
outf.write("# AUTOMATICALLY GENERATED DO NOT EDIT! \n")
for path in sources:
with open(path, 'r') as f:
outf.write('## {}\n'.format(path))
with open(path, "r") as f:
outf.write("## {}\n".format(path))
outf.write(f.read())
outf.write('\n')
outf.write("\n")
elif os.path.isdir(sources[0]):
ldst = os.path.expanduser(dst)
if os.path.islink(ldst):
os.unlink(ldst)
elif os.path.exists(ldst):
raise RuntimeError('{} already exists and is not controlled by us!'.format(ldst))
raise RuntimeError(
"{} already exists and is not controlled by us!".format(ldst)
)
assert not os.path.islink(ldst)
os.symlink(os.path.expanduser(path), ldst, target_is_directory=True)


def install_taps(taps):
for tap in taps:
runcmd('brew tap {}'.format(tap))
runcmd("brew tap {}".format(tap))


def install_brew(pkgs, tags):
already_installed = set(runcmd('brew list').strip().split('\n'))
already_installed = set(runcmd("brew list").strip().split("\n"))
to_install = set(pkgs) - already_installed
if to_install:
print('Installing {} homebrew formulae'.format(len(to_install)))
with NamedTemporaryFile('w') as tf:
tf.write('\n'.join(to_install))
print("Installing {} homebrew formulae".format(len(to_install)))
with NamedTemporaryFile("w") as tf:
tf.write("\n".join(to_install))
tf.flush()
runcmd('xargs <{} brew install'.format(tf.name))
runcmd("xargs <{} brew install".format(tf.name))


def install_casks(pkgs, tags):
# These need to be installed in a usable command line as some casks
# ask for a password
already_installed = set(runcmd('brew cask list').strip().split('\n'))
already_installed = set(runcmd("brew cask list").strip().split("\n"))
casks = []
for cask in pkgs:
if is_str(cask):
casks.append(cask)
elif isinstance(cask, dict):
if 'name' in cask and 'when' in cask and cask['when'] in tags:
casks.append(cask['name'])
if "name" in cask and "when" in cask and cask["when"] in tags:
casks.append(cask["name"])

to_install = set(casks) - already_installed
if to_install:
with open('/tmp/casks', 'w') as f:
f.write('\n'.join(to_install))
with open("/tmp/casks", "w") as f:
f.write("\n".join(to_install))


def install_mas(apps, tags):
appids = [runcmd(['mas search "{}"'.format(app)]).split(' ')[0] for app in apps]
already_installed = set(c.split()[0] for c in runcmd('mas list').strip().split('\n'))
appids = [runcmd(['mas search "{}"'.format(app)]).split(" ")[0] for app in apps]
already_installed = set(
c.split()[0] for c in runcmd("mas list").strip().split("\n")
)
to_install = set(appids) - already_installed
if to_install:
print('Installing {} apps from the Mac App Store'.format(len(to_install)))
print("Installing {} apps from the Mac App Store".format(len(to_install)))
with NamedTemporaryFile() as tf:
tf.write('\n'.join(to_install))
tf.write("\n".join(to_install))
tf.flush()
runcmd('xargs <{} mas install'.format(tf.name))
runcmd("xargs <{} mas install".format(tf.name))


def check_install_deps_macos():
pass


def post_install(config):
scripts = config.get('post-install', [])
scripts = config.get("post-install", [])
if isinstance(scripts, str):
scripts = [scripts]
for script in scripts:
runcmd(script)


def install_from_config(config_file, tags):
with open(config_file, 'r') as f:
with open(config_file, "r") as f:
config = json.loads(f.read(), object_pairs_hook=collections.OrderedDict)

try:
os.mkdir(os.path.expanduser("~/.config/zsh"))
except OSError:
pass
# FIXME: only do the following four on macos hosts
install_sources(config.get('sources', {}))
install_symlinks(config.get('symlinks', {}))
install_sources(config.get("sources", {}))
install_symlinks(config.get("symlinks", {}))
post_install(config)

if __name__ == '__main__':

if __name__ == "__main__":
if len(sys.argv) < 2:
print("{}: CONFIG [TAGS]")
sys.exit(1)
Expand Down
4 changes: 3 additions & 1 deletion launchagents/local.timods.watchman.plist
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<false/>
<key>ProgramArguments</key>
<array>
<string>/Users/timods/.local/bin/watchman</string>
<string> /usr/local/Cellar/watchman/4.9.0_4/libexec/bin/watchman
<string>--foreground</string>
<string>--logfile=/usr/local/var/run/watchman/timods-state/log</string>
<string>--log-level=1</string>
Expand All @@ -25,6 +25,8 @@
<true/>
<key>EnvironmentVariables</key>
<dict>
<key>PYTHONPATH</key>
<string>/usr/local/Cellar/watchman/4.9.0_4/libexec/lib/python3.8/site-packages</string>
<key>PATH</key>
<string><![CDATA[/Users/timods/.local/bin:/Users/timods/.cargo/bin:/opt/X11/bin:/usr/local/bin:/Users/timods/homebrew/sbin:/usr/bin:/bin:/usr/sbin:/sbin:]]></string>
</dict>
Expand Down
2 changes: 1 addition & 1 deletion zsh/nix.sh
Original file line number Diff line number Diff line change
@@ -1 +1 @@
test -f "$HOME/.nix-profile/etc/profile.d/nix.sh" && source "$HOME/.nix-profile/etc/profile.d/nix.sh"
if [ -e "$HOME/.nix-profile/etc/profile.d/nix.sh" ]; then . "$HOME/.nix-profile/etc/profile.d/nix.sh"; fi # added by Nix installer

0 comments on commit 8d9e83e

Please sign in to comment.