Merge branch 'ohmyzsh:master' into recursive_dotenv

This commit is contained in:
Heitor Polidoro 2024-05-22 15:00:38 -03:00 committed by GitHub
commit af3825e13e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
123 changed files with 1323 additions and 629 deletions

View file

@ -6,3 +6,6 @@ insert_final_newline = true
charset = utf-8 charset = utf-8
indent_size = 2 indent_size = 2
indent_style = space indent_style = space
[*.py]
indent_size = 4

View file

@ -36,3 +36,11 @@ dependencies:
precopy: | precopy: |
set -e set -e
find . ! -name _gradle ! -name LICENSE -delete find . ! -name _gradle ! -name LICENSE -delete
plugins/wd:
repo: mfaerevaag/wd
branch: master
version: tag:v0.7.0
precopy: |
set -e
rm -r test
rm install.sh tty.gif wd.1

View file

@ -1,8 +1,8 @@
name: Update dependencies name: Update dependencies
on: on:
workflow_dispatch: {} workflow_dispatch: {}
# schedule: schedule:
# - cron: '34 3 * * */8' - cron: "0 6 * * 0"
jobs: jobs:
check: check:
@ -12,12 +12,19 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Authenticate as @ohmyzsh - name: Authenticate as @ohmyzsh
id: generate_token id: generate_token
uses: ohmyzsh/github-app-token@v2 uses: ohmyzsh/github-app-token@v2
with: with:
app_id: ${{ secrets.OHMYZSH_APP_ID }} app_id: ${{ secrets.OHMYZSH_APP_ID }}
private_key: ${{ secrets.OHMYZSH_APP_PRIVATE_KEY }} private_key: ${{ secrets.OHMYZSH_APP_PRIVATE_KEY }}
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: "pip"
- name: Process dependencies - name: Process dependencies
env: env:
GH_TOKEN: ${{ steps.generate_token.outputs.token }} GH_TOKEN: ${{ steps.generate_token.outputs.token }}

View file

@ -1,2 +1,7 @@
PyYAML~=6.0.1 certifi==2024.2.2
requests~=2.31.0 charset-normalizer==3.3.2
idna==3.7
PyYAML==6.0.1
requests==2.31.0
semver==3.0.2
urllib3==2.2.1

View file

@ -1,11 +1,16 @@
import json
import os import os
import re
import shutil
import subprocess import subprocess
import sys import sys
import requests import timeit
import shutil
import yaml
from copy import deepcopy from copy import deepcopy
from typing import Optional, TypedDict from typing import Literal, NotRequired, Optional, TypedDict
import requests
import yaml
from semver import Version
# Get TMP_DIR variable from environment # Get TMP_DIR variable from environment
TMP_DIR = os.path.join(os.environ.get("TMP_DIR", "/tmp"), "ohmyzsh") TMP_DIR = os.path.join(os.environ.get("TMP_DIR", "/tmp"), "ohmyzsh")
@ -14,17 +19,46 @@ DEPS_YAML_FILE = ".github/dependencies.yml"
# Dry run flag # Dry run flag
DRY_RUN = os.environ.get("DRY_RUN", "0") == "1" DRY_RUN = os.environ.get("DRY_RUN", "0") == "1"
import timeit # utils for tag comparison
BASEVERSION = re.compile(
r"""[vV]?
(?P<major>(0|[1-9])\d*)
(\.
(?P<minor>(0|[1-9])\d*)
(\.
(?P<patch>(0|[1-9])\d*)
)?
)?
""",
re.VERBOSE,
)
def coerce(version: str) -> Optional[Version]:
match = BASEVERSION.search(version)
if not match:
return None
# BASEVERSION looks for `MAJOR.minor.patch` in the string given
# it fills with None if any of them is missing (for example `2.1`)
ver = {
key: 0 if value is None else value for key, value in match.groupdict().items()
}
# Version takes `major`, `minor`, `patch` arguments
ver = Version(**ver) # pyright: ignore[reportArgumentType]
return ver
class CodeTimer: class CodeTimer:
def __init__(self, name=None): def __init__(self, name=None):
self.name = " '" + name + "'" if name else '' self.name = " '" + name + "'" if name else ""
def __enter__(self): def __enter__(self):
self.start = timeit.default_timer() self.start = timeit.default_timer()
def __exit__(self, exc_type, exc_value, traceback): def __exit__(self, exc_type, exc_value, traceback):
self.took = (timeit.default_timer() - self.start) * 1000.0 self.took = (timeit.default_timer() - self.start) * 1000.0
print('Code block' + self.name + ' took: ' + str(self.took) + ' ms') print("Code block" + self.name + " took: " + str(self.took) + " ms")
### YAML representation ### YAML representation
@ -34,8 +68,9 @@ def str_presenter(dumper, data):
Ref: https://stackoverflow.com/a/33300001 Ref: https://stackoverflow.com/a/33300001
""" """
if len(data.splitlines()) > 1: # check for multiline string if len(data.splitlines()) > 1: # check for multiline string
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|")
return dumper.represent_scalar('tag:yaml.org,2002:str', data) return dumper.represent_scalar("tag:yaml.org,2002:str", data)
yaml.add_representer(str, str_presenter) yaml.add_representer(str, str_presenter)
yaml.representer.SafeRepresenter.add_representer(str, str_presenter) yaml.representer.SafeRepresenter.add_representer(str, str_presenter)
@ -46,18 +81,24 @@ class DependencyDict(TypedDict):
repo: str repo: str
branch: str branch: str
version: str version: str
precopy: Optional[str] precopy: NotRequired[str]
postcopy: Optional[str] postcopy: NotRequired[str]
class DependencyYAML(TypedDict): class DependencyYAML(TypedDict):
dependencies: dict[str, DependencyDict] dependencies: dict[str, DependencyDict]
class UpdateStatus(TypedDict):
has_updates: bool class UpdateStatusFalse(TypedDict):
version: Optional[str] has_updates: Literal[False]
compare_url: Optional[str]
head_ref: Optional[str]
head_url: Optional[str] class UpdateStatusTrue(TypedDict):
has_updates: Literal[True]
version: str
compare_url: str
head_ref: str
head_url: str
class CommandRunner: class CommandRunner:
@ -78,19 +119,18 @@ class CommandRunner:
if result.returncode != 0: if result.returncode != 0:
raise CommandRunner.Exception( raise CommandRunner.Exception(
f"{stage} command failed with exit code {result.returncode}", returncode=result.returncode, f"{stage} command failed with exit code {result.returncode}",
returncode=result.returncode,
stage=stage, stage=stage,
stdout=result.stdout.decode("utf-8"), stdout=result.stdout.decode("utf-8"),
stderr=result.stderr.decode("utf-8") stderr=result.stderr.decode("utf-8"),
) )
return result return result
class DependencyStore: class DependencyStore:
store: DependencyYAML = { store: DependencyYAML = {"dependencies": {}}
"dependencies": {}
}
@staticmethod @staticmethod
def set(data: DependencyYAML): def set(data: DependencyYAML):
@ -101,7 +141,9 @@ class DependencyStore:
with CodeTimer(f"store deepcopy: {path}"): with CodeTimer(f"store deepcopy: {path}"):
store_copy = deepcopy(DependencyStore.store) store_copy = deepcopy(DependencyStore.store)
dependency = store_copy["dependencies"].get(path, {}) dependency = store_copy["dependencies"].get(path)
if dependency is None:
raise ValueError(f"Dependency {path} {version} not found")
dependency["version"] = version dependency["version"] = version
store_copy["dependencies"][path] = dependency store_copy["dependencies"][path] = dependency
@ -136,7 +178,7 @@ class Dependency:
def __str__(self): def __str__(self):
output: str = "" output: str = ""
for key in DependencyDict.__dict__['__annotations__'].keys(): for key in DependencyDict.__dict__["__annotations__"].keys():
if key not in self.values: if key not in self.values:
output += f"{key}: None\n" output += f"{key}: None\n"
continue continue
@ -167,23 +209,28 @@ class Dependency:
else: else:
status = GitHub.check_updates(repo, remote_branch, version) status = GitHub.check_updates(repo, remote_branch, version)
if status["has_updates"]: if status["has_updates"] is True:
short_sha = status["head_ref"][:8] short_sha = status["head_ref"][:8]
new_version = status["version"] if is_tag else short_sha new_version = status["version"] if is_tag else short_sha
try: try:
branch_name = f"update/{self.path}/{new_version}"
# Create new branch # Create new branch
branch = Git.create_branch(self.path, new_version) branch = Git.checkout_or_create_branch(branch_name)
# Update dependencies.yml file # Update dependencies.yml file
self.__update_yaml(f"tag:{new_version}" if is_tag else status["version"]) self.__update_yaml(
f"tag:{new_version}" if is_tag else status["version"]
)
# Update dependency files # Update dependency files
self.__apply_upstream_changes() self.__apply_upstream_changes()
# Add all changes and commit # Add all changes and commit
Git.add_and_commit(self.name, short_sha) has_new_commit = Git.add_and_commit(self.name, short_sha)
if has_new_commit:
# Push changes to remote # Push changes to remote
Git.push(branch) Git.push(branch)
@ -195,7 +242,7 @@ class Dependency:
Update for **{self.desc}**: update to version [{new_version}]({status['head_url']}). Update for **{self.desc}**: update to version [{new_version}]({status['head_url']}).
Check out the [list of changes]({status['compare_url']}). Check out the [list of changes]({status['compare_url']}).
""" """,
) )
# Clean up repository # Clean up repository
@ -205,30 +252,34 @@ Check out the [list of changes]({status['compare_url']}).
match type(e): match type(e):
case CommandRunner.Exception: case CommandRunner.Exception:
# Print error message # Print error message
print(f"Error running {e.stage} command: {e.returncode}", file=sys.stderr) print(
print(e.stderr, file=sys.stderr) f"Error running {e.stage} command: {e.returncode}", # pyright: ignore[reportAttributeAccessIssue]
file=sys.stderr,
)
print(e.stderr, file=sys.stderr) # pyright: ignore[reportAttributeAccessIssue]
case shutil.Error: case shutil.Error:
print(f"Error copying files: {e}", file=sys.stderr) print(f"Error copying files: {e}", file=sys.stderr)
try: try:
Git.clean_repo() Git.clean_repo()
except CommandRunner.Exception as e: except CommandRunner.Exception as e:
print(f"Error reverting repository to clean state: {e}", file=sys.stderr) print(
f"Error reverting repository to clean state: {e}",
file=sys.stderr,
)
sys.exit(1) sys.exit(1)
# Create a GitHub issue to notify maintainer # Create a GitHub issue to notify maintainer
title = f"{self.path}: update to {new_version}" title = f"{self.path}: update to {new_version}"
body = ( body = f"""## Description
f"""## Description
There is a new version of `{self.name}` {self.kind} available. There is a new version of `{self.name}` {self.kind} available.
New version: [{new_version}]({status['head_url']}) New version: [{new_version}]({status['head_url']})
Check out the [list of changes]({status['compare_url']}). Check out the [list of changes]({status['compare_url']}).
""" """
)
print(f"Creating GitHub issue", file=sys.stderr) print("Creating GitHub issue", file=sys.stderr)
print(f"{title}\n\n{body}", file=sys.stderr) print(f"{title}\n\n{body}", file=sys.stderr)
GitHub.create_issue(title, body) GitHub.create_issue(title, body)
except Exception as e: except Exception as e:
@ -240,11 +291,7 @@ Check out the [list of changes]({status['compare_url']}).
def __apply_upstream_changes(self) -> None: def __apply_upstream_changes(self) -> None:
# Patterns to ignore in copying files from upstream repo # Patterns to ignore in copying files from upstream repo
GLOBAL_IGNORE = [ GLOBAL_IGNORE = [".git", ".github", ".gitignore"]
".git",
".github",
".gitignore"
]
path = os.path.abspath(self.path) path = os.path.abspath(self.path)
precopy = self.values.get("precopy") precopy = self.values.get("precopy")
@ -261,18 +308,32 @@ Check out the [list of changes]({status['compare_url']}).
# Run precopy on tmp repo # Run precopy on tmp repo
if precopy is not None: if precopy is not None:
print("Running precopy script:", end="\n ", file=sys.stderr) print("Running precopy script:", end="\n ", file=sys.stderr)
print(precopy.replace("\n", "\n ", precopy.count("\n") - 1), file=sys.stderr) print(
CommandRunner.run_or_fail(["bash", "-c", precopy], cwd=repo_dir, stage="Precopy") precopy.replace("\n", "\n ", precopy.count("\n") - 1), file=sys.stderr
)
CommandRunner.run_or_fail(
["bash", "-c", precopy], cwd=repo_dir, stage="Precopy"
)
# Copy files from upstream repo # Copy files from upstream repo
print(f"Copying files from {repo_dir} to {path}", file=sys.stderr) print(f"Copying files from {repo_dir} to {path}", file=sys.stderr)
shutil.copytree(repo_dir, path, dirs_exist_ok=True, ignore=shutil.ignore_patterns(*GLOBAL_IGNORE)) shutil.copytree(
repo_dir,
path,
dirs_exist_ok=True,
ignore=shutil.ignore_patterns(*GLOBAL_IGNORE),
)
# Run postcopy on our repository # Run postcopy on our repository
if postcopy is not None: if postcopy is not None:
print("Running postcopy script:", end="\n ", file=sys.stderr) print("Running postcopy script:", end="\n ", file=sys.stderr)
print(postcopy.replace("\n", "\n ", postcopy.count("\n") - 1), file=sys.stderr) print(
CommandRunner.run_or_fail(["bash", "-c", postcopy], cwd=path, stage="Postcopy") postcopy.replace("\n", "\n ", postcopy.count("\n") - 1),
file=sys.stderr,
)
CommandRunner.run_or_fail(
["bash", "-c", postcopy], cwd=path, stage="Postcopy"
)
class Git: class Git:
@ -286,22 +347,52 @@ class Git:
# Clone repo in tmp directory and checkout branch # Clone repo in tmp directory and checkout branch
if not os.path.exists(repo_dir): if not os.path.exists(repo_dir):
print(f"Cloning {remote_url} to {repo_dir} and checking out {branch}", file=sys.stderr) print(
CommandRunner.run_or_fail(["git", "clone", "--depth=1", "-b", branch, remote_url, repo_dir], stage="Clone") f"Cloning {remote_url} to {repo_dir} and checking out {branch}",
file=sys.stderr,
)
CommandRunner.run_or_fail(
["git", "clone", "--depth=1", "-b", branch, remote_url, repo_dir],
stage="Clone",
)
@staticmethod @staticmethod
def create_branch(path: str, version: str): def checkout_or_create_branch(branch_name: str):
# Get current branch name # Get current branch name
result = CommandRunner.run_or_fail(["git", "rev-parse", "--abbrev-ref", "HEAD"], stage="GetDefaultBranch") result = CommandRunner.run_or_fail(
["git", "rev-parse", "--abbrev-ref", "HEAD"], stage="GetDefaultBranch"
)
Git.default_branch = result.stdout.decode("utf-8").strip() Git.default_branch = result.stdout.decode("utf-8").strip()
# Create new branch and return created branch name # Create new branch and return created branch name
branch_name = f"update/{path}/{version}" try:
CommandRunner.run_or_fail(["git", "checkout", "-b", branch_name], stage="CreateBranch") # try to checkout already existing branch
CommandRunner.run_or_fail(
["git", "checkout", branch_name], stage="CreateBranch"
)
except CommandRunner.Exception:
# otherwise create new branch
CommandRunner.run_or_fail(
["git", "checkout", "-b", branch_name], stage="CreateBranch"
)
return branch_name return branch_name
@staticmethod @staticmethod
def add_and_commit(scope: str, version: str): def add_and_commit(scope: str, version: str) -> bool:
"""
Returns `True` if there were changes and were indeed commited.
Returns `False` if the repo was clean and no changes were commited.
"""
# check if repo is clean (clean => no error, no commit)
try:
CommandRunner.run_or_fail(
["git", "diff", "--exit-code"], stage="CheckRepoClean"
)
return False
except CommandRunner.Exception:
# if it's other kind of error just throw!
pass
user_name = os.environ.get("GIT_APP_NAME") user_name = os.environ.get("GIT_APP_NAME")
user_email = os.environ.get("GIT_APP_EMAIL") user_email = os.environ.get("GIT_APP_EMAIL")
@ -310,37 +401,56 @@ class Git:
# Reset environment and git config # Reset environment and git config
clean_env = os.environ.copy() clean_env = os.environ.copy()
clean_env["LANG"]="C.UTF-8" clean_env["LANG"] = "C.UTF-8"
clean_env["GIT_CONFIG_GLOBAL"]="/dev/null" clean_env["GIT_CONFIG_GLOBAL"] = "/dev/null"
clean_env["GIT_CONFIG_NOSYSTEM"]="1" clean_env["GIT_CONFIG_NOSYSTEM"] = "1"
# Commit with settings above # Commit with settings above
CommandRunner.run_or_fail([ CommandRunner.run_or_fail(
[
"git", "git",
"-c", f"user.name={user_name}", "-c",
"-c", f"user.email={user_email}", f"user.name={user_name}",
"-c",
f"user.email={user_email}",
"commit", "commit",
"-m", f"feat({scope}): update to {version}" "-m",
], stage="CreateCommit", env=clean_env) f"feat({scope}): update to {version}",
],
stage="CreateCommit",
env=clean_env,
)
return True
@staticmethod @staticmethod
def push(branch: str): def push(branch: str):
CommandRunner.run_or_fail(["git", "push", "-u", "origin", branch], stage="PushBranch") CommandRunner.run_or_fail(
["git", "push", "-u", "origin", branch], stage="PushBranch"
)
@staticmethod @staticmethod
def clean_repo(): def clean_repo():
CommandRunner.run_or_fail(["git", "reset", "--hard", "HEAD"], stage="ResetRepository") CommandRunner.run_or_fail(
CommandRunner.run_or_fail(["git", "checkout", Git.default_branch], stage="CheckoutDefaultBranch") ["git", "reset", "--hard", "HEAD"], stage="ResetRepository"
)
CommandRunner.run_or_fail(
["git", "checkout", Git.default_branch], stage="CheckoutDefaultBranch"
)
class GitHub: class GitHub:
@staticmethod @staticmethod
def check_newer_tag(repo, current_tag) -> UpdateStatus: def check_newer_tag(repo, current_tag) -> UpdateStatusFalse | UpdateStatusTrue:
# GET /repos/:owner/:repo/git/refs/tags # GET /repos/:owner/:repo/git/refs/tags
url = f"https://api.github.com/repos/{repo}/git/refs/tags" url = f"https://api.github.com/repos/{repo}/git/refs/tags"
# Send a GET request to the GitHub API # Send a GET request to the GitHub API
response = requests.get(url) response = requests.get(url)
current_version = coerce(current_tag)
if current_version is None:
raise ValueError(
f"Stored {current_version} from {repo} does not follow semver"
)
# If the request was successful # If the request was successful
if response.status_code == 200: if response.status_code == 200:
@ -352,10 +462,27 @@ class GitHub:
"has_updates": False, "has_updates": False,
} }
latest_ref = data[-1] latest_ref = None
latest_version: Optional[Version] = None
for ref in data:
# we find the tag since GitHub returns it as plain git ref
tag_version = coerce(ref["ref"].replace("refs/tags/", ""))
if tag_version is None:
# we skip every tag that is not semver-complaint
continue
if latest_version is None or tag_version.compare(latest_version) > 0:
# if we have a "greater" semver version, set it as latest
latest_version = tag_version
latest_ref = ref
# raise if no valid semver tag is found
if latest_ref is None or latest_version is None:
raise ValueError(f"No tags following semver found in {repo}")
# we get the tag since GitHub returns it as plain git ref
latest_tag = latest_ref["ref"].replace("refs/tags/", "") latest_tag = latest_ref["ref"].replace("refs/tags/", "")
if latest_tag == current_tag: if latest_version.compare(current_version) <= 0:
return { return {
"has_updates": False, "has_updates": False,
} }
@ -369,13 +496,12 @@ class GitHub:
} }
else: else:
# If the request was not successful, raise an exception # If the request was not successful, raise an exception
raise Exception(f"GitHub API request failed with status code {response.status_code}: {response.json()}") raise Exception(
f"GitHub API request failed with status code {response.status_code}: {response.json()}"
)
@staticmethod @staticmethod
def check_updates(repo, branch, version) -> UpdateStatus: def check_updates(repo, branch, version) -> UpdateStatusFalse | UpdateStatusTrue:
# TODO: add support for semver updating (based on tags)
# Check if upstream github repo has a new version
# GitHub API URL for comparing two commits
url = f"https://api.github.com/repos/{repo}/compare/{version}...{branch}" url = f"https://api.github.com/repos/{repo}/compare/{version}...{branch}"
# Send a GET request to the GitHub API # Send a GET request to the GitHub API
@ -399,33 +525,54 @@ class GitHub:
"version": data["commits"][-1]["sha"], "version": data["commits"][-1]["sha"],
"compare_url": data["permalink_url"], "compare_url": data["permalink_url"],
"head_ref": data["commits"][-1]["sha"], "head_ref": data["commits"][-1]["sha"],
"head_url": data["commits"][-1]["html_url"] "head_url": data["commits"][-1]["html_url"],
} }
else: else:
# If the request was not successful, raise an exception # If the request was not successful, raise an exception
raise Exception(f"GitHub API request failed with status code {response.status_code}: {response.json()}") raise Exception(
f"GitHub API request failed with status code {response.status_code}: {response.json()}"
)
@staticmethod @staticmethod
def create_issue(title: str, body: str) -> None: def create_issue(title: str, body: str) -> None:
cmd = [ cmd = ["gh", "issue", "create", "-t", title, "-b", body]
"gh",
"issue",
"create",
"-t", title,
"-b", body
]
CommandRunner.run_or_fail(cmd, stage="CreateIssue") CommandRunner.run_or_fail(cmd, stage="CreateIssue")
@staticmethod @staticmethod
def create_pr(branch: str, title: str, body: str) -> None: def create_pr(branch: str, title: str, body: str) -> None:
# first of all let's check if PR is already open
check_cmd = [
"gh",
"pr",
"list",
"--state",
"open",
"--head",
branch,
"--json",
"title",
]
# returncode is 0 also if no PRs are found
output = json.loads(
CommandRunner.run_or_fail(check_cmd, stage="CheckPullRequestOpen")
.stdout.decode("utf-8")
.strip()
)
# we have PR in this case!
if len(output) > 0:
return
cmd = [ cmd = [
"gh", "gh",
"pr", "pr",
"create", "create",
"-B", Git.default_branch, "-B",
"-H", branch, Git.default_branch,
"-t", title, "-H",
"-b", body branch,
"-t",
title,
"-b",
body,
] ]
CommandRunner.run_or_fail(cmd, stage="CreatePullRequest") CommandRunner.run_or_fail(cmd, stage="CreatePullRequest")
@ -436,7 +583,7 @@ def main():
data: DependencyYAML = yaml.safe_load(yaml_file) data: DependencyYAML = yaml.safe_load(yaml_file)
if "dependencies" not in data: if "dependencies" not in data:
raise Exception(f"dependencies.yml not properly formatted") raise Exception("dependencies.yml not properly formatted")
# Cache YAML version # Cache YAML version
DependencyStore.set(data) DependencyStore.set(data)
@ -446,5 +593,6 @@ def main():
dependency = Dependency(path, dependencies[path]) dependency = Dependency(path, dependencies[path])
dependency.update_or_notify() dependency.update_or_notify()
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View file

@ -43,6 +43,7 @@ To learn more, visit [ohmyz.sh](https://ohmyz.sh), follow [@ohmyzsh](https://twi
- [Custom Plugins And Themes](#custom-plugins-and-themes) - [Custom Plugins And Themes](#custom-plugins-and-themes)
- [Enable GNU ls In macOS And freeBSD Systems](#enable-gnu-ls-in-macos-and-freebsd-systems) - [Enable GNU ls In macOS And freeBSD Systems](#enable-gnu-ls-in-macos-and-freebsd-systems)
- [Skip Aliases](#skip-aliases) - [Skip Aliases](#skip-aliases)
- [Disable async git prompt](#disable-async-git-prompt)
- [Getting Updates](#getting-updates) - [Getting Updates](#getting-updates)
- [Updates Verbosity](#updates-verbosity) - [Updates Verbosity](#updates-verbosity)
- [Manual Updates](#manual-updates) - [Manual Updates](#manual-updates)
@ -361,6 +362,17 @@ Instead, you can now use the following:
zstyle ':omz:lib:directories' aliases no zstyle ':omz:lib:directories' aliases no
``` ```
### Disable async git prompt
Async prompt functions are an experimental feature (included on April 3, 2024) that allows Oh My Zsh to render prompt information
asyncronously. This can improve prompt rendering performance, but it might not work well with some setups. We hope that's not an
issue, but if you're seeing problems with this new feature, you can turn it off by setting the following in your .zshrc file,
before Oh My Zsh is sourced:
```sh
zstyle ':omz:alpha:lib:git' async-prompt no
```
#### Notice <!-- omit in toc --> #### Notice <!-- omit in toc -->
> This feature is currently in a testing phase and it may be subject to change in the future. > This feature is currently in a testing phase and it may be subject to change in the future.

View file

@ -3,6 +3,7 @@
# https://github.com/woefe/git-prompt.zsh/blob/master/git-prompt.zsh # https://github.com/woefe/git-prompt.zsh/blob/master/git-prompt.zsh
zmodload zsh/system zmodload zsh/system
autoload -Uz is-at-least
# For now, async prompt function handlers are set up like so: # For now, async prompt function handlers are set up like so:
# First, define the async function handler and register the handler # First, define the async function handler and register the handler
@ -82,10 +83,8 @@ function _omz_async_request {
exec {fd}< <( exec {fd}< <(
# Tell parent process our PID # Tell parent process our PID
builtin echo ${sysparams[pid]} builtin echo ${sysparams[pid]}
# Store handler name for callback
builtin echo $handler
# Set exit code for the handler if used # Set exit code for the handler if used
(exit $ret) () { return $ret }
# Run the async function handler # Run the async function handler
$handler $handler
) )
@ -95,11 +94,11 @@ function _omz_async_request {
# There's a weird bug here where ^C stops working unless we force a fork # There's a weird bug here where ^C stops working unless we force a fork
# See https://github.com/zsh-users/zsh-autosuggestions/issues/364 # See https://github.com/zsh-users/zsh-autosuggestions/issues/364
command true # and https://github.com/zsh-users/zsh-autosuggestions/pull/612
is-at-least 5.8 || command true
# Save the PID from the handler child process # Save the PID from the handler child process
read pid <&$fd read -u $fd "_OMZ_ASYNC_PIDS[$handler]"
_OMZ_ASYNC_PIDS[$handler]=$pid
# When the fd is readable, call the response handler # When the fd is readable, call the response handler
zle -F "$fd" _omz_async_callback zle -F "$fd" _omz_async_callback
@ -114,19 +113,18 @@ function _omz_async_callback() {
local err=$2 # Second arg will be passed in case of error local err=$2 # Second arg will be passed in case of error
if [[ -z "$err" || "$err" == "hup" ]]; then if [[ -z "$err" || "$err" == "hup" ]]; then
# Get handler name from first line # Get handler name from fd
local handler local handler="${(k)_OMZ_ASYNC_FDS[(r)$fd]}"
read handler <&$fd
# Store old output which is supposed to be already printed # Store old output which is supposed to be already printed
local old_output="${_OMZ_ASYNC_OUTPUT[$handler]}" local old_output="${_OMZ_ASYNC_OUTPUT[$handler]}"
# Read output from fd # Read output from fd
_OMZ_ASYNC_OUTPUT[$handler]="$(cat <&$fd)" IFS= read -r -u $fd -d '' "_OMZ_ASYNC_OUTPUT[$handler]"
# Repaint prompt if output has changed # Repaint prompt if output has changed
if [[ "$old_output" != "${_OMZ_ASYNC_OUTPUT[$handler]}" ]]; then if [[ "$old_output" != "${_OMZ_ASYNC_OUTPUT[$handler]}" ]]; then
zle reset-prompt zle .reset-prompt
zle -R zle -R
fi fi

View file

@ -241,10 +241,18 @@ function _omz::plugin::disable {
# Remove plugins substitution awk script # Remove plugins substitution awk script
local awk_subst_plugins="\ local awk_subst_plugins="\
gsub(/[ \t]+(${(j:|:)dis_plugins})/, \"\") # with spaces before gsub(/[ \t]+(${(j:|:)dis_plugins})[ \t]+/, \" \") # with spaces before or after
gsub(/(${(j:|:)dis_plugins})[ \t]+/, \"\") # with spaces after gsub(/[ \t]+(${(j:|:)dis_plugins})$/, \"\") # with spaces before and EOL
gsub(/\((${(j:|:)dis_plugins})\)/, \"\") # without spaces (only plugin) gsub(/^(${(j:|:)dis_plugins})[ \t]+/, \"\") # with BOL and spaces after
gsub(/\((${(j:|:)dis_plugins})[ \t]+/, \"(\") # with parenthesis before and spaces after
gsub(/[ \t]+(${(j:|:)dis_plugins})\)/, \")\") # with spaces before or parenthesis after
gsub(/\((${(j:|:)dis_plugins})\)/, \"()\") # with only parentheses
gsub(/^(${(j:|:)dis_plugins})\)/, \")\") # with BOL and closing parenthesis
gsub(/\((${(j:|:)dis_plugins})$/, \"(\") # with opening parenthesis and EOL
" "
# Disable plugins awk script # Disable plugins awk script
local awk_script=" local awk_script="
# if plugins=() is in oneline form, substitute disabled plugins and go to next line # if plugins=() is in oneline form, substitute disabled plugins and go to next line
@ -773,7 +781,17 @@ function _omz::theme::use {
} }
function _omz::update { function _omz::update {
local last_commit=$(builtin cd -q "$ZSH"; git rev-parse HEAD) # Check if git command is available
(( $+commands[git] )) || {
_omz::log error "git is not installed. Aborting..."
return 1
}
local last_commit=$(builtin cd -q "$ZSH"; git rev-parse HEAD 2>/dev/null)
[[ $? -eq 0 ]] || {
_omz::log error "\`$ZSH\` is not a git directory. Aborting..."
return 1
}
# Run update script # Run update script
zstyle -s ':omz:update' verbose verbose_mode || verbose_mode=default zstyle -s ':omz:update' verbose verbose_mode || verbose_mode=default

View file

@ -1,3 +1,5 @@
autoload -Uz is-at-least
# The git prompt's git commands are read-only and should not interfere with # The git prompt's git commands are read-only and should not interfere with
# other processes. This environment variable is equivalent to running with `git # other processes. This environment variable is equivalent to running with `git
# --no-optional-locks`, but falls back gracefully for older versions of git. # --no-optional-locks`, but falls back gracefully for older versions of git.
@ -9,7 +11,7 @@ function __git_prompt_git() {
GIT_OPTIONAL_LOCKS=0 command git "$@" GIT_OPTIONAL_LOCKS=0 command git "$@"
} }
function _omz_git_prompt_status() { function _omz_git_prompt_info() {
# If we are on a folder not tracked by git, get out. # If we are on a folder not tracked by git, get out.
# Otherwise, check for hide-info at global and local repository level # Otherwise, check for hide-info at global and local repository level
if ! __git_prompt_git rev-parse --git-dir &> /dev/null \ if ! __git_prompt_git rev-parse --git-dir &> /dev/null \
@ -37,11 +39,17 @@ function _omz_git_prompt_status() {
echo "${ZSH_THEME_GIT_PROMPT_PREFIX}${ref:gs/%/%%}${upstream:gs/%/%%}$(parse_git_dirty)${ZSH_THEME_GIT_PROMPT_SUFFIX}" echo "${ZSH_THEME_GIT_PROMPT_PREFIX}${ref:gs/%/%%}${upstream:gs/%/%%}$(parse_git_dirty)${ZSH_THEME_GIT_PROMPT_SUFFIX}"
} }
# Enable async prompt by default unless the setting is at false / no # Use async version if setting is enabled or undefined
if zstyle -t ':omz:alpha:lib:git' async-prompt; then if zstyle -T ':omz:alpha:lib:git' async-prompt; then
function git_prompt_info() { function git_prompt_info() {
if [[ -n "$_OMZ_ASYNC_OUTPUT[_omz_git_prompt_status]" ]]; then if [[ -n "${_OMZ_ASYNC_OUTPUT[_omz_git_prompt_info]}" ]]; then
echo -n "$_OMZ_ASYNC_OUTPUT[_omz_git_prompt_status]" echo -n "${_OMZ_ASYNC_OUTPUT[_omz_git_prompt_info]}"
fi
}
function git_prompt_status() {
if [[ -n "${_OMZ_ASYNC_OUTPUT[_omz_git_prompt_status]}" ]]; then
echo -n "${_OMZ_ASYNC_OUTPUT[_omz_git_prompt_status]}"
fi fi
} }
@ -49,10 +57,15 @@ if zstyle -t ':omz:alpha:lib:git' async-prompt; then
# or any of the other prompt variables # or any of the other prompt variables
function _defer_async_git_register() { function _defer_async_git_register() {
# Check if git_prompt_info is used in a prompt variable # Check if git_prompt_info is used in a prompt variable
case "${PS1}:${PS2}:${PS3}:${PS4}:${RPS1}:${RPS2}:${RPS3}:${RPS4}" in case "${PS1}:${PS2}:${PS3}:${PS4}:${RPROMPT}:${RPS1}:${RPS2}:${RPS3}:${RPS4}" in
*(\$\(git_prompt_info\)|\`git_prompt_info\`)*) *(\$\(git_prompt_info\)|\`git_prompt_info\`)*)
_omz_register_handler _omz_git_prompt_info
;;
esac
case "${PS1}:${PS2}:${PS3}:${PS4}:${RPROMPT}:${RPS1}:${RPS2}:${RPS3}:${RPS4}" in
*(\$\(git_prompt_status\)|\`git_prompt_status\`)*)
_omz_register_handler _omz_git_prompt_status _omz_register_handler _omz_git_prompt_status
return
;; ;;
esac esac
@ -65,6 +78,9 @@ if zstyle -t ':omz:alpha:lib:git' async-prompt; then
precmd_functions=(_defer_async_git_register $precmd_functions) precmd_functions=(_defer_async_git_register $precmd_functions)
else else
function git_prompt_info() { function git_prompt_info() {
_omz_git_prompt_info
}
function git_prompt_status() {
_omz_git_prompt_status _omz_git_prompt_status
} }
fi fi
@ -197,7 +213,7 @@ function git_prompt_long_sha() {
SHA=$(__git_prompt_git rev-parse HEAD 2> /dev/null) && echo "$ZSH_THEME_GIT_PROMPT_SHA_BEFORE$SHA$ZSH_THEME_GIT_PROMPT_SHA_AFTER" SHA=$(__git_prompt_git rev-parse HEAD 2> /dev/null) && echo "$ZSH_THEME_GIT_PROMPT_SHA_BEFORE$SHA$ZSH_THEME_GIT_PROMPT_SHA_AFTER"
} }
function git_prompt_status() { function _omz_git_prompt_status() {
[[ "$(__git_prompt_git config --get oh-my-zsh.hide-status 2>/dev/null)" = 1 ]] && return [[ "$(__git_prompt_git config --get oh-my-zsh.hide-status 2>/dev/null)" = 1 ]] && return
# Maps a git status prefix to an internal constant # Maps a git status prefix to an internal constant

View file

@ -1,19 +1,20 @@
## History wrapper ## History wrapper
function omz_history { function omz_history {
local clear list # parse arguments and remove from $@
zparseopts -E c=clear l=list local clear list stamp
zparseopts -E -D c=clear l=list f=stamp E=stamp i=stamp t:=stamp
if [[ -n "$clear" ]]; then if [[ -n "$clear" ]]; then
# if -c provided, clobber the history file # if -c provided, clobber the history file
echo -n >| "$HISTFILE" echo -n >| "$HISTFILE"
fc -p "$HISTFILE" fc -p "$HISTFILE"
echo >&2 History file deleted. echo >&2 History file deleted.
elif [[ -n "$list" ]]; then elif [[ $# -eq 0 ]]; then
# if -l provided, run as if calling `fc' directly # if no arguments provided, show full history starting from 1
builtin fc "$@" builtin fc $stamp -l 1
else else
# unless a number is provided, show all history events (starting from 1) # otherwise, run `fc -l` with a custom format
[[ ${@[-1]-} = *[0-9]* ]] && builtin fc -l "$@" || builtin fc -l "$@" 1 builtin fc $stamp -l "$@"
fi fi
} }

View file

@ -17,7 +17,7 @@ function title {
: ${2=$1} : ${2=$1}
case "$TERM" in case "$TERM" in
cygwin|xterm*|putty*|rxvt*|konsole*|ansi|mlterm*|alacritty|st*|foot*|contour*) cygwin|xterm*|putty*|rxvt*|konsole*|ansi|mlterm*|alacritty*|st*|foot*|contour*)
print -Pn "\e]2;${2:q}\a" # set window name print -Pn "\e]2;${2:q}\a" # set window name
print -Pn "\e]1;${1:q}\a" # set tab name print -Pn "\e]1;${1:q}\a" # set tab name
;; ;;
@ -129,7 +129,7 @@ fi
# Don't define the function if we're in an unsupported terminal # Don't define the function if we're in an unsupported terminal
case "$TERM" in case "$TERM" in
# all of these either process OSC 7 correctly or ignore entirely # all of these either process OSC 7 correctly or ignore entirely
xterm*|putty*|rxvt*|konsole*|mlterm*|alacritty|screen*|tmux*) ;; xterm*|putty*|rxvt*|konsole*|mlterm*|alacritty*|screen*|tmux*) ;;
contour*|foot*) ;; contour*|foot*) ;;
*) *)
# Terminal.app and iTerm2 process OSC 7 correctly # Terminal.app and iTerm2 process OSC 7 correctly

169
lib/tests/cli.test.zsh Normal file
View file

@ -0,0 +1,169 @@
#!/usr/bin/zsh -df
run_awk() {
local -a dis_plugins=(${=1})
local input_text="$2"
(( ! DEBUG )) || set -xv
local awk_subst_plugins="\
gsub(/[ \t]+(${(j:|:)dis_plugins})[ \t]+/, \" \") # with spaces before or after
gsub(/[ \t]+(${(j:|:)dis_plugins})$/, \"\") # with spaces before and EOL
gsub(/^(${(j:|:)dis_plugins})[ \t]+/, \"\") # with BOL and spaces after
gsub(/\((${(j:|:)dis_plugins})[ \t]+/, \"(\") # with parenthesis before and spaces after
gsub(/[ \t]+(${(j:|:)dis_plugins})\)/, \")\") # with spaces before or parenthesis after
gsub(/\((${(j:|:)dis_plugins})\)/, \"()\") # with only parentheses
gsub(/^(${(j:|:)dis_plugins})\)/, \")\") # with BOL and closing parenthesis
gsub(/\((${(j:|:)dis_plugins})$/, \"(\") # with opening parenthesis and EOL
"
# Disable plugins awk script
local awk_script="
# if plugins=() is in oneline form, substitute disabled plugins and go to next line
/^[ \t]*plugins=\([^#]+\).*\$/ {
$awk_subst_plugins
print \$0
next
}
# if plugins=() is in multiline form, enable multi flag and disable plugins if they're there
/^[ \t]*plugins=\(/ {
multi=1
$awk_subst_plugins
print \$0
next
}
# if multi flag is enabled and we find a valid closing parenthesis, remove plugins and disable multi flag
multi == 1 && /^[^#]*\)/ {
multi=0
$awk_subst_plugins
print \$0
next
}
multi == 1 && length(\$0) > 0 {
$awk_subst_plugins
if (length(\$0) > 0) print \$0
next
}
{ print \$0 }
"
command awk "$awk_script" <<< "$input_text"
(( ! DEBUG )) || set +xv
}
# runs awk against stdin, checks if the resulting file is not empty and then checks if the file has valid zsh syntax
run_awk_and_test() {
local description="$1"
local plugins_to_disable="$2"
local input_text="$3"
local expected_output="$4"
local tmpfile==(:)
{
print -u2 "Test: $description"
DEBUG=0 run_awk "$plugins_to_disable" "$input_text" >| $tmpfile
if [[ ! -s "$tmpfile" ]]; then
print -u2 "\e[31mError\e[0m: output file empty"
return 1
fi
if ! zsh -n $tmpfile; then
print -u2 "\e[31mError\e[0m: zsh syntax error"
diff -u $tmpfile <(echo "$expected_output")
return 1
fi
if ! diff -u --color=always $tmpfile <(echo "$expected_output"); then
if (( DEBUG )); then
print -u2 ""
DEBUG=1 run_awk "$plugins_to_disable" "$input_text"
print -u2 ""
fi
print -u2 "\e[31mError\e[0m: output file does not match expected output"
return 1
fi
print -u2 "\e[32mSuccess\e[0m"
} always {
print -u2 ""
command rm -f "$tmpfile"
}
}
# These tests are for the `omz plugin disable` command
run_awk_and_test \
"it should delete a single plugin in oneline format" \
"git" \
"plugins=(git)" \
"plugins=()"
run_awk_and_test \
"it should delete a single plugin in multiline format" \
"github" \
"plugins=(
github
)" \
"plugins=(
)"
run_awk_and_test \
"it should delete multiple plugins in oneline format" \
"github git z" \
"plugins=(github git z)" \
"plugins=()"
run_awk_and_test \
"it should delete multiple plugins in multiline format" \
"github git z" \
"plugins=(
github
git
z
)" \
"plugins=(
)"
run_awk_and_test \
"it should delete a single plugin among multiple in oneline format" \
"git" \
"plugins=(github git z)" \
"plugins=(github z)"
run_awk_and_test \
"it should delete a single plugin among multiple in multiline format" \
"git" \
"plugins=(
github
git
z
)" \
"plugins=(
github
z
)"
run_awk_and_test \
"it should delete multiple plugins in mixed format" \
"git z" \
"plugins=(github
git z)" \
"plugins=(github
)"
run_awk_and_test \
"it should delete multiple plugins in mixed format 2" \
"github z" \
"plugins=(github
git
z)" \
"plugins=(
git
)"

View file

@ -179,8 +179,8 @@ fi
# Check Arch Linux PGP Keyring before System Upgrade to prevent failure. # Check Arch Linux PGP Keyring before System Upgrade to prevent failure.
function upgrade() { function upgrade() {
echo ":: Checking Arch Linux PGP Keyring..." echo ":: Checking Arch Linux PGP Keyring..."
local installedver="$(sudo pacman -Qi archlinux-keyring | grep -Po '(?<=Version : ).*')" local installedver="$(LANG= sudo pacman -Qi archlinux-keyring | grep -Po '(?<=Version : ).*')"
local currentver="$(sudo pacman -Si archlinux-keyring | grep -Po '(?<=Version : ).*')" local currentver="$(LANG= sudo pacman -Si archlinux-keyring | grep -Po '(?<=Version : ).*')"
if [ $installedver != $currentver ]; then if [ $installedver != $currentver ]; then
echo " Arch Linux PGP Keyring is out of date." echo " Arch Linux PGP Keyring is out of date."
echo " Updating before full system upgrade." echo " Updating before full system upgrade."

View file

@ -13,7 +13,9 @@ autojump_paths=(
/opt/local/etc/profile.d/autojump.sh # macOS with MacPorts /opt/local/etc/profile.d/autojump.sh # macOS with MacPorts
/usr/local/etc/profile.d/autojump.sh # macOS with Homebrew (default) /usr/local/etc/profile.d/autojump.sh # macOS with Homebrew (default)
/opt/homebrew/etc/profile.d/autojump.sh # macOS with Homebrew (default on M1 macs) /opt/homebrew/etc/profile.d/autojump.sh # macOS with Homebrew (default on M1 macs)
/opt/pkg/share/autojump/autojump.zsh # macOS with pkgsrc
/etc/profiles/per-user/$USER/etc/profile.d/autojump.sh # macOS Nix, Home Manager and flakes /etc/profiles/per-user/$USER/etc/profile.d/autojump.sh # macOS Nix, Home Manager and flakes
/nix/var/nix/gcroots/current-system/sw/share/zsh/site-functions/autojump.zsh # macOS Nix, nix-darwin
) )
for file in $autojump_paths; do for file in $autojump_paths; do

View file

@ -2,7 +2,7 @@
# onto the system clipboard # onto the system clipboard
copybuffer () { copybuffer () {
if which clipcopy &>/dev/null; then if builtin which clipcopy &>/dev/null; then
printf "%s" "$BUFFER" | clipcopy printf "%s" "$BUFFER" | clipcopy
else else
zle -M "clipcopy not found. Please make sure you have Oh My Zsh installed correctly." zle -M "clipcopy not found. Please make sure you have Oh My Zsh installed correctly."

View file

@ -87,7 +87,7 @@ EOF
builtin cd -q control; extract ../control.tar.* builtin cd -q control; extract ../control.tar.*
builtin cd -q ../data; extract ../data.tar.* builtin cd -q ../data; extract ../data.tar.*
builtin cd -q ..; command rm *.tar.* debian-binary ;; builtin cd -q ..; command rm *.tar.* debian-binary ;;
(*.zst) unzstd "$full_path" ;; (*.zst) unzstd --stdout "$full_path" > "${file:t:r}" ;;
(*.cab|*.exe) cabextract "$full_path" ;; (*.cab|*.exe) cabextract "$full_path" ;;
(*.cpio|*.obscpio) cpio -idmvF "$full_path" ;; (*.cpio|*.obscpio) cpio -idmvF "$full_path" ;;
(*.zpaq) zpaq x "$full_path" ;; (*.zpaq) zpaq x "$full_path" ;;

View file

@ -1,3 +1,16 @@
function fzf_setup_using_fzf() {
(( ${+commands[fzf]} )) || return 1
# we remove "fzf " prefix, this fixes really old fzf versions behaviour
# see https://github.com/ohmyzsh/ohmyzsh/issues/12387
local fzf_ver=${"$(fzf --version)"#fzf }
autoload -Uz is-at-least
is-at-least 0.48.0 ${${(s: :)fzf_ver}[1]} || return 1
eval "$(fzf --zsh)"
}
function fzf_setup_using_base_dir() { function fzf_setup_using_base_dir() {
local fzf_base fzf_shell fzfdirs dir local fzf_base fzf_shell fzfdirs dir
@ -135,6 +148,27 @@ function fzf_setup_using_opensuse() {
return 0 return 0
} }
function fzf_setup_using_fedora() {
(( $+commands[fzf] )) || return 1
local completions="/usr/share/zsh/site-functions/fzf"
local key_bindings="/usr/share/fzf/shell/key-bindings.zsh"
if [[ ! -f "$completions" || ! -f "$key_bindings" ]]; then
return 1
fi
if [[ -o interactive && "$DISABLE_FZF_AUTO_COMPLETION" != "true" ]]; then
source "$completions" 2>/dev/null
fi
if [[ "$DISABLE_FZF_KEY_BINDINGS" != "true" ]]; then
source "$key_bindings" 2>/dev/null
fi
return 0
}
function fzf_setup_using_openbsd() { function fzf_setup_using_openbsd() {
# openBSD installs fzf in /usr/local/bin/fzf # openBSD installs fzf in /usr/local/bin/fzf
if [[ "$OSTYPE" != openbsd* ]] || (( ! $+commands[fzf] )); then if [[ "$OSTYPE" != openbsd* ]] || (( ! $+commands[fzf] )); then
@ -217,9 +251,11 @@ Please add `export FZF_BASE=/path/to/fzf/install/dir` to your .zshrc
EOF EOF
} }
fzf_setup_using_openbsd \ fzf_setup_using_fzf \
|| fzf_setup_using_openbsd \
|| fzf_setup_using_debian \ || fzf_setup_using_debian \
|| fzf_setup_using_opensuse \ || fzf_setup_using_opensuse \
|| fzf_setup_using_fedora \
|| fzf_setup_using_cygwin \ || fzf_setup_using_cygwin \
|| fzf_setup_using_macports \ || fzf_setup_using_macports \
|| fzf_setup_using_base_dir \ || fzf_setup_using_base_dir \

View file

@ -9,6 +9,7 @@ if [[ -z "${CLOUDSDK_HOME}" ]]; then
"/usr/local/share/google-cloud-sdk" "/usr/local/share/google-cloud-sdk"
"/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk" "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk"
"/opt/homebrew/Caskroom/google-cloud-sdk/latest/google-cloud-sdk" "/opt/homebrew/Caskroom/google-cloud-sdk/latest/google-cloud-sdk"
"/opt/homebrew/share/google-cloud-sdk"
"/usr/share/google-cloud-sdk" "/usr/share/google-cloud-sdk"
"/snap/google-cloud-sdk/current" "/snap/google-cloud-sdk/current"
"/snap/google-cloud-cli/current" "/snap/google-cloud-cli/current"

View file

@ -9,6 +9,10 @@ To use it, add `git-prompt` to the plugins array in your zshrc file:
plugins=(... git-prompt) plugins=(... git-prompt)
``` ```
You may also need to [customize your theme](https://github.com/ohmyzsh/ohmyzsh/issues/9395#issuecomment-1027130429)
to change the way the prompt is built. See the
[OMZ wiki on customizing themes](https://github.com/ohmyzsh/ohmyzsh/wiki/Customization#overriding-and-adding-themes).
See the [original repository](https://github.com/olivierverdier/zsh-git-prompt). See the [original repository](https://github.com/olivierverdier/zsh-git-prompt).
## Requirements ## Requirements

View file

@ -41,8 +41,8 @@ plugins=(... git)
| `gba` | `git branch --all` | | `gba` | `git branch --all` |
| `gbd` | `git branch --delete` | | `gbd` | `git branch --delete` |
| `gbD` | `git branch --delete --force` | | `gbD` | `git branch --delete --force` |
| `gbgd` | `LANG=C git branch --no-color -vv \| grep ": gone\]" \| awk '"'"'{print $1}'"'"' \| xargs git branch -d` | | `gbgd` | `LANG=C git branch --no-color -vv \| grep ": gone\]" \| cut -c 3- \| awk '"'"'{print $1}'"'"' \| xargs git branch -d` |
| `gbgD` | `LANG=C git branch --no-color -vv \| grep ": gone\]" \| awk '"'"'{print $1}'"'"' \| xargs git branch -D` | | `gbgD` | `LANG=C git branch --no-color -vv \| grep ": gone\]" \| cut -c 3- \| awk '"'"'{print $1}'"'"' \| xargs git branch -D` |
| `gbm` | `git branch --move` | | `gbm` | `git branch --move` |
| `gbnm` | `git branch --no-merged` | | `gbnm` | `git branch --no-merged` |
| `gbr` | `git branch --remote` | | `gbr` | `git branch --remote` |
@ -111,6 +111,7 @@ plugins=(... git)
| `gfg` | `git ls-files \| grep` | | `gfg` | `git ls-files \| grep` |
| `gm` | `git merge` | | `gm` | `git merge` |
| `gma` | `git merge --abort` | | `gma` | `git merge --abort` |
| `gmc` | `git merge --continue` |
| `gms` | `git merge --squash` | | `gms` | `git merge --squash` |
| `gmom` | `git merge origin/$(git_main_branch)` | | `gmom` | `git merge origin/$(git_main_branch)` |
| `gmum` | `git merge upstream/$(git_main_branch)` | | `gmum` | `git merge upstream/$(git_main_branch)` |
@ -166,6 +167,7 @@ plugins=(... git)
| `grhk` | `git reset --keep` | | `grhk` | `git reset --keep` |
| `grhs` | `git reset --soft` | | `grhs` | `git reset --soft` |
| `gpristine` | `git reset --hard && git clean --force -dfx` | | `gpristine` | `git reset --hard && git clean --force -dfx` |
| `gwipe` | `git reset --hard && git clean --force -df` |
| `groh` | `git reset origin/$(git_current_branch) --hard` | | `groh` | `git reset origin/$(git_current_branch) --hard` |
| `grs` | `git restore` | | `grs` | `git restore` |
| `grss` | `git restore --source` | | `grss` | `git restore --source` |

View file

@ -147,8 +147,8 @@ function gbds() {
done done
} }
alias gbgd='LANG=C git branch --no-color -vv | grep ": gone\]" | awk '"'"'{print $1}'"'"' | xargs git branch -d' alias gbgd='LANG=C git branch --no-color -vv | grep ": gone\]" | cut -c 3- | awk '"'"'{print $1}'"'"' | xargs git branch -d'
alias gbgD='LANG=C git branch --no-color -vv | grep ": gone\]" | awk '"'"'{print $1}'"'"' | xargs git branch -D' alias gbgD='LANG=C git branch --no-color -vv | grep ": gone\]" | cut -c 3- | awk '"'"'{print $1}'"'"' | xargs git branch -D'
alias gbm='git branch --move' alias gbm='git branch --move'
alias gbnm='git branch --no-merged' alias gbnm='git branch --no-merged'
alias gbr='git branch --remote' alias gbr='git branch --remote'
@ -252,6 +252,7 @@ alias gignored='git ls-files -v | grep "^[[:lower:]]"'
alias gfg='git ls-files | grep' alias gfg='git ls-files | grep'
alias gm='git merge' alias gm='git merge'
alias gma='git merge --abort' alias gma='git merge --abort'
alias gmc='git merge --continue'
alias gms="git merge --squash" alias gms="git merge --squash"
alias gmom='git merge origin/$(git_main_branch)' alias gmom='git merge origin/$(git_main_branch)'
alias gmum='git merge upstream/$(git_main_branch)' alias gmum='git merge upstream/$(git_main_branch)'
@ -349,6 +350,7 @@ alias grhh='git reset --hard'
alias grhk='git reset --keep' alias grhk='git reset --keep'
alias grhs='git reset --soft' alias grhs='git reset --soft'
alias gpristine='git reset --hard && git clean --force -dfx' alias gpristine='git reset --hard && git clean --force -dfx'
alias gwipe='git reset --hard && git clean --force -df'
alias groh='git reset origin/$(git_current_branch) --hard' alias groh='git reset origin/$(git_current_branch) --hard'
alias grs='git restore' alias grs='git restore'
alias grss='git restore --source' alias grss='git restore --source'

View file

@ -1,4 +1,4 @@
#compdef http #compdef http https
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
# Copyright (c) 2015 GitHub zsh-users - http://github.com/zsh-users # Copyright (c) 2015 GitHub zsh-users - http://github.com/zsh-users
# All rights reserved. # All rights reserved.

View file

@ -16,18 +16,21 @@ This plugin supplies one command, `jira`, through which all its features are exp
## Commands ## Commands
`jira help` or `jira usage` will print the below usage instructions
| Command | Description | | Command | Description |
| :------------ | :-------------------------------------------------------- | | :------------ | :-------------------------------------------------------- |
| `jira` | Performs the default action | | `jira` | Performs the default action |
| `jira new` | Opens a new Jira issue dialogue | | `jira new` | Opens a new Jira issue dialogue |
| `jira ABC-123` | Opens an existing issue | | `jira ABC-123` | Opens an existing issue |
| `jira ABC-123 m` | Opens an existing issue for adding a comment | | `jira ABC-123 m` | Opens an existing issue for adding a comment |
| `jira dashboard [rapid_view]` | # opens your JIRA dashboard | | `jira dashboard [rapid_view]` | Opens your JIRA dashboard |
| `jira mine` | Queries for your own issues | | `jira mine` | Queries for your own issues |
| `jira tempo` | Opens your JIRA Tempo | | `jira tempo` | Opens your JIRA Tempo |
| `jira reported [username]` | Queries for issues reported by a user | | `jira reported [username]` | Queries for issues reported by a user |
| `jira assigned [username]` | Queries for issues assigned to a user | | `jira assigned [username]` | Queries for issues assigned to a user |
| `jira branch` | Opens an existing issue matching the current branch name | | `jira branch` | Opens an existing issue matching the current branch name |
| `jira help` | Prints usage instructions |
### Jira Branch usage notes ### Jira Branch usage notes

View file

@ -11,6 +11,7 @@ _1st_arguments=(
'assigned:search for issues assigned to a user' 'assigned:search for issues assigned to a user'
'branch:open the issue named after the git branch of the current directory' 'branch:open the issue named after the git branch of the current directory'
'dumpconfig:display effective jira configuration' 'dumpconfig:display effective jira configuration'
'help:print usage help to stdout'
) )
_arguments -C \ _arguments -C \

View file

@ -2,6 +2,21 @@
# #
# See README.md for details # See README.md for details
function _jira_usage() {
cat <<EOF
jira Performs the default action
jira new Opens a new Jira issue dialogue
jira ABC-123 Opens an existing issue
jira ABC-123 m Opens an existing issue for adding a comment
jira dashboard [rapid_view] Opens your JIRA dashboard
jira mine Queries for your own issues
jira tempo Opens your JIRA Tempo
jira reported [username] Queries for issues reported by a user
jira assigned [username] Queries for issues assigned to a user
jira branch Opens an existing issue matching the current branch name
EOF
}
function jira() { function jira() {
emulate -L zsh emulate -L zsh
local action jira_url jira_prefix local action jira_url jira_prefix
@ -44,6 +59,8 @@ function jira() {
open_command "${jira_url}/secure/CreateIssue!default.jspa" open_command "${jira_url}/secure/CreateIssue!default.jspa"
elif [[ "$action" == "assigned" || "$action" == "reported" ]]; then elif [[ "$action" == "assigned" || "$action" == "reported" ]]; then
_jira_query ${@:-$action} _jira_query ${@:-$action}
elif [[ "$action" == "help" || "$action" == "usage" ]]; then
_jira_usage
elif [[ "$action" == "mine" ]]; then elif [[ "$action" == "mine" ]]; then
echo "Opening my issues" echo "Opening my issues"
open_command "${jira_url}/issues/?filter=-1" open_command "${jira_url}/issues/?filter=-1"

View file

@ -10,6 +10,7 @@ plugins=(... laravel)
|:-:|:-:| |:-:|:-:|
| `artisan` | `php artisan` | | `artisan` | `php artisan` |
| `pas` | `php artisan serve` | | `pas` | `php artisan serve` |
| `pats` | `php artisan test` |
## Database ## Database
@ -35,6 +36,10 @@ plugins=(... laravel)
| `pamj` | `php artisan make:job` | | `pamj` | `php artisan make:job` |
| `paml` | `php artisan make:listener` | | `paml` | `php artisan make:listener` |
| `pamn` | `php artisan make:notification` | | `pamn` | `php artisan make:notification` |
| `pamcl` | `php artisan make:class` |
| `pamen` | `php artisan make:enum` |
| `pami` | `php artisan make:interface` |
| `pamtr` | `php artisan make:trait` |
## Clears ## Clears

View file

@ -4,6 +4,7 @@ alias bob='php artisan bob::build'
# Development # Development
alias pas='php artisan serve' alias pas='php artisan serve'
alias pats='php artisan test'
# Database # Database
alias pam='php artisan migrate' alias pam='php artisan migrate'
@ -24,6 +25,10 @@ alias pamj='php artisan make:job'
alias paml='php artisan make:listener' alias paml='php artisan make:listener'
alias pamn='php artisan make:notification' alias pamn='php artisan make:notification'
alias pampp='php artisan make:provider' alias pampp='php artisan make:provider'
alias pamcl='php artisan make:class'
alias pamen='php artisan make:enum'
alias pami='php artisan make:interface'
alias pamtr='php artisan make:trait'
# Clears # Clears

View file

@ -17,7 +17,7 @@ Original author: [Sorin Ionescu](https://github.com/sorin-ionescu)
| `tab` | Open the current directory in a new tab | | `tab` | Open the current directory in a new tab |
| `split_tab` | Split the current terminal tab horizontally | | `split_tab` | Split the current terminal tab horizontally |
| `vsplit_tab` | Split the current terminal tab vertically | | `vsplit_tab` | Split the current terminal tab vertically |
| `ofd` | Open the current directory in a Finder window | | `ofd` | Open passed directories (or $PWD by default) in Finder |
| `pfd` | Return the path of the frontmost Finder window | | `pfd` | Return the path of the frontmost Finder window |
| `pfs` | Return the current Finder selection | | `pfs` | Return the current Finder selection |
| `cdf` | `cd` to the current Finder directory | | `cdf` | `cd` to the current Finder directory |

View file

@ -3,8 +3,15 @@
0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}" 0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}"
0="${${(M)0:#/*}:-$PWD/$0}" 0="${${(M)0:#/*}:-$PWD/$0}"
# Open the current directory in a Finder window # Open in Finder the directories passed as arguments, or the current directory if
alias ofd='open_command $PWD' # no directories are passed
function ofd {
if (( ! $# )); then
open_command $PWD
else
open_command $@
fi
}
# Show/hide hidden files in the Finder # Show/hide hidden files in the Finder
alias showfiles="defaults write com.apple.finder AppleShowAllFiles -bool true && killall Finder" alias showfiles="defaults write com.apple.finder AppleShowAllFiles -bool true && killall Finder"

View file

@ -11,6 +11,9 @@ fi
# Load mise hooks # Load mise hooks
eval "$($__mise activate zsh)" eval "$($__mise activate zsh)"
# Hook mise into current environment
eval "$($__mise hook-env -s zsh)"
# If the completion file doesn't exist yet, we need to autoload it and # If the completion file doesn't exist yet, we need to autoload it and
# bind it to `mise`. Otherwise, compinit will have already done that. # bind it to `mise`. Otherwise, compinit will have already done that.
if [[ ! -f "$ZSH_CACHE_DIR/completions/_$__mise" ]]; then if [[ ! -f "$ZSH_CACHE_DIR/completions/_$__mise" ]]; then

View file

@ -26,9 +26,9 @@ These settings should go in your zshrc file, before Oh My Zsh is sourced:
#### Lazy startup #### Lazy startup
This option will help you to defer nvm's load until you use it to speed-up your zsh startup. This will source This option will help you to defer nvm's load until you use it to speed-up your zsh startup. This will source
nvm script only when using it, and will create a function for `node`, `npm`, `npx`, `pnpm`, `yarn`, and the nvm script only when using it, and will create a function for `node`, `npm`, `npx`, `pnpm`, `yarn`, `corepack`
command(s) specified by `lazy-cmd` option, so when you call either of them, nvm will be loaded and run with and the command(s) specified by `lazy-cmd` option, so when you call either of them, nvm will be loaded and run
default version. To enable it, you can add this snippet to your zshrc, before Oh My Zsh is sourced: with default version. To enable it, you can add this snippet to your zshrc, before Oh My Zsh is sourced:
```zsh ```zsh
zstyle ':omz:plugins:nvm' lazy yes zstyle ':omz:plugins:nvm' lazy yes

View file

@ -50,11 +50,11 @@ function _omz_setup_autoload {
zstyle -t ':omz:plugins:nvm' silent-autoload && nvm_silent="--silent" zstyle -t ':omz:plugins:nvm' silent-autoload && nvm_silent="--silent"
if [[ -n "$nvmrc_path" ]]; then if [[ -n "$nvmrc_path" ]]; then
local nvmrc_node_version=$(nvm version $(cat "$nvmrc_path" | tr -dc '[:print:]')) local nvmrc_node_version=$(nvm version $(command cat "$nvmrc_path" | tr -dc '[:print:]'))
if [[ "$nvmrc_node_version" = "N/A" ]]; then if [[ "$nvmrc_node_version" = "N/A" ]]; then
nvm install nvm install
elif [[ "$nvmrc_node_version" != "$node_version" ]]; then elif [[ "$nvmrc_node_version" != "$(nvm version)" ]]; then
nvm use $nvm_silent nvm use $nvm_silent
fi fi
elif [[ -n "$(PWD=$OLDPWD nvm_find_nvmrc)" ]] && [[ "$(nvm version)" != "$(nvm version default)" ]]; then elif [[ -n "$(PWD=$OLDPWD nvm_find_nvmrc)" ]] && [[ "$(nvm version)" != "$(nvm version default)" ]]; then
@ -72,9 +72,9 @@ function _omz_setup_autoload {
} }
if zstyle -t ':omz:plugins:nvm' lazy; then if zstyle -t ':omz:plugins:nvm' lazy; then
# Call nvm when first using nvm, node, npm, pnpm, yarn or other commands in lazy-cmd # Call nvm when first using nvm, node, npm, pnpm, yarn, corepack or other commands in lazy-cmd
zstyle -a ':omz:plugins:nvm' lazy-cmd nvm_lazy_cmd zstyle -a ':omz:plugins:nvm' lazy-cmd nvm_lazy_cmd
nvm_lazy_cmd=(nvm node npm npx pnpm yarn $nvm_lazy_cmd) # default values nvm_lazy_cmd=(nvm node npm npx pnpm yarn corepack $nvm_lazy_cmd) # default values
eval " eval "
function $nvm_lazy_cmd { function $nvm_lazy_cmd {
for func in $nvm_lazy_cmd; do for func in $nvm_lazy_cmd; do

View file

@ -1,27 +1,27 @@
# Automatic poetry environment activation/deactivation
_togglePoetryShell() { _togglePoetryShell() {
# deactivate environment if pyproject.toml doesn't exist and not in a subdir # Determine if currently in a Poetry-managed directory
if [[ ! -f "$PWD/pyproject.toml" ]] ; then local in_poetry_dir=0
if [[ "$poetry_active" == 1 ]]; then if [[ -f "$PWD/pyproject.toml" ]] && grep -q 'tool.poetry' "$PWD/pyproject.toml"; then
if [[ "$PWD" != "$poetry_dir"* ]]; then in_poetry_dir=1
export poetry_active=0
deactivate
return
fi
fi
fi fi
# activate the environment if pyproject.toml exists # Deactivate the current environment if moving out of a Poetry directory or into a different Poetry directory
if [[ "$poetry_active" != 1 ]]; then if [[ $poetry_active -eq 1 ]] && { [[ $in_poetry_dir -eq 0 ]] && [[ "$PWD" != "$poetry_dir"* ]]; }; then
if [[ -f "$PWD/pyproject.toml" ]]; then export poetry_active=0
if grep -q 'tool.poetry' "$PWD/pyproject.toml"; then unset poetry_dir
deactivate
fi
# Activate the environment if in a Poetry directory and no environment is currently active
if [[ $in_poetry_dir -eq 1 ]] && [[ $poetry_active -ne 1 ]]; then
venv_dir=$(poetry env info --path 2>/dev/null)
if [[ -n "$venv_dir" ]]; then
export poetry_active=1 export poetry_active=1
export poetry_dir="$PWD" export poetry_dir="$PWD"
source "$(poetry env info --path)/bin/activate" source "${venv_dir}/bin/activate"
fi
fi fi
fi fi
} }
autoload -U add-zsh-hook autoload -U add-zsh-hook
add-zsh-hook chpwd _togglePoetryShell add-zsh-hook chpwd _togglePoetryShell
_togglePoetryShell _togglePoetryShell # Initial call to check the current directory at shell startup

9
plugins/procs/README.md Normal file
View file

@ -0,0 +1,9 @@
# procs
This plugin provides completion for [procs](https://github.com/dalance/procs).
To use it, add `procs` to the plugins array in your zshrc file.
```
plugins=(... procs)
```

View file

@ -0,0 +1,13 @@
if (( ! $+commands[procs] )); then
return
fi
# If the completion file doesn't exist yet, we need to autoload it and
# bind it to `minikube`. Otherwise, compinit will have already done that.
if [[ ! -f "$ZSH_CACHE_DIR/completions/_procs" ]]; then
typeset -g -A _comps
autoload -Uz _procs
_comps[procs]=_procs
fi
procs --gen-completion-out zsh >| "$ZSH_CACHE_DIR/completions/_procs" &|

View file

@ -32,8 +32,9 @@ virtual environments:
`venv`) in the current directory. `venv`) in the current directory.
- `auto_vrun`: Automatically activate the venv virtual environment when entering a directory containing - `auto_vrun`: Automatically activate the venv virtual environment when entering a directory containing
`<venv-name>/bin/activate`, and automatically deactivate it when navigating out of it (including `<venv-name>/bin/activate`, and automatically deactivate it when navigating out of it (keeps venv activated
subdirectories!). in subdirectories).
- To enable the feature, set `export PYTHON_AUTO_VRUN=true` before sourcing oh-my-zsh. - To enable the feature, set `export PYTHON_AUTO_VRUN=true` before sourcing oh-my-zsh.
- The default virtual environment name is `venv`. To use a different name, set - Plugin activates first virtual environment in lexicographic order whose name begins with `<venv-name>`.
The default virtual environment name is `venv`. To use a different name, set
`export PYTHON_VENV_NAME=<venv-name>`. For example: `export PYTHON_VENV_NAME=".venv"` `export PYTHON_VENV_NAME=<venv-name>`. For example: `export PYTHON_VENV_NAME=".venv"`

View file

@ -86,11 +86,20 @@ function mkv() {
if [[ "$PYTHON_AUTO_VRUN" == "true" ]]; then if [[ "$PYTHON_AUTO_VRUN" == "true" ]]; then
# Automatically activate venv when changing dir # Automatically activate venv when changing dir
auto_vrun() { function auto_vrun() {
if [[ -f "${PYTHON_VENV_NAME}/bin/activate" ]]; then # deactivate if we're on a different dir than VIRTUAL_ENV states
source "${PYTHON_VENV_NAME}/bin/activate" > /dev/null 2>&1 # we don't deactivate subdirectories!
else if (( $+functions[deactivate] )) && [[ $PWD != ${VIRTUAL_ENV:h}* ]]; then
deactivate > /dev/null 2>&1
fi
if [[ $PWD != ${VIRTUAL_ENV:h} ]]; then
for _file in "${PYTHON_VENV_NAME}"*/bin/activate(N.); do
# make sure we're not in a venv already
(( $+functions[deactivate] )) && deactivate > /dev/null 2>&1 (( $+functions[deactivate] )) && deactivate > /dev/null 2>&1
source $_file > /dev/null 2>&1
break
done
fi fi
} }
add-zsh-hook chpwd auto_vrun add-zsh-hook chpwd auto_vrun

View file

@ -22,7 +22,8 @@ if parsed.scheme not in proxy_protocols:
def make_argv(): def make_argv():
yield "nc" yield "nc"
if sys.platform == 'linux': if sys.platform in {'linux', 'cygwin'}:
# caveats: the built-in netcat of most linux distributions and cygwin support proxy type
# caveats: macOS built-in netcat command not supported proxy-type # caveats: macOS built-in netcat command not supported proxy-type
yield "-X" # --proxy-type yield "-X" # --proxy-type
# Supported protocols are 4 (SOCKS v4), 5 (SOCKS v5) and connect (HTTP proxy). # Supported protocols are 4 (SOCKS v4), 5 (SOCKS v5) and connect (HTTP proxy).

View file

@ -62,7 +62,7 @@ function _add_identities() {
# if id is an absolute path, make file equal to id # if id is an absolute path, make file equal to id
[[ "$id" = /* ]] && file="$id" || file="$HOME/.ssh/$id" [[ "$id" = /* ]] && file="$id" || file="$HOME/.ssh/$id"
# check for filename match, otherwise try for signature match # check for filename match, otherwise try for signature match
if [[ ${loaded_ids[(I)$file]} -le 0 ]]; then if [[ -f $file && ${loaded_ids[(I)$file]} -le 0 ]]; then
sig="$(ssh-keygen -lf "$file" | awk '{print $2}')" sig="$(ssh-keygen -lf "$file" | awk '{print $2}')"
[[ ${loaded_sigs[(I)$sig]} -le 0 ]] && not_loaded+=("$file") [[ ${loaded_sigs[(I)$sig]} -le 0 ]] && not_loaded+=("$file")
fi fi
@ -98,8 +98,10 @@ function _add_identities() {
# Add a nifty symlink for screen/tmux if agent forwarding is enabled # Add a nifty symlink for screen/tmux if agent forwarding is enabled
if zstyle -t :omz:plugins:ssh-agent agent-forwarding \ if zstyle -t :omz:plugins:ssh-agent agent-forwarding \
&& [[ -n "$SSH_AUTH_SOCK" && ! -L "$SSH_AUTH_SOCK" ]]; then && [[ -n "$SSH_AUTH_SOCK" ]]; then
if [[ ! -L "$SSH_AUTH_SOCK" ]]; then
ln -sf "$SSH_AUTH_SOCK" /tmp/ssh-agent-$USERNAME-screen ln -sf "$SSH_AUTH_SOCK" /tmp/ssh-agent-$USERNAME-screen
fi
else else
_start_agent _start_agent
fi fi

View file

@ -1,7 +1,7 @@
# ignore oh-my-zsh theme
unset ZSH_THEME
if (( $+commands[starship] )); then if (( $+commands[starship] )); then
# ignore oh-my-zsh theme
unset ZSH_THEME
eval "$(starship init zsh)" eval "$(starship init zsh)"
else else
echo '[oh-my-zsh] starship not found, please install it from https://starship.rs' echo '[oh-my-zsh] starship not found, please install it from https://starship.rs'

View file

@ -16,7 +16,7 @@ plugins=(... terraform)
## Aliases ## Aliases
| Alias | Command | | Alias | Command |
| ----- | -------------------- | | ------ | -------------------- |
| `tf` | `terraform` | | `tf` | `terraform` |
| `tfa` | `terraform apply` | | `tfa` | `terraform apply` |
| `tfc` | `terraform console` | | `tfc` | `terraform console` |
@ -27,7 +27,8 @@ plugins=(... terraform)
| `tfp` | `terraform plan` | | `tfp` | `terraform plan` |
| `tfv` | `terraform validate` | | `tfv` | `terraform validate` |
| `tfs` | `terraform state` | | `tfs` | `terraform state` |
| `tfsh`| `terraform show` | | `tft` | `terraform test` |
| `tfsh` | `terraform show` |
## Prompt function ## Prompt function

View file

@ -25,4 +25,5 @@ alias tfo='terraform output'
alias tfp='terraform plan' alias tfp='terraform plan'
alias tfv='terraform validate' alias tfv='terraform validate'
alias tfs='terraform state' alias tfs='terraform state'
alias tft='terraform test'
alias tfsh='terraform show' alias tfsh='terraform show'

15
plugins/tldr/README.md Normal file
View file

@ -0,0 +1,15 @@
# tldr plugin
This plugin adds a shortcut to insert tldr before the previous command.
Heavily inspired from [Man plugin](https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/man).
To use it, add `tldr` to the plugins array in your zshrc file:
```zsh
plugins=(... tldr)
```
# Keyboard Shortcuts
| Shortcut | Description |
|------------------------------------|----------------------------------------------------------------------------|
| <kbd>Esc</kbd> + tldr | add tldr before the previous command to see the tldr page for this command |

View file

@ -0,0 +1,19 @@
tldr-command-line() {
# if there is no command typed, use the last command
[[ -z "$BUFFER" ]] && zle up-history
# if typed command begins with tldr, do nothing
[[ "$BUFFER" = tldr\ * ]] && return
# get command and possible subcommand
# http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion-Flags
local -a args
args=(${${(Az)BUFFER}[1]} ${${(Az)BUFFER}[2]})
BUFFER="tldr ${args[1]}"
}
zle -N tldr-command-line
# Defined shortcut keys: [Esc]tldr
bindkey "\e"tldr tldr-command-line

View file

@ -37,6 +37,7 @@ The plugin also supports the following:
| `ZSH_TMUX_AUTOQUIT` | Automatically closes terminal once tmux exits (default: `ZSH_TMUX_AUTOSTART`) | | `ZSH_TMUX_AUTOQUIT` | Automatically closes terminal once tmux exits (default: `ZSH_TMUX_AUTOSTART`) |
| `ZSH_TMUX_CONFIG` | Set the configuration path (default: `$HOME/.tmux.conf`, `$XDG_CONFIG_HOME/tmux/tmux.conf`) | | `ZSH_TMUX_CONFIG` | Set the configuration path (default: `$HOME/.tmux.conf`, `$XDG_CONFIG_HOME/tmux/tmux.conf`) |
| `ZSH_TMUX_DEFAULT_SESSION_NAME` | Set tmux default session name when autostart is enabled | | `ZSH_TMUX_DEFAULT_SESSION_NAME` | Set tmux default session name when autostart is enabled |
| `ZSH_TMUX_AUTONAME_SESSION` | Automatically name new sessions based on the basename of `$PWD` (default: `false`) |
| `ZSH_TMUX_DETACHED` | Set the detached mode (default: `false`) | | `ZSH_TMUX_DETACHED` | Set the detached mode (default: `false`) |
| `ZSH_TMUX_FIXTERM` | Sets `$TERM` to 256-color term or not based on current terminal support | | `ZSH_TMUX_FIXTERM` | Sets `$TERM` to 256-color term or not based on current terminal support |
| `ZSH_TMUX_FIXTERM_WITHOUT_256COLOR` | `$TERM` to use for non 256-color terminals (default: `tmux` if available, `screen` otherwise) | | `ZSH_TMUX_FIXTERM_WITHOUT_256COLOR` | `$TERM` to use for non 256-color terminals (default: `tmux` if available, `screen` otherwise) |

View file

@ -13,6 +13,8 @@ fi
: ${ZSH_TMUX_AUTOCONNECT:=true} : ${ZSH_TMUX_AUTOCONNECT:=true}
# Automatically close the terminal when tmux exits # Automatically close the terminal when tmux exits
: ${ZSH_TMUX_AUTOQUIT:=$ZSH_TMUX_AUTOSTART} : ${ZSH_TMUX_AUTOQUIT:=$ZSH_TMUX_AUTOSTART}
# Automatically name the new session based on the basename of PWD
: ${ZSH_TMUX_AUTONAME_SESSION:=false}
# Set term to screen or screen-256color based on current terminal support # Set term to screen or screen-256color based on current terminal support
: ${ZSH_TMUX_DETACHED:=false} : ${ZSH_TMUX_DETACHED:=false}
# Set detached mode # Set detached mode
@ -102,9 +104,22 @@ function _zsh_tmux_plugin_run() {
local _detached="" local _detached=""
[[ "$ZSH_TMUX_DETACHED" == "true" ]] && _detached="-d" [[ "$ZSH_TMUX_DETACHED" == "true" ]] && _detached="-d"
local session_name
if [[ "$ZSH_TMUX_AUTONAME_SESSION" == "true" ]]; then
# Name the session after the basename of the current directory
session_name=${PWD##*/}
# If the current directory is the home directory, name it 'HOME'
[[ "$PWD" == "$HOME" ]] && session_name="HOME"
# If the current directory is the root directory, name it 'ROOT'
[[ "$PWD" == "/" ]] && session_name="ROOT"
else
session_name="$ZSH_TMUX_DEFAULT_SESSION_NAME"
fi
# Try to connect to an existing session. # Try to connect to an existing session.
if [[ -n "$ZSH_TMUX_DEFAULT_SESSION_NAME" ]]; then if [[ -n "$session_name" ]]; then
[[ "$ZSH_TMUX_AUTOCONNECT" == "true" ]] && $tmux_cmd attach $_detached -t $ZSH_TMUX_DEFAULT_SESSION_NAME [[ "$ZSH_TMUX_AUTOCONNECT" == "true" ]] && $tmux_cmd attach $_detached -t "$session_name"
else else
[[ "$ZSH_TMUX_AUTOCONNECT" == "true" ]] && $tmux_cmd attach $_detached [[ "$ZSH_TMUX_AUTOCONNECT" == "true" ]] && $tmux_cmd attach $_detached
fi fi
@ -116,8 +131,9 @@ function _zsh_tmux_plugin_run() {
elif [[ -e "$ZSH_TMUX_CONFIG" ]]; then elif [[ -e "$ZSH_TMUX_CONFIG" ]]; then
tmux_cmd+=(-f "$ZSH_TMUX_CONFIG") tmux_cmd+=(-f "$ZSH_TMUX_CONFIG")
fi fi
if [[ -n "$ZSH_TMUX_DEFAULT_SESSION_NAME" ]]; then
$tmux_cmd new-session -s $ZSH_TMUX_DEFAULT_SESSION_NAME if [[ -n "$session_name" ]]; then
$tmux_cmd new-session -s "$session_name"
else else
$tmux_cmd new-session $tmux_cmd new-session
fi fi

View file

@ -57,6 +57,24 @@ wd() {
} }
``` ```
### [Home Manager](https://github.com/nix-community/home-manager)
Add the following to your `home.nix` then run `home-manager switch`:
```nix
programs.zsh.plugins = [
{
name = "wd";
src = pkgs.fetchFromGitHub {
owner = "mfaerevaag";
repo = "wd";
rev = "v0.5.2";
sha256 = "sha256-4yJ1qhqhNULbQmt6Z9G22gURfDLe30uV1ascbzqgdhg=";
};
}
];
```
### [zplug](https://github.com/zplug/zplug) ### [zplug](https://github.com/zplug/zplug)
```zsh ```zsh
@ -119,6 +137,14 @@ Also, you may have to force a rebuild of `zcompdump` by running:
rm -f ~/.zcompdump; compinit rm -f ~/.zcompdump; compinit
``` ```
## Browse
If you want to make use of the `fzf`-powered browse feature to fuzzy search through all your warp points, set up a keybind in your `.zshrc`:
```zsh
bindkey ${FZF_WD_BINDKEY:-'^B'} fuzzy_wd_widget
```
## Usage ## Usage
* Add warp point to current working directory: * Add warp point to current working directory:
@ -132,6 +158,19 @@ If a warp point with the same name exists, use `wd add foo --force` to overwrite
**Note:** a warp point cannot contain colons, or consist of only spaces and dots. **Note:** a warp point cannot contain colons, or consist of only spaces and dots.
The first will conflict in how `wd` stores the warp points, and the second will conflict with other features, as below. The first will conflict in how `wd` stores the warp points, and the second will conflict with other features, as below.
* Add warp point to any directory with default name:
```zsh
wd addcd /foo/ bar
```
* Add warp point to any directory with a custom name:
```zsh
wd addcd /foo/
```
You can omit point name to automatically use the current directory's name instead. You can omit point name to automatically use the current directory's name instead.
* From any directory, warp to `foo` with: * From any directory, warp to `foo` with:

View file

@ -31,6 +31,7 @@ function _wd() {
commands=( commands=(
'add:Adds the current working directory to your warp points' 'add:Adds the current working directory to your warp points'
'addcd:Adds a directory to your warp points'
'add!:Overwrites existing warp point' 'add!:Overwrites existing warp point'
'export:Export warp points as static named directories' 'export:Export warp points as static named directories'
'rm:Removes the given warp point' 'rm:Removes the given warp point'
@ -63,6 +64,9 @@ function _wd() {
add) add)
_message 'Write the name of your warp point' && ret=0 _message 'Write the name of your warp point' && ret=0
;; ;;
addcd)
_message 'Write the name of your path' && ret=0
;;
show) show)
_describe -t points "Warp points" warp_points && ret=0 _describe -t points "Warp points" warp_points && ret=0
;; ;;

View file

@ -8,8 +8,14 @@
# @github.com/mfaerevaag/wd # @github.com/mfaerevaag/wd
# Handle $0 according to the standard: # Handle $0 according to the standard:
# https://zdharma-continuum.github.io/Zsh-100-Commits-Club/Zsh-Plugin-Standard.html # # https://zdharma-continuum.github.io/Zsh-100-Commits-Club/Zsh-Plugin-Standard.html
0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}" 0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}"
0="${${(M)0:#/*}:-$PWD/$0}" 0="${${(M)0:#/*}:-$PWD/$0}"
eval "wd() { source '${0:A:h}/wd.sh' }" eval "wd() { source '${0:A:h}/wd.sh' }"
wd > /dev/null
zle -N wd_browse_widget
zle -N wd_restore_buffer
autoload -Uz add-zle-hook-widget
add-zle-hook-widget line-init wd_restore_buffer
bindkey ${FZF_WD_BINDKEY:-'^B'} wd_browse_widget

94
plugins/wd/wd.sh Normal file → Executable file
View file

@ -8,7 +8,7 @@
# @github.com/mfaerevaag/wd # @github.com/mfaerevaag/wd
# version # version
readonly WD_VERSION=0.5.0 readonly WD_VERSION=0.7.0
# colors # colors
readonly WD_BLUE="\033[96m" readonly WD_BLUE="\033[96m"
@ -57,12 +57,11 @@ wd_print_msg()
{ {
if [[ -z $wd_quiet_mode ]] if [[ -z $wd_quiet_mode ]]
then then
local color=$1 local color="${1:-$WD_BLUE}" # Default to blue if no color is provided
local msg=$2 local msg="$2"
if [[ $color == "" || $msg == "" ]] if [[ -z "$msg" ]]; then
then print "${WD_RED}*${WD_NOC} Could not print message. Sorry!"
print " ${WD_RED}*${WD_NOC} Could not print message. Sorry!"
else else
print " ${color}*${WD_NOC} ${msg}" print " ${color}*${WD_NOC} ${msg}"
fi fi
@ -79,6 +78,8 @@ Commands:
<point> <path> Warps to the directory specified by the warp point with path appended <point> <path> Warps to the directory specified by the warp point with path appended
add <point> Adds the current working directory to your warp points add <point> Adds the current working directory to your warp points
add Adds the current working directory to your warp points with current directory's name add Adds the current working directory to your warp points with current directory's name
addcd <path> Adds a path to your warp points with the directory's name
addcd <path> <point> Adds a path to your warp points with a custom name
rm <point> Removes the given warp point rm <point> Removes the given warp point
rm Removes the given warp point with current directory's name rm Removes the given warp point with current directory's name
show <point> Print path to given warp point show <point> Print path to given warp point
@ -204,6 +205,28 @@ wd_add()
fi fi
} }
wd_addcd() {
local folder="$1"
local point=$2
local force=$3
local currentdir=$PWD
if [[ -z "$folder" ]]; then
wd_exit_fail "You must specify a path"
return
fi
if [[ ! -d "$folder" ]]; then
wd_exit_fail "The directory does not exist"
return
fi
cd "$folder" || return
wd_add "$point" "$force"
cd "$currentdir" || return
}
wd_remove() wd_remove()
{ {
local point_list=$1 local point_list=$1
@ -230,6 +253,46 @@ wd_remove()
done done
} }
wd_browse() {
if ! command -v fzf >/dev/null; then
echo "This functionality requires fzf. Please install fzf first."
return 1
fi
local entries=("${(@f)$(sed "s:${HOME}:~:g" "$WD_CONFIG" | awk -F ':' '{print $1 " -> " $2}')}")
local script_path="${${(%):-%x}:h}"
local wd_remove_output=$(mktemp "${TMPDIR:-/tmp}/wd.XXXXXXXXXX")
local entries_with_headers=("All warp points:" "Press enter to select. Press delete to remove" "${entries[@]}")
local fzf_bind="delete:execute(echo {} | awk -F ' -> ' '{print \$1}' | xargs -I {} "$script_path/wd.sh" rm {} > "$wd_remove_output")+abort"
local fzf_command=$(printf '%s\n' "${entries_with_headers[@]}" | fzf --height 100% --reverse --header-lines=2 --bind="$fzf_bind")
if [[ -e $wd_remove_output ]]; then
cat "$wd_remove_output"
rm "$wd_remove_output"
fi
if [[ -n $selected_entry ]]; then
local selected_point="${selected_entry%% ->*}"
selected_point=$(echo "$selected_point" | xargs)
wd $selected_point
fi
}
wd_browse_widget() {
if [[ -e $WD_CONFIG ]]; then
wd_browse
saved_buffer=$BUFFER
saved_cursor=$CURSOR
BUFFER=
zle redisplay
zle accept-line
fi
}
wd_restore_buffer() {
BUFFER=$saved_buffer
CURSOR=$saved_cursor
saved_buffer=
saved_cursor=1
}
wd_list_all() wd_list_all()
{ {
wd_print_msg "$WD_BLUE" "All warp points:" wd_print_msg "$WD_BLUE" "All warp points:"
@ -358,7 +421,7 @@ wd_export_static_named_directories() {
fi fi
} }
local WD_CONFIG=${WD_CONFIG:-$HOME/.warprc} WD_CONFIG=${WD_CONFIG:-$HOME/.warprc}
local WD_QUIET=0 local WD_QUIET=0
local WD_EXIT_CODE=0 local WD_EXIT_CODE=0
local WD_DEBUG=0 local WD_DEBUG=0
@ -396,7 +459,9 @@ fi
# disable extendedglob for the complete wd execution time # disable extendedglob for the complete wd execution time
setopt | grep -q extendedglob setopt | grep -q extendedglob
wd_extglob_is_set=$? wd_extglob_is_set=$?
(( ! $wd_extglob_is_set )) && setopt noextendedglob if (( wd_extglob_is_set == 0 )); then
setopt noextendedglob
fi
# load warp points # load warp points
typeset -A points typeset -A points
@ -436,6 +501,14 @@ else
wd_add "$2" "$wd_force_mode" wd_add "$2" "$wd_force_mode"
break break
;; ;;
"-b"|"browse")
wd_browse
break
;;
"-c"|"--addcd"|"addcd")
wd_addcd "$2" "$3" "$wd_force_mode"
break
;;
"-e"|"export") "-e"|"export")
wd_export_static_named_directories wd_export_static_named_directories
break break
@ -484,11 +557,14 @@ fi
# if not, next time warp will pick up variables from this run # if not, next time warp will pick up variables from this run
# remember, there's no sub shell # remember, there's no sub shell
(( ! $wd_extglob_is_set )) && setopt extendedglob if (( wd_extglob_is_set == 0 )); then
setopt extendedglob
fi
unset wd_extglob_is_set unset wd_extglob_is_set
unset wd_warp unset wd_warp
unset wd_add unset wd_add
unset wd_addcd
unset wd_remove unset wd_remove
unset wd_show unset wd_show
unset wd_list_all unset wd_list_all

View file

@ -86,7 +86,7 @@ _global_commands=(
) )
_yarn_find_package_json() { _yarn_find_package_json() {
local dir=$(cd "$1" && pwd) local dir=$(builtin cd "$1" && pwd)
while true while true
do do
@ -109,7 +109,7 @@ _yarn_commands_scripts() {
if [[ -n $opt_args[--cwd] ]]; then if [[ -n $opt_args[--cwd] ]]; then
packageJson=$(_yarn_find_package_json $opt_args[--cwd]) packageJson=$(_yarn_find_package_json $opt_args[--cwd])
binaries=($(cd $opt_args[--cwd] && echo node_modules/.bin/*(x:t))) binaries=($(builtin cd $opt_args[--cwd] && echo node_modules/.bin/*(x:t)))
else else
packageJson=$(_yarn_find_package_json $pwd) packageJson=$(_yarn_find_package_json $pwd)
binaries=($(echo node_modules/.bin/*(x:t))) binaries=($(echo node_modules/.bin/*(x:t)))
@ -130,9 +130,9 @@ _yarn_scripts() {
if [[ -n $_yarn_run_cwd ]]; then if [[ -n $_yarn_run_cwd ]]; then
packageJson=$(_yarn_find_package_json $_yarn_run_cwd) packageJson=$(_yarn_find_package_json $_yarn_run_cwd)
if [[ -d "${_yarn_run_cwd}/node_modules" ]]; then if [[ -d "${_yarn_run_cwd}/node_modules" ]]; then
binaries=($(cd $_yarn_run_cwd && echo node_modules/.bin/*(x:t))) binaries=($(builtin cd $_yarn_run_cwd && echo node_modules/.bin/*(x:t)))
else else
binaries=($(cd $_yarn_run_cwd && yarn bin | perl -wln -e 'm{^[^:]+: (\S+)$} and print $1')) binaries=($(builtin cd $_yarn_run_cwd && yarn bin | perl -wln -e 'm{^[^:]+: (\S+)$} and print $1'))
fi fi
else else
packageJson=$(_yarn_find_package_json $pwd) packageJson=$(_yarn_find_package_json $pwd)

View file

@ -1,5 +1,5 @@
# If you come from bash you might have to change your $PATH. # If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH # export PATH=$HOME/bin:$HOME/.local/bin:/usr/local/bin:$PATH
# Path to your oh-my-zsh installation. # Path to your oh-my-zsh installation.
export ZSH=$HOME/.oh-my-zsh export ZSH=$HOME/.oh-my-zsh

View file

@ -96,7 +96,7 @@ prompt_context() {
# Git: branch/detached head, dirty status # Git: branch/detached head, dirty status
prompt_git() { prompt_git() {
(( $+commands[git] )) || return (( $+commands[git] )) || return
if [[ "$(git config --get oh-my-zsh.hide-status 2>/dev/null)" = 1 ]]; then if [[ "$(command git config --get oh-my-zsh.hide-status 2>/dev/null)" = 1 ]]; then
return return
fi fi
local PL_BRANCH_CHAR local PL_BRANCH_CHAR
@ -106,12 +106,12 @@ prompt_git() {
} }
local ref dirty mode repo_path local ref dirty mode repo_path
if [[ "$(git rev-parse --is-inside-work-tree 2>/dev/null)" = "true" ]]; then if [[ "$(command git rev-parse --is-inside-work-tree 2>/dev/null)" = "true" ]]; then
repo_path=$(git rev-parse --git-dir 2>/dev/null) repo_path=$(command git rev-parse --git-dir 2>/dev/null)
dirty=$(parse_git_dirty) dirty=$(parse_git_dirty)
ref=$(git symbolic-ref HEAD 2> /dev/null) || \ ref=$(command git symbolic-ref HEAD 2> /dev/null) || \
ref="◈ $(git describe --exact-match --tags HEAD 2> /dev/null)" || \ ref="◈ $(command git describe --exact-match --tags HEAD 2> /dev/null)" || \
ref="➦ $(git rev-parse --short HEAD 2> /dev/null)" ref="➦ $(command git rev-parse --short HEAD 2> /dev/null)"
if [[ -n $dirty ]]; then if [[ -n $dirty ]]; then
prompt_segment yellow black prompt_segment yellow black
else else
@ -119,8 +119,8 @@ prompt_git() {
fi fi
local ahead behind local ahead behind
ahead=$(git log --oneline @{upstream}.. 2>/dev/null) ahead=$(command git log --oneline @{upstream}.. 2>/dev/null)
behind=$(git log --oneline ..@{upstream} 2>/dev/null) behind=$(command git log --oneline ..@{upstream} 2>/dev/null)
if [[ -n "$ahead" ]] && [[ -n "$behind" ]]; then if [[ -n "$ahead" ]] && [[ -n "$behind" ]]; then
PL_BRANCH_CHAR=$'\u21c5' PL_BRANCH_CHAR=$'\u21c5'
elif [[ -n "$ahead" ]]; then elif [[ -n "$ahead" ]]; then
@ -163,10 +163,10 @@ prompt_bzr() {
done done
local bzr_status status_mod status_all revision local bzr_status status_mod status_all revision
if bzr_status=$(bzr status 2>&1); then if bzr_status=$(command bzr status 2>&1); then
status_mod=$(echo -n "$bzr_status" | head -n1 | grep "modified" | wc -m) status_mod=$(echo -n "$bzr_status" | head -n1 | grep "modified" | wc -m)
status_all=$(echo -n "$bzr_status" | head -n1 | wc -m) status_all=$(echo -n "$bzr_status" | head -n1 | wc -m)
revision=${$(bzr log -r-1 --log-format line | cut -d: -f1):gs/%/%%} revision=${$(command bzr log -r-1 --log-format line | cut -d: -f1):gs/%/%%}
if [[ $status_mod -gt 0 ]] ; then if [[ $status_mod -gt 0 ]] ; then
prompt_segment yellow black "bzr@$revision ✚" prompt_segment yellow black "bzr@$revision ✚"
else else
@ -182,13 +182,13 @@ prompt_bzr() {
prompt_hg() { prompt_hg() {
(( $+commands[hg] )) || return (( $+commands[hg] )) || return
local rev st branch local rev st branch
if $(hg id >/dev/null 2>&1); then if $(command hg id >/dev/null 2>&1); then
if $(hg prompt >/dev/null 2>&1); then if $(command hg prompt >/dev/null 2>&1); then
if [[ $(hg prompt "{status|unknown}") = "?" ]]; then if [[ $(command hg prompt "{status|unknown}") = "?" ]]; then
# if files are not added # if files are not added
prompt_segment red white prompt_segment red white
st='±' st='±'
elif [[ -n $(hg prompt "{status|modified}") ]]; then elif [[ -n $(command hg prompt "{status|modified}") ]]; then
# if any modification # if any modification
prompt_segment yellow black prompt_segment yellow black
st='±' st='±'
@ -196,15 +196,15 @@ prompt_hg() {
# if working copy is clean # if working copy is clean
prompt_segment green $CURRENT_FG prompt_segment green $CURRENT_FG
fi fi
echo -n ${$(hg prompt "☿ {rev}@{branch}"):gs/%/%%} $st echo -n ${$(command hg prompt "☿ {rev}@{branch}"):gs/%/%%} $st
else else
st="" st=""
rev=$(hg id -n 2>/dev/null | sed 's/[^-0-9]//g') rev=$(command hg id -n 2>/dev/null | sed 's/[^-0-9]//g')
branch=$(hg id -b 2>/dev/null) branch=$(command hg id -b 2>/dev/null)
if `hg st | grep -q "^\?"`; then if command hg st | command grep -q "^\?"; then
prompt_segment red black prompt_segment red black
st='±' st='±'
elif `hg st | grep -q "^[MA]"`; then elif command hg st | command grep -q "^[MA]"; then
prompt_segment yellow black prompt_segment yellow black
st='±' st='±'
else else

View file

@ -17,7 +17,7 @@ $ '
RPROMPT='$(ruby_prompt_info)' RPROMPT='$(ruby_prompt_info)'
VIRTUAL_ENV_DISABLE_PROMPT=0 VIRTUAL_ENV_DISABLE_PROMPT=0
ZSH_THEME_VIRTUAL_ENV_PROMPT_PREFIX=" %{$fg[green]%}🐍" ZSH_THEME_VIRTUAL_ENV_PROMPT_PREFIX=" %{$fg[green]%}🐍 "
ZSH_THEME_VIRTUAL_ENV_PROMPT_SUFFIX="%{$reset_color%}" ZSH_THEME_VIRTUAL_ENV_PROMPT_SUFFIX="%{$reset_color%}"
ZSH_THEME_VIRTUALENV_PREFIX=$ZSH_THEME_VIRTUAL_ENV_PROMPT_PREFIX ZSH_THEME_VIRTUALENV_PREFIX=$ZSH_THEME_VIRTUAL_ENV_PROMPT_PREFIX
ZSH_THEME_VIRTUALENV_SUFFIX=$ZSH_THEME_VIRTUAL_ENV_PROMPT_SUFFIX ZSH_THEME_VIRTUALENV_SUFFIX=$ZSH_THEME_VIRTUAL_ENV_PROMPT_SUFFIX

View file

@ -16,7 +16,8 @@ _fishy_collapsed_wd() {
} }
local user_color='green'; [ $UID -eq 0 ] && user_color='red' local user_color='green'; [ $UID -eq 0 ] && user_color='red'
PROMPT='%n@%m %{$fg[$user_color]%}$(_fishy_collapsed_wd)%{$reset_color%}%(!.#.>) ' local host_color='white'; [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ] && host_color='yellow'
PROMPT='%{$fg[$user_color]%}%n%{$reset_color%}@%{$fg[$host_color]%}%m %{$fg[$user_color]%}$(_fishy_collapsed_wd)%{$reset_color%}%(!.#.>) '
PROMPT2='%{$fg[red]%}\ %{$reset_color%}' PROMPT2='%{$fg[red]%}\ %{$reset_color%}'
local return_status="%{$fg_bold[red]%}%(?..%?)%{$reset_color%}" local return_status="%{$fg_bold[red]%}%(?..%?)%{$reset_color%}"

View file

@ -20,14 +20,16 @@ zstyle -s ':omz:update' mode update_mode || {
} }
# Cancel update if: # Cancel update if:
# - the automatic update is disabled. # - the automatic update is disabled
# - the current user doesn't have write permissions nor owns the $ZSH directory. # - the current user doesn't have write permissions nor owns the $ZSH directory
# - is not run from a tty # - is not run from a tty
# - git is unavailable on the system. # - git is unavailable on the system
# - $ZSH is not a git repository
if [[ "$update_mode" = disabled ]] \ if [[ "$update_mode" = disabled ]] \
|| [[ ! -w "$ZSH" || ! -O "$ZSH" ]] \ || [[ ! -w "$ZSH" || ! -O "$ZSH" ]] \
|| [[ ! -t 1 ]] \ || [[ ! -t 1 ]] \
|| ! command git --version 2>&1 >/dev/null; then || ! command git --version 2>&1 >/dev/null \
|| (builtin cd -q "$ZSH"; ! command git rev-parse --is-inside-work-tree &>/dev/null); then
unset update_mode unset update_mode
return return
fi fi

View file

@ -10,9 +10,14 @@ fi
# Protect against unwanted sourcing # Protect against unwanted sourcing
case "$ZSH_EVAL_CONTEXT" in case "$ZSH_EVAL_CONTEXT" in
*:file) echo "error: this file should not be sourced" && return ;; *:file) echo "error: this file should not be sourced" && return 1 ;;
esac esac
# Define "$ZSH" if not defined -- in theory this should be `export`ed by the calling script
if [[ -z "$ZSH" ]]; then
ZSH="${0:a:h:h}"
fi
cd "$ZSH" cd "$ZSH"
verbose_mode="default" verbose_mode="default"