1
0
Fork 0
mirror of https://github.com/ohmyzsh/ohmyzsh.git synced 2024-11-27 08:10:08 +00:00

Merge branch 'master' into docker-patch-1

This commit is contained in:
baltic-tea 2024-11-10 16:56:58 +03:00 committed by GitHub
commit 4579956901
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
372 changed files with 8440 additions and 6115 deletions

View file

@ -0,0 +1,20 @@
{
"image": "mcr.microsoft.com/devcontainers/base:noble",
"features": {
"ghcr.io/devcontainers/features/common-utils": {
"installZsh": true,
"configureZshAsDefaultShell": true,
"username": "vscode",
"userUid": 1000,
"userGid": 1000
}
},
"postCreateCommand": "dir=/workspaces/ohmyzsh; rm -rf $HOME/.oh-my-zsh && ln -s $dir $HOME/.oh-my-zsh && cp $dir/templates/minimal.zshrc $HOME/.zshrc && chgrp -R 1000 $dir && chmod g-w,o-w $dir",
"customizations": {
"codespaces": {
"openFiles": [
"README.md"
]
}
}
}

View file

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

10
.github/CODEOWNERS vendored
View file

@ -1,13 +1,19 @@
# Plugin owners
plugins/archlinux/ @ratijas
plugins/dbt/ @msempere
plugins/eza/ @pepoluan
plugins/genpass/ @atoponce
plugins/git-lfs/ @hellovietduc
plugins/gitfast/ @felipec
plugins/kube-ps1/ @mcornella
plugins/kubectl/ @mcornella
plugins/kubectx/ @mcornella
plugins/opentofu/ @mcornella
plugins/react-native @esthor
plugins/sdk/ @rgoldberg
plugins/shell-proxy/ @septs
plugins/starship/ @axieax
plugins/terraform/ @mcornella
plugins/universalarchive/ @Konfekt
plugins/wp-cli/ @joshmedeski
plugins/zoxide/ @ajeetdsouza
plugins/starship/ @axieax
plugins/dbt/ @msempere

14
.github/dependabot.yml vendored Normal file
View file

@ -0,0 +1,14 @@
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: "weekly"
day: "sunday"
labels: []
- package-ecosystem: "pip"
directory: "/.github/workflows/dependencies"
schedule:
interval: "weekly"
day: "sunday"
labels: []

46
.github/dependencies.yml vendored Normal file
View file

@ -0,0 +1,46 @@
dependencies:
plugins/gitfast:
repo: felipec/git-completion
branch: master
version: tag:v2.1
postcopy: |
set -e
rm -rf git-completion.plugin.zsh Makefile README.adoc t tools
test -e git-completion.zsh && mv -f git-completion.zsh _git
plugins/gradle:
repo: gradle/gradle-completion
branch: master
version: 25da917cf5a88f3e58f05be3868a7b2748c8afe6
precopy: |
set -e
find . ! -name _gradle ! -name LICENSE -delete
plugins/history-substring-search:
repo: zsh-users/zsh-history-substring-search
branch: master
version: 87ce96b1862928d84b1afe7c173316614b30e301
precopy: |
set -e
rm -f zsh-history-substring-search.plugin.zsh
test -e zsh-history-substring-search.zsh && mv zsh-history-substring-search.zsh history-substring-search.zsh
postcopy: |
set -e
test -e dependencies/OMZ-README.md && cat dependencies/OMZ-README.md >> README.md
plugins/wd:
repo: mfaerevaag/wd
branch: master
version: tag:v0.9.1
precopy: |
set -e
rm -r test
rm install.sh tty.gif wd.1
plugins/z:
branch: master
repo: agkozak/zsh-z
version: afaf2965b41fdc6ca66066e09382726aa0b6aa04
precopy: |
set -e
test -e README.md && mv -f README.md MANUAL.md
postcopy: |
set -e
test -e _zshz && mv -f _zshz _z
test -e zsh-z.plugin.zsh && mv -f zsh-z.plugin.zsh z.plugin.zsh

36
.github/workflows/dependencies.yml vendored Normal file
View file

@ -0,0 +1,36 @@
name: Update dependencies
on:
workflow_dispatch: {}
schedule:
- cron: "0 6 * * 0"
jobs:
check:
name: Check for updates
runs-on: ubuntu-latest
if: github.repository == 'ohmyzsh/ohmyzsh'
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Authenticate as @ohmyzsh
id: generate_token
uses: ohmyzsh/github-app-token@v2
with:
app_id: ${{ secrets.OHMYZSH_APP_ID }}
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
env:
GH_TOKEN: ${{ steps.generate_token.outputs.token }}
GIT_APP_NAME: ohmyzsh[bot]
GIT_APP_EMAIL: 54982679+ohmyzsh[bot]@users.noreply.github.com
TMP_DIR: ${{ runner.temp }}
run: |
pip install -r .github/workflows/dependencies/requirements.txt
python3 .github/workflows/dependencies/updater.py

View file

@ -0,0 +1 @@
.venv

View file

@ -0,0 +1,7 @@
certifi==2024.8.30
charset-normalizer==3.4.0
idna==3.10
PyYAML==6.0.2
requests==2.32.3
semver==3.0.2
urllib3==2.2.3

View file

@ -0,0 +1,598 @@
import json
import os
import re
import shutil
import subprocess
import sys
import timeit
from copy import deepcopy
from typing import Literal, NotRequired, Optional, TypedDict
import requests
import yaml
from semver import Version
# Get TMP_DIR variable from environment
TMP_DIR = os.path.join(os.environ.get("TMP_DIR", "/tmp"), "ohmyzsh")
# Relative path to dependencies.yml file
DEPS_YAML_FILE = ".github/dependencies.yml"
# Dry run flag
DRY_RUN = os.environ.get("DRY_RUN", "0") == "1"
# 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:
def __init__(self, name=None):
self.name = " '" + name + "'" if name else ""
def __enter__(self):
self.start = timeit.default_timer()
def __exit__(self, exc_type, exc_value, traceback):
self.took = (timeit.default_timer() - self.start) * 1000.0
print("Code block" + self.name + " took: " + str(self.took) + " ms")
### YAML representation
def str_presenter(dumper, data):
"""
Configures yaml for dumping multiline strings
Ref: https://stackoverflow.com/a/33300001
"""
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)
yaml.add_representer(str, str_presenter)
yaml.representer.SafeRepresenter.add_representer(str, str_presenter)
# Types
class DependencyDict(TypedDict):
repo: str
branch: str
version: str
precopy: NotRequired[str]
postcopy: NotRequired[str]
class DependencyYAML(TypedDict):
dependencies: dict[str, DependencyDict]
class UpdateStatusFalse(TypedDict):
has_updates: Literal[False]
class UpdateStatusTrue(TypedDict):
has_updates: Literal[True]
version: str
compare_url: str
head_ref: str
head_url: str
class CommandRunner:
class Exception(Exception):
def __init__(self, message, returncode, stage, stdout, stderr):
super().__init__(message)
self.returncode = returncode
self.stage = stage
self.stdout = stdout
self.stderr = stderr
@staticmethod
def run_or_fail(command: list[str], stage: str, *args, **kwargs):
if DRY_RUN and command[0] == "gh":
command.insert(0, "echo")
result = subprocess.run(command, *args, capture_output=True, **kwargs)
if result.returncode != 0:
raise CommandRunner.Exception(
f"{stage} command failed with exit code {result.returncode}",
returncode=result.returncode,
stage=stage,
stdout=result.stdout.decode("utf-8"),
stderr=result.stderr.decode("utf-8"),
)
return result
class DependencyStore:
store: DependencyYAML = {"dependencies": {}}
@staticmethod
def set(data: DependencyYAML):
DependencyStore.store = data
@staticmethod
def update_dependency_version(path: str, version: str) -> DependencyYAML:
with CodeTimer(f"store deepcopy: {path}"):
store_copy = deepcopy(DependencyStore.store)
dependency = store_copy["dependencies"].get(path)
if dependency is None:
raise ValueError(f"Dependency {path} {version} not found")
dependency["version"] = version
store_copy["dependencies"][path] = dependency
return store_copy
@staticmethod
def write_store(file: str, data: DependencyYAML):
with open(file, "w") as yaml_file:
yaml.safe_dump(data, yaml_file, sort_keys=False)
class Dependency:
def __init__(self, path: str, values: DependencyDict):
self.path = path
self.values = values
self.name: str = ""
self.desc: str = ""
self.kind: str = ""
match path.split("/"):
case ["plugins", name]:
self.name = name
self.kind = "plugin"
self.desc = f"{name} plugin"
case ["themes", name]:
self.name = name.replace(".zsh-theme", "")
self.kind = "theme"
self.desc = f"{self.name} theme"
case _:
self.name = self.desc = path
def __str__(self):
output: str = ""
for key in DependencyDict.__dict__["__annotations__"].keys():
if key not in self.values:
output += f"{key}: None\n"
continue
value = self.values[key]
if "\n" not in value:
output += f"{key}: {value}\n"
else:
output += f"{key}:\n "
output += value.replace("\n", "\n ", value.count("\n") - 1)
return output
def update_or_notify(self):
# Print dependency settings
print(f"Processing {self.desc}...", file=sys.stderr)
print(self, file=sys.stderr)
# Check for updates
repo = self.values["repo"]
remote_branch = self.values["branch"]
version = self.values["version"]
is_tag = version.startswith("tag:")
try:
with CodeTimer(f"update check: {repo}"):
if is_tag:
status = GitHub.check_newer_tag(repo, version.replace("tag:", ""))
else:
status = GitHub.check_updates(repo, remote_branch, version)
if status["has_updates"] is True:
short_sha = status["head_ref"][:8]
new_version = status["version"] if is_tag else short_sha
try:
branch_name = f"update/{self.path}/{new_version}"
# Create new branch
branch = Git.checkout_or_create_branch(branch_name)
# Update dependencies.yml file
self.__update_yaml(
f"tag:{new_version}" if is_tag else status["version"]
)
# Update dependency files
self.__apply_upstream_changes()
# Add all changes and commit
has_new_commit = Git.add_and_commit(self.name, new_version)
if has_new_commit:
# Push changes to remote
Git.push(branch)
# Create GitHub PR
GitHub.create_pr(
branch,
f"feat({self.name}): update to version {new_version}",
f"""## Description
Update for **{self.desc}**: update to version [{new_version}]({status['head_url']}).
Check out the [list of changes]({status['compare_url']}).
""",
)
# Clean up repository
Git.clean_repo()
except (CommandRunner.Exception, shutil.Error) as e:
# Handle exception on automatic update
match type(e):
case CommandRunner.Exception:
# Print error message
print(
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:
print(f"Error copying files: {e}", file=sys.stderr)
try:
Git.clean_repo()
except CommandRunner.Exception as e:
print(
f"Error reverting repository to clean state: {e}",
file=sys.stderr,
)
sys.exit(1)
# Create a GitHub issue to notify maintainer
title = f"{self.path}: update to {new_version}"
body = f"""## Description
There is a new version of `{self.name}` {self.kind} available.
New version: [{new_version}]({status['head_url']})
Check out the [list of changes]({status['compare_url']}).
"""
print("Creating GitHub issue", file=sys.stderr)
print(f"{title}\n\n{body}", file=sys.stderr)
GitHub.create_issue(title, body)
except Exception as e:
print(e, file=sys.stderr)
def __update_yaml(self, new_version: str) -> None:
dep_yaml = DependencyStore.update_dependency_version(self.path, new_version)
DependencyStore.write_store(DEPS_YAML_FILE, dep_yaml)
def __apply_upstream_changes(self) -> None:
# Patterns to ignore in copying files from upstream repo
GLOBAL_IGNORE = [".git", ".github", ".gitignore"]
path = os.path.abspath(self.path)
precopy = self.values.get("precopy")
postcopy = self.values.get("postcopy")
repo = self.values["repo"]
branch = self.values["branch"]
remote_url = f"https://github.com/{repo}.git"
repo_dir = os.path.join(TMP_DIR, repo)
# Clone repository
Git.clone(remote_url, branch, repo_dir, reclone=True)
# Run precopy on tmp repo
if precopy is not None:
print("Running precopy script:", end="\n ", file=sys.stderr)
print(
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
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),
)
# Run postcopy on our repository
if postcopy is not None:
print("Running postcopy script:", end="\n ", file=sys.stderr)
print(
postcopy.replace("\n", "\n ", postcopy.count("\n") - 1),
file=sys.stderr,
)
CommandRunner.run_or_fail(
["bash", "-c", postcopy], cwd=path, stage="Postcopy"
)
class Git:
default_branch = "master"
@staticmethod
def clone(remote_url: str, branch: str, repo_dir: str, reclone=False):
# If repo needs to be fresh
if reclone and os.path.exists(repo_dir):
shutil.rmtree(repo_dir)
# Clone repo in tmp directory and checkout branch
if not os.path.exists(repo_dir):
print(
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
def checkout_or_create_branch(branch_name: str):
# Get current branch name
result = CommandRunner.run_or_fail(
["git", "rev-parse", "--abbrev-ref", "HEAD"], stage="GetDefaultBranch"
)
Git.default_branch = result.stdout.decode("utf-8").strip()
# Create new branch and return created branch name
try:
# 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
@staticmethod
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_email = os.environ.get("GIT_APP_EMAIL")
# Add all files to git staging
CommandRunner.run_or_fail(["git", "add", "-A", "-v"], stage="AddFiles")
# Reset environment and git config
clean_env = os.environ.copy()
clean_env["LANG"] = "C.UTF-8"
clean_env["GIT_CONFIG_GLOBAL"] = "/dev/null"
clean_env["GIT_CONFIG_NOSYSTEM"] = "1"
# Commit with settings above
CommandRunner.run_or_fail(
[
"git",
"-c",
f"user.name={user_name}",
"-c",
f"user.email={user_email}",
"commit",
"-m",
f"feat({scope}): update to {version}",
],
stage="CreateCommit",
env=clean_env,
)
return True
@staticmethod
def push(branch: str):
CommandRunner.run_or_fail(
["git", "push", "-u", "origin", branch], stage="PushBranch"
)
@staticmethod
def clean_repo():
CommandRunner.run_or_fail(
["git", "reset", "--hard", "HEAD"], stage="ResetRepository"
)
CommandRunner.run_or_fail(
["git", "checkout", Git.default_branch], stage="CheckoutDefaultBranch"
)
class GitHub:
@staticmethod
def check_newer_tag(repo, current_tag) -> UpdateStatusFalse | UpdateStatusTrue:
# GET /repos/:owner/:repo/git/refs/tags
url = f"https://api.github.com/repos/{repo}/git/refs/tags"
# Send a GET request to the GitHub API
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 response.status_code == 200:
# Parse the JSON response
data = response.json()
if len(data) == 0:
return {
"has_updates": False,
}
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/", "")
if latest_version.compare(current_version) <= 0:
return {
"has_updates": False,
}
return {
"has_updates": True,
"version": latest_tag,
"compare_url": f"https://github.com/{repo}/compare/{current_tag}...{latest_tag}",
"head_ref": latest_ref["object"]["sha"],
"head_url": f"https://github.com/{repo}/releases/tag/{latest_tag}",
}
else:
# If the request was not successful, raise an exception
raise Exception(
f"GitHub API request failed with status code {response.status_code}: {response.json()}"
)
@staticmethod
def check_updates(repo, branch, version) -> UpdateStatusFalse | UpdateStatusTrue:
url = f"https://api.github.com/repos/{repo}/compare/{version}...{branch}"
# Send a GET request to the GitHub API
response = requests.get(url)
# If the request was successful
if response.status_code == 200:
# Parse the JSON response
data = response.json()
# If the base is behind the head, there is a newer version
has_updates = data["status"] != "identical"
if not has_updates:
return {
"has_updates": False,
}
return {
"has_updates": data["status"] != "identical",
"version": data["commits"][-1]["sha"],
"compare_url": data["permalink_url"],
"head_ref": data["commits"][-1]["sha"],
"head_url": data["commits"][-1]["html_url"],
}
else:
# If the request was not successful, raise an exception
raise Exception(
f"GitHub API request failed with status code {response.status_code}: {response.json()}"
)
@staticmethod
def create_issue(title: str, body: str) -> None:
cmd = ["gh", "issue", "create", "-t", title, "-b", body]
CommandRunner.run_or_fail(cmd, stage="CreateIssue")
@staticmethod
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 = [
"gh",
"pr",
"create",
"-B",
Git.default_branch,
"-H",
branch,
"-t",
title,
"-b",
body,
]
CommandRunner.run_or_fail(cmd, stage="CreatePullRequest")
def main():
# Load the YAML file
with open(DEPS_YAML_FILE, "r") as yaml_file:
data: DependencyYAML = yaml.safe_load(yaml_file)
if "dependencies" not in data:
raise Exception("dependencies.yml not properly formatted")
# Cache YAML version
DependencyStore.set(data)
dependencies = data["dependencies"]
for path in dependencies:
dependency = Dependency(path, dependencies[path])
dependency.update_or_notify()
if __name__ == "__main__":
main()

View file

@ -3,9 +3,9 @@ on:
workflow_dispatch: {}
push:
paths:
- tools/install.sh
- .github/workflows/installer
- .github/workflows/installer.yml
- 'tools/install.sh'
- '.github/workflows/installer/**'
- '.github/workflows/installer.yml'
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
@ -17,6 +17,7 @@ permissions:
jobs:
test:
name: Test installer
if: github.repository == 'ohmyzsh/ohmyzsh'
runs-on: ${{ matrix.os }}
strategy:
matrix:
@ -25,7 +26,7 @@ jobs:
- macos-latest
steps:
- name: Set up git repository
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Install zsh
if: runner.os == 'Linux'
run: sudo apt-get update; sudo apt-get install zsh
@ -41,15 +42,15 @@ jobs:
- test
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Install Vercel CLI
run: npm install -g vercel
- name: Setup project and deploy
env:
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
run: |
cp tools/install.sh .github/workflows/installer/install.sh
cd .github/workflows/installer
vc link --yes -t ${{ secrets.VERCEL_TOKEN }}
vc deploy --prod -t ${{ secrets.VERCEL_TOKEN }}
vc deploy --prod -t "$VERCEL_TOKEN"

View file

@ -1,13 +1,22 @@
{
"headers": [
{
"source": "/((?!favicon.ico).*)",
"headers": [{ "key": "Content-Type", "value": "text/plain" }]
"source": "/(|install.sh)",
"headers": [
{
"key": "Content-Type",
"value": "text/plain"
},
{
"key": "Content-Disposition",
"value": "inline; filename=\"install.sh\""
}
]
}
],
"rewrites": [
{
"source": "/((?!favicon.ico|install.sh).*)",
"source": "/",
"destination": "/install.sh"
}
]

View file

@ -20,16 +20,12 @@ permissions:
jobs:
tests:
name: Run tests
runs-on: ${{ matrix.os }}
runs-on: ubuntu-latest
if: github.repository == 'ohmyzsh/ohmyzsh'
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
steps:
- name: Set up git repository
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Install zsh
if: runner.os == 'Linux'
run: sudo apt-get update; sudo apt-get install zsh
- name: Check syntax
run: |

View file

@ -15,9 +15,15 @@ jobs:
name: Add to project
runs-on: ubuntu-latest
if: github.repository == 'ohmyzsh/ohmyzsh'
env:
GITHUB_TOKEN: ${{ secrets.PROJECT_TOKEN }}
steps:
- name: Authenticate as @ohmyzsh
id: generate_token
uses: ohmyzsh/github-app-token@v2
with:
app_id: ${{ secrets.OHMYZSH_APP_ID }}
private_key: ${{ secrets.OHMYZSH_APP_PRIVATE_KEY }}
- name: Store app token
run: echo "GH_TOKEN=${{ steps.generate_token.outputs.token }}" >> "$GITHUB_ENV"
- name: Read project data
env:
ORGANIZATION: ohmyzsh

285
README.md
View file

@ -1,53 +1,60 @@
<p align="center"><img src="https://ohmyzsh.s3.amazonaws.com/omz-ansi-github.png" alt="Oh My Zsh"></p>
Oh My Zsh is an open source, community-driven framework for managing your [zsh](https://www.zsh.org/) configuration.
Oh My Zsh is an open source, community-driven framework for managing your [zsh](https://www.zsh.org/)
configuration.
Sounds boring. Let's try again.
**Oh My Zsh will not make you a 10x developer...but you may feel like one.**
Once installed, your terminal shell will become the talk of the town _or your money back!_ With each keystroke in your command prompt, you'll take advantage of the hundreds of powerful plugins and beautiful themes. Strangers will come up to you in cafés and ask you, _"that is amazing! are you some sort of genius?"_
Once installed, your terminal shell will become the talk of the town _or your money back!_ With each keystroke
in your command prompt, you'll take advantage of the hundreds of powerful plugins and beautiful themes.
Strangers will come up to you in cafés and ask you, _"that is amazing! are you some sort of genius?"_
Finally, you'll begin to get the sort of attention that you have always felt you deserved. ...or maybe you'll use the time that you're saving to start flossing more often. 😬
Finally, you'll begin to get the sort of attention that you have always felt you deserved. ...or maybe you'll
use the time that you're saving to start flossing more often. 😬
To learn more, visit [ohmyz.sh](https://ohmyz.sh), follow [@ohmyzsh](https://twitter.com/ohmyzsh) on Twitter, and join us on [Discord](https://discord.gg/ohmyzsh).
To learn more, visit [ohmyz.sh](https://ohmyz.sh), follow [@ohmyzsh](https://x.com/ohmyzsh) on X (formerly
Twitter), and join us on [Discord](https://discord.gg/ohmyzsh).
[![CI](https://github.com/ohmyzsh/ohmyzsh/workflows/CI/badge.svg)](https://github.com/ohmyzsh/ohmyzsh/actions?query=workflow%3ACI)
[![Follow @ohmyzsh](https://img.shields.io/twitter/follow/ohmyzsh?label=Follow+@ohmyzsh&style=flat)](https://twitter.com/intent/follow?screen_name=ohmyzsh)
[![X (formerly Twitter) Follow](https://img.shields.io/twitter/follow/ohmyzsh?label=%40ohmyzsh&logo=x&style=flat)](https://twitter.com/intent/follow?screen_name=ohmyzsh)
[![Mastodon Follow](https://img.shields.io/mastodon/follow/111169632522566717?label=%40ohmyzsh&domain=https%3A%2F%2Fmstdn.social&logo=mastodon&style=flat)](https://mstdn.social/@ohmyzsh)
[![Discord server](https://img.shields.io/discord/642496866407284746)](https://discord.gg/ohmyzsh)
[![Gitpod ready](https://img.shields.io/badge/Gitpod-ready-blue?logo=gitpod)](https://gitpod.io/#https://github.com/ohmyzsh/ohmyzsh)
[![huntr.dev](https://cdn.huntr.dev/huntr_security_badge_mono.svg)](https://huntr.dev/bounties/disclose/?utm_campaign=ohmyzsh%2Fohmyzsh&utm_medium=social&utm_source=github&target=https%3A%2F%2Fgithub.com%2Fohmyzsh%2Fohmyzsh)
<details>
<summary>Table of Contents</summary>
- [Getting Started](#getting-started)
- [Operating System Compatibility](#operating-system-compatibility)
- [Prerequisites](#prerequisites)
- [Basic Installation](#basic-installation)
- [Manual inspection](#manual-inspection)
- [Manual Inspection](#manual-inspection)
- [Using Oh My Zsh](#using-oh-my-zsh)
- [Plugins](#plugins)
- [Enabling Plugins](#enabling-plugins)
- [Using Plugins](#using-plugins)
- [Themes](#themes)
- [Selecting a Theme](#selecting-a-theme)
- [Selecting A Theme](#selecting-a-theme)
- [FAQ](#faq)
- [Advanced Topics](#advanced-topics)
- [Advanced Installation](#advanced-installation)
- [Custom Directory](#custom-directory)
- [Unattended install](#unattended-install)
- [Installing from a forked repository](#installing-from-a-forked-repository)
- [Unattended Install](#unattended-install)
- [Installing From A Forked Repository](#installing-from-a-forked-repository)
- [Manual Installation](#manual-installation)
- [Installation Problems](#installation-problems)
- [Custom Plugins and Themes](#custom-plugins-and-themes)
- [Enable GNU ls in macOS and freeBSD systems](#enable-gnu-ls)
- [Skip aliases](#skip-aliases)
- [Custom Plugins And Themes](#custom-plugins-and-themes)
- [Enable GNU ls In macOS And freeBSD Systems](#enable-gnu-ls-in-macos-and-freebsd-systems)
- [Skip Aliases](#skip-aliases)
- [Async git prompt](#async-git-prompt)
- [Getting Updates](#getting-updates)
- [Updates verbosity](#updates-verbosity)
- [Updates Verbosity](#updates-verbosity)
- [Manual Updates](#manual-updates)
- [Uninstalling Oh My Zsh](#uninstalling-oh-my-zsh)
- [How do I contribute to Oh My Zsh?](#how-do-i-contribute-to-oh-my-zsh)
- [Do NOT send us themes](#do-not-send-us-themes)
- [How Do I Contribute To Oh My Zsh?](#how-do-i-contribute-to-oh-my-zsh)
- [Do Not Send Us Themes](#do-not-send-us-themes)
- [Contributors](#contributors)
- [Follow Us](#follow-us)
- [Merchandise](#merchandise)
@ -58,16 +65,30 @@ To learn more, visit [ohmyz.sh](https://ohmyz.sh), follow [@ohmyzsh](https://twi
## Getting Started
### Operating System Compatibility
| O/S | Status |
| :------------- | :----: |
| Android | ✅ |
| freeBSD | ✅ |
| LCARS | 🛸 |
| Linux | ✅ |
| macOS | ✅ |
| OS/2 Warp | ❌ |
| Windows (WSL2) | ✅ |
### Prerequisites
- A Unix-like operating system: macOS, Linux, BSD. On Windows: WSL2 is preferred, but cygwin or msys also mostly work.
- [Zsh](https://www.zsh.org) should be installed (v4.3.9 or more recent is fine but we prefer 5.0.8 and newer). If not pre-installed (run `zsh --version` to confirm), check the following wiki instructions here: [Installing ZSH](https://github.com/ohmyzsh/ohmyzsh/wiki/Installing-ZSH)
- [Zsh](https://www.zsh.org) should be installed (v4.3.9 or more recent is fine but we prefer 5.0.8 and
newer). If not pre-installed (run `zsh --version` to confirm), check the following wiki instructions here:
[Installing ZSH](https://github.com/ohmyzsh/ohmyzsh/wiki/Installing-ZSH)
- `curl` or `wget` should be installed
- `git` should be installed (recommended v2.4.11 or higher)
### Basic Installation
Oh My Zsh is installed by running one of the following commands in your terminal. You can install this via the command-line with either `curl`, `wget` or another similar tool.
Oh My Zsh is installed by running one of the following commands in your terminal. You can install this via the
command-line with either `curl`, `wget` or another similar tool.
| Method | Command |
| :-------- | :------------------------------------------------------------------------------------------------ |
@ -75,28 +96,44 @@ Oh My Zsh is installed by running one of the following commands in your terminal
| **wget** | `sh -c "$(wget -O- https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"` |
| **fetch** | `sh -c "$(fetch -o - https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"` |
_Note that any previous `.zshrc` will be renamed to `.zshrc.pre-oh-my-zsh`. After installation, you can move the configuration you want to preserve into the new `.zshrc`._
Alternatively, the installer is also mirrored outside GitHub. Using this URL instead may be required if you're
in a country like China or India (for certain ISPs), that blocks `raw.githubusercontent.com`:
#### Manual inspection
| Method | Command |
| :-------- | :------------------------------------------------ |
| **curl** | `sh -c "$(curl -fsSL https://install.ohmyz.sh/)"` |
| **wget** | `sh -c "$(wget -O- https://install.ohmyz.sh/)"` |
| **fetch** | `sh -c "$(fetch -o - https://install.ohmyz.sh/)"` |
It's a good idea to inspect the install script from projects you don't yet know. You can do
that by downloading the install script first, looking through it so everything looks normal,
then running it:
_Note that any previous `.zshrc` will be renamed to `.zshrc.pre-oh-my-zsh`. After installation, you can move
the configuration you want to preserve into the new `.zshrc`._
#### Manual Inspection
It's a good idea to inspect the install script from projects you don't yet know. You can do that by
downloading the install script first, looking through it so everything looks normal, then running it:
```sh
wget https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh
sh install.sh
```
If the above URL times out or otherwise fails, you may have to substitute the URL for
`https://install.ohmyz.sh` to be able to get the script.
## Using Oh My Zsh
### Plugins
Oh My Zsh comes with a shitload of plugins for you to take advantage of. You can take a look in the [plugins](https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins) directory and/or the [wiki](https://github.com/ohmyzsh/ohmyzsh/wiki/Plugins) to see what's currently available.
Oh My Zsh comes with a shitload of plugins for you to take advantage of. You can take a look in the
[plugins](https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins) directory and/or the
[wiki](https://github.com/ohmyzsh/ohmyzsh/wiki/Plugins) to see what's currently available.
#### Enabling Plugins
Once you spot a plugin (or several) that you'd like to use with Oh My Zsh, you'll need to enable them in the `.zshrc` file. You'll find the zshrc file in your `$HOME` directory. Open it with your favorite text editor and you'll see a spot to list all the plugins you want to load.
Once you spot a plugin (or several) that you'd like to use with Oh My Zsh, you'll need to enable them in the
`.zshrc` file. You'll find the zshrc file in your `$HOME` directory. Open it with your favorite text editor
and you'll see a spot to list all the plugins you want to load.
```sh
vi ~/.zshrc
@ -116,21 +153,28 @@ plugins=(
)
```
_Note that the plugins are separated by whitespace (spaces, tabs, new lines...). **Do not** use commas between them or it will break._
_Note that the plugins are separated by whitespace (spaces, tabs, new lines...). **Do not** use commas between
them or it will break._
#### Using Plugins
Each built-in plugin includes a **README**, documenting it. This README should show the aliases (if the plugin adds any) and extra goodies that are included in that particular plugin.
Each built-in plugin includes a **README**, documenting it. This README should show the aliases (if the plugin
adds any) and extra goodies that are included in that particular plugin.
### Themes
We'll admit it. Early in the Oh My Zsh world, we may have gotten a bit too theme happy. We have over one hundred and fifty themes now bundled. Most of them have [screenshots](https://github.com/ohmyzsh/ohmyzsh/wiki/Themes) on the wiki (We are working on updating this!). Check them out!
We'll admit it. Early in the Oh My Zsh world, we may have gotten a bit too theme happy. We have over one
hundred and fifty themes now bundled. Most of them have
[screenshots](https://github.com/ohmyzsh/ohmyzsh/wiki/Themes) on the wiki (We are working on updating this!).
Check them out!
#### Selecting a Theme
#### Selecting A Theme
_Robby's theme is the default one. It's not the fanciest one. It's not the simplest one. It's just the right one (for him)._
_Robby's theme is the default one. It's not the fanciest one. It's not the simplest one. It's just the right
one (for him)._
Once you find a theme that you'd like to use, you will need to edit the `~/.zshrc` file. You'll see an environment variable (all caps) in there that looks like:
Once you find a theme that you'd like to use, you will need to edit the `~/.zshrc` file. You'll see an
environment variable (all caps) in there that looks like:
```sh
ZSH_THEME="robbyrussell"
@ -143,15 +187,32 @@ ZSH_THEME="agnoster" # (this is one of the fancy ones)
# see https://github.com/ohmyzsh/ohmyzsh/wiki/Themes#agnoster
```
_Note: many themes require installing a [Powerline Font](https://github.com/powerline/fonts) or a [Nerd Font](https://github.com/ryanoasis/nerd-fonts) in order to render properly. Without them, these themes will render [weird prompt symbols](https://github.com/ohmyzsh/ohmyzsh/wiki/FAQ#i-have-a-weird-character-in-my-prompt)_
<!-- prettier-ignore-start -->
> [!NOTE]
> You will many times see screenshots for a zsh theme, and try it out, and find that it doesn't look the same for you.
>
> This is because many themes require installing a [Powerline Font](https://github.com/powerline/fonts) or a
> [Nerd Font](https://github.com/ryanoasis/nerd-fonts) in order to render properly. Without them, these themes
> will render weird prompt symbols. Check out
> [the FAQ](https://github.com/ohmyzsh/ohmyzsh/wiki/FAQ#i-have-a-weird-character-in-my-prompt) for more
> information.
>
> Also, beware that themes only control what your prompt looks like. This is, the text you see before or after
> your cursor, where you'll type your commands. Themes don't control things such as the colors of your
> terminal window (known as _color scheme_) or the font of your terminal. These are settings that you can
> change in your terminal emulator. For more information, see
> [what is a zsh theme](https://github.com/ohmyzsh/ohmyzsh/wiki/FAQ#what-is-a-zsh-theme).
<!-- prettier-ignore-end -->
Open up a new terminal window and your prompt should look something like this:
![Agnoster theme](https://cloud.githubusercontent.com/assets/2618447/6316862/70f58fb6-ba03-11e4-82c9-c083bf9a6574.png)
In case you did not find a suitable theme for your needs, please have a look at the wiki for [more of them](https://github.com/ohmyzsh/ohmyzsh/wiki/External-themes).
In case you did not find a suitable theme for your needs, please have a look at the wiki for
[more of them](https://github.com/ohmyzsh/ohmyzsh/wiki/External-themes).
If you're feeling feisty, you can let the computer select one randomly for you each time you open a new terminal window.
If you're feeling feisty, you can let the computer select one randomly for you each time you open a new
terminal window.
```sh
ZSH_THEME="random" # (...please let it be pie... please be some pie..)
@ -174,7 +235,8 @@ ZSH_THEME_RANDOM_IGNORED=(pygmalion tjkirch_mod)
### FAQ
If you have some more questions or issues, you might find a solution in our [FAQ](https://github.com/ohmyzsh/ohmyzsh/wiki/FAQ).
If you have some more questions or issues, you might find a solution in our
[FAQ](https://github.com/ohmyzsh/ohmyzsh/wiki/FAQ).
## Advanced Topics
@ -182,47 +244,50 @@ If you're the type that likes to get their hands dirty, these sections might res
### Advanced Installation
Some users may want to manually install Oh My Zsh, or change the default path or other settings that
the installer accepts (these settings are also documented at the top of the install script).
Some users may want to manually install Oh My Zsh, or change the default path or other settings that the
installer accepts (these settings are also documented at the top of the install script).
#### Custom Directory
The default location is `~/.oh-my-zsh` (hidden in your home directory, you can access it with `cd ~/.oh-my-zsh`)
The default location is `~/.oh-my-zsh` (hidden in your home directory, you can access it with
`cd ~/.oh-my-zsh`)
If you'd like to change the install directory with the `ZSH` environment variable, either by running
`export ZSH=/your/path` before installing, or by setting it before the end of the install pipeline
like this:
`export ZSH=/your/path` before installing, or by setting it before the end of the install pipeline like this:
```sh
ZSH="$HOME/.dotfiles/oh-my-zsh" sh install.sh
```
#### Unattended install
#### Unattended Install
If you're running the Oh My Zsh install script as part of an automated install, you can pass the `--unattended`
flag to the `install.sh` script. This will have the effect of not trying to change
the default shell, and it also won't run `zsh` when the installation has finished.
If you're running the Oh My Zsh install script as part of an automated install, you can pass the
`--unattended` flag to the `install.sh` script. This will have the effect of not trying to change the default
shell, and it also won't run `zsh` when the installation has finished.
```sh
sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended
```
#### Installing from a forked repository
If you're in China, India, or another country that blocks `raw.githubusercontent.com`, you may have to
substitute the URL for `https://install.ohmyz.sh` for it to install.
The install script also accepts these variables to allow installation of a different repository:
#### Installing From A Forked Repository
- `REPO` (default: `ohmyzsh/ohmyzsh`): this takes the form of `owner/repository`. If you set
this variable, the installer will look for a repository at `https://github.com/{owner}/{repository}`.
The install script also accepts these variables to allow the installation of a different repository:
- `REMOTE` (default: `https://github.com/${REPO}.git`): this is the full URL of the git repository
clone. You can use this setting if you want to install from a fork that is not on GitHub (GitLab,
Bitbucket...) or if you want to clone with SSH instead of HTTPS (`git@github.com:user/project.git`).
- `REPO` (default: `ohmyzsh/ohmyzsh`): this takes the form of `owner/repository`. If you set this variable,
the installer will look for a repository at `https://github.com/{owner}/{repository}`.
- `REMOTE` (default: `https://github.com/${REPO}.git`): this is the full URL of the git repository clone. You
can use this setting if you want to install from a fork that is not on GitHub (GitLab, Bitbucket...) or if
you want to clone with SSH instead of HTTPS (`git@github.com:user/project.git`).
_NOTE: it's incompatible with setting the `REPO` variable. This setting will take precedence._
- `BRANCH` (default: `master`): you can use this setting if you want to change the default branch to be
checked out when cloning the repository. This might be useful for testing a Pull Request, or if you
want to use a branch other than `master`.
checked out when cloning the repository. This might be useful for testing a Pull Request, or if you want to
use a branch other than `master`.
For example:
@ -232,19 +297,19 @@ REPO=apjanke/oh-my-zsh BRANCH=edge sh install.sh
#### Manual Installation
##### 1. Clone the repository <!-- omit in toc -->
##### 1. Clone The Repository <!-- omit in toc -->
```sh
git clone https://github.com/ohmyzsh/ohmyzsh.git ~/.oh-my-zsh
```
##### 2. _Optionally_, backup your existing `~/.zshrc` file <!-- omit in toc -->
##### 2. _Optionally_, Backup Your Existing `~/.zshrc` File <!-- omit in toc -->
```sh
cp ~/.zshrc ~/.zshrc.orig
```
##### 3. Create a new zsh configuration file <!-- omit in toc -->
##### 3. Create A New Zsh Configuration File <!-- omit in toc -->
You can create a new zsh config file by copying the template that we have included for you.
@ -252,7 +317,7 @@ You can create a new zsh config file by copying the template that we have includ
cp ~/.oh-my-zsh/templates/zshrc.zsh-template ~/.zshrc
```
##### 4. Change your default shell <!-- omit in toc -->
##### 4. Change Your Default Shell <!-- omit in toc -->
```sh
chsh -s $(which zsh)
@ -260,7 +325,7 @@ chsh -s $(which zsh)
You must log out from your user session and log back in to see this change.
##### 5. Initialize your new zsh configuration <!-- omit in toc -->
##### 5. Initialize Your New Zsh Configuration <!-- omit in toc -->
Once you open up a new terminal window, it should load zsh with Oh My Zsh's configuration.
@ -268,22 +333,27 @@ Once you open up a new terminal window, it should load zsh with Oh My Zsh's conf
If you have any hiccups installing, here are a few common fixes.
- You _might_ need to modify your `PATH` in `~/.zshrc` if you're not able to find some commands after switching to `oh-my-zsh`.
- If you installed manually or changed the install location, check the `ZSH` environment variable in `~/.zshrc`.
- You _might_ need to modify your `PATH` in `~/.zshrc` if you're not able to find some commands after
switching to `oh-my-zsh`.
- If you installed manually or changed the install location, check the `ZSH` environment variable in
`~/.zshrc`.
### Custom Plugins and Themes
### Custom Plugins And Themes
If you want to override any of the default behaviors, just add a new file (ending in `.zsh`) in the `custom/` directory.
If you want to override any of the default behaviors, just add a new file (ending in `.zsh`) in the `custom/`
directory.
If you have many functions that go well together, you can put them as a `XYZ.plugin.zsh` file in the `custom/plugins/` directory and then enable this plugin.
If you have many functions that go well together, you can put them as a `XYZ.plugin.zsh` file in the
`custom/plugins/` directory and then enable this plugin.
If you would like to override the functionality of a plugin distributed with Oh My Zsh, create a plugin of the same name in the `custom/plugins/` directory and it will be loaded instead of the one in `plugins/`.
If you would like to override the functionality of a plugin distributed with Oh My Zsh, create a plugin of the
same name in the `custom/plugins/` directory and it will be loaded instead of the one in `plugins/`.
### Enable GNU ls in macOS and freeBSD systems
### Enable GNU ls In macOS And freeBSD Systems
<a name="enable-gnu-ls"></a>
The default behaviour in Oh My Zsh is to use BSD `ls` in macOS and freeBSD systems. If GNU `ls` is installed
The default behaviour in Oh My Zsh is to use BSD `ls` in macOS and FreeBSD systems. If GNU `ls` is installed
(as `gls` command), you can choose to use it instead. To do it, you can use zstyle-based config before
sourcing `oh-my-zsh.sh`:
@ -293,13 +363,13 @@ zstyle ':omz:lib:theme-and-appearance' gnu-ls yes
_Note: this is not compatible with `DISABLE_LS_COLORS=true`_
### Skip aliases
### Skip Aliases
<a name="remove-directories-aliases"></a>
If you want to skip default Oh My Zsh aliases (those defined in `lib/*` files) or plugin aliases,
you can use the settings below in your `~/.zshrc` file, **before Oh My Zsh is loaded**. Note that
there are many different ways to skip aliases, depending on your needs.
If you want to skip default Oh My Zsh aliases (those defined in `lib/*` files) or plugin aliases, you can use
the settings below in your `~/.zshrc` file, **before Oh My Zsh is loaded**. Note that there are many different
ways to skip aliases, depending on your needs.
```sh
# Skip all aliases, in lib files and enabled plugins
@ -316,7 +386,7 @@ zstyle ':omz:plugins:*' aliases no
zstyle ':omz:plugins:git' aliases no
```
You can combine these in other ways taking into account that more specific scopes takes precedence:
You can combine these in other ways taking into account that more specific scopes take precedence:
```sh
# Skip all plugin aliases, except for the git plugin
@ -338,16 +408,36 @@ zstyle ':omz:lib:directories' aliases no
#### Notice <!-- omit in toc -->
> This feature is currently in a testing phase and it may be subject to change in the future.
> It is also not currently compatible with plugin managers such as zpm or zinit, which don't
> source the init script (`oh-my-zsh.sh`) where this feature is implemented in.
> This feature is currently in a testing phase and it may be subject to change in the future. It is also not
> currently compatible with plugin managers such as zpm or zinit, which don't source the init script
> (`oh-my-zsh.sh`) where this feature is implemented in.
> It is also not currently aware of "aliases" that are defined as functions. Example of such
> are `gccd`, `ggf`, or `ggl` functions from the git plugin.
> It is also not currently aware of "aliases" that are defined as functions. Example of such are `gccd`,
> `ggf`, or `ggl` functions from the git plugin.
### Async git prompt
Async prompt functions are an experimental feature (included on April 3, 2024) that allows Oh My Zsh to render
prompt information asynchronously. 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
```
If your problem is that the git prompt just stopped appearing, you can try to force it setting the following
configuration before `oh-my-zsh.sh` is sourced. If it still does not work, please open an issue with your
case.
```sh
zstyle ':omz:alpha:lib:git' async-prompt force
```
## Getting Updates
By default, you will be prompted to check for updates every 2 weeks. You can choose other update modes by adding a line to your `~/.zshrc` file, **before Oh My Zsh is loaded**:
By default, you will be prompted to check for updates every 2 weeks. You can choose other update modes by
adding a line to your `~/.zshrc` file, **before Oh My Zsh is loaded**:
1. Automatic update without confirmation prompt:
@ -376,7 +466,7 @@ zstyle ':omz:update' frequency 7
zstyle ':omz:update' frequency 0
```
### Updates verbosity
### Updates Verbosity
You can also limit the update verbosity with the following settings:
@ -390,7 +480,8 @@ zstyle ':omz:update' verbose silent # only errors
### Manual Updates
If you'd like to update at any point in time (maybe someone just released a new plugin and you don't want to wait a week?) you just need to run:
If you'd like to update at any point in time (maybe someone just released a new plugin and you don't want to
wait a week?) you just need to run:
```sh
omz update
@ -402,40 +493,52 @@ Magic! 🎉
Oh My Zsh isn't for everyone. We'll miss you, but we want to make this an easy breakup.
If you want to uninstall `oh-my-zsh`, just run `uninstall_oh_my_zsh` from the command-line. It will remove itself and revert your previous `bash` or `zsh` configuration.
If you want to uninstall `oh-my-zsh`, just run `uninstall_oh_my_zsh` from the command-line. It will remove
itself and revert your previous `bash` or `zsh` configuration.
## How do I contribute to Oh My Zsh?
## How Do I Contribute To Oh My Zsh?
Before you participate in our delightful community, please read the [code of conduct](CODE_OF_CONDUCT.md).
I'm far from being a [Zsh](https://www.zsh.org/) expert and suspect there are many ways to improve if you have ideas on how to make the configuration easier to maintain (and faster), don't hesitate to fork and send pull requests!
I'm far from being a [Zsh](https://www.zsh.org/) expert and suspect there are many ways to improve if you
have ideas on how to make the configuration easier to maintain (and faster), don't hesitate to fork and send
pull requests!
We also need people to test out pull requests. So take a look through [the open issues](https://github.com/ohmyzsh/ohmyzsh/issues) and help where you can.
We also need people to test out pull requests. So take a look through
[the open issues](https://github.com/ohmyzsh/ohmyzsh/issues) and help where you can.
See [Contributing](CONTRIBUTING.md) for more details.
### Do NOT send us themes
### Do Not Send Us Themes
We have (more than) enough themes for the time being. Please add your theme to the [external themes](https://github.com/ohmyzsh/ohmyzsh/wiki/External-themes) wiki page.
We have (more than) enough themes for the time being. Please add your theme to the
[external themes](https://github.com/ohmyzsh/ohmyzsh/wiki/External-themes) wiki page.
## Contributors
Oh My Zsh has a vibrant community of happy users and delightful contributors. Without all the time and help from our contributors, it wouldn't be so awesome.
Oh My Zsh has a vibrant community of happy users and delightful contributors. Without all the time and help
from our contributors, it wouldn't be so awesome.
Thank you so much!
<a href="https://github.com/ohmyzsh/ohmyzsh/graphs/contributors">
<img src="https://contrib.rocks/image?repo=ohmyzsh/ohmyzsh" width="100%"/>
</a>
## Follow Us
We're on social media:
- [@ohmyzsh](https://twitter.com/ohmyzsh) on Twitter. You should follow it.
- [@ohmyzsh](https://x.com/ohmyzsh) on X (formerly Twitter). You should follow it.
- [Facebook](https://www.facebook.com/Oh-My-Zsh-296616263819290/) poke us.
- [Instagram](https://www.instagram.com/_ohmyzsh/) tag us in your post showing Oh My Zsh!
- [Discord](https://discord.gg/ohmyzsh) to chat with us!
## Merchandise
We have [stickers, shirts, and coffee mugs available](https://shop.planetargon.com/collections/oh-my-zsh?utm_source=github) for you to show off your love of Oh My Zsh. Again, you will become the talk of the town!
We have
[stickers, shirts, and coffee mugs available](https://shop.planetargon.com/collections/oh-my-zsh?utm_source=github)
for you to show off your love of Oh My Zsh. Again, you will become the talk of the town!
## License
@ -445,4 +548,6 @@ Oh My Zsh is released under the [MIT license](LICENSE.txt).
![Planet Argon](https://pa-github-assets.s3.amazonaws.com/PARGON_logo_digital_COL-small.jpg)
Oh My Zsh was started by the team at [Planet Argon](https://www.planetargon.com/?utm_source=github), a [Ruby on Rails development agency](http://www.planetargon.com/services/ruby-on-rails-development?utm_source=github). Check out our [other open source projects](https://www.planetargon.com/open-source?utm_source=github).
Oh My Zsh was started by the team at [Planet Argon](https://www.planetargon.com/?utm_source=github), a
[Ruby on Rails development agency](https://www.planetargon.com/services/ruby-on-rails-development?utm_source=github).
Check out our [other open source projects](https://www.planetargon.com/open-source?utm_source=github).

View file

@ -17,8 +17,7 @@ In the near future we will introduce versioning, so expect this section to chang
**Do not submit an issue or pull request**: this might reveal the vulnerability.
Instead, you should email the maintainers directly at: [**security@ohmyz.sh**](mailto:security@ohmyz.sh).
Instead, you should use the form to [privately report a vulnerability to us via GitHub](https://github.com/ohmyzsh/ohmyzsh/security/advisories/new)
or email the maintainers directly at: [**security@ohmyz.sh**](mailto:security@ohmyz.sh).
We will deal with the vulnerability privately and submit a patch as soon as possible.
You can also submit your vulnerability report to [huntr.dev](https://huntr.dev/bounties/disclose/?utm_campaign=ohmyzsh%2Fohmyzsh&utm_medium=social&utm_source=github&target=https%3A%2F%2Fgithub.com%2Fohmyzsh%2Fohmyzsh) and see if you can get a bounty reward.

144
lib/async_prompt.zsh Normal file
View file

@ -0,0 +1,144 @@
# The async code is taken from
# https://github.com/zsh-users/zsh-autosuggestions/blob/master/src/async.zsh
# https://github.com/woefe/git-prompt.zsh/blob/master/git-prompt.zsh
zmodload zsh/system
autoload -Uz is-at-least
# For now, async prompt function handlers are set up like so:
# First, define the async function handler and register the handler
# with _omz_register_handler:
#
# function _git_prompt_status_async {
# # Do some expensive operation that outputs to stdout
# }
# _omz_register_handler _git_prompt_status_async
#
# Then add a stub prompt function in `$PROMPT` or similar prompt variables,
# which will show the output of "$_OMZ_ASYNC_OUTPUT[handler_name]":
#
# function git_prompt_status {
# echo -n $_OMZ_ASYNC_OUTPUT[_git_prompt_status_async]
# }
#
# RPROMPT='$(git_prompt_status)'
#
# This API is subject to change and optimization. Rely on it at your own risk.
function _omz_register_handler {
setopt localoptions noksharrays
typeset -ga _omz_async_functions
# we want to do nothing if there's no $1 function or we already set it up
if [[ -z "$1" ]] || (( ! ${+functions[$1]} )) \
|| (( ${_omz_async_functions[(Ie)$1]} )); then
return
fi
_omz_async_functions+=("$1")
# let's add the hook to async_request if it's not there yet
if (( ! ${precmd_functions[(Ie)_omz_async_request]} )) \
&& (( ${+functions[_omz_async_request]})); then
autoload -Uz add-zsh-hook
add-zsh-hook precmd _omz_async_request
fi
}
# Set up async handlers and callbacks
function _omz_async_request {
local -i ret=$?
typeset -gA _OMZ_ASYNC_FDS _OMZ_ASYNC_PIDS _OMZ_ASYNC_OUTPUT
# executor runs a subshell for all async requests based on key
local handler
for handler in ${_omz_async_functions}; do
(( ${+functions[$handler]} )) || continue
local fd=${_OMZ_ASYNC_FDS[$handler]:--1}
local pid=${_OMZ_ASYNC_PIDS[$handler]:--1}
# If we've got a pending request, cancel it
if (( fd != -1 && pid != -1 )) && { true <&$fd } 2>/dev/null; then
# Close the file descriptor and remove the handler
exec {fd}<&-
zle -F $fd
# Zsh will make a new process group for the child process only if job
# control is enabled (MONITOR option)
if [[ -o MONITOR ]]; then
# Send the signal to the process group to kill any processes that may
# have been forked by the async function handler
kill -TERM -$pid 2>/dev/null
else
# Kill just the child process since it wasn't placed in a new process
# group. If the async function handler forked any child processes they may
# be orphaned and left behind.
kill -TERM $pid 2>/dev/null
fi
fi
# Define global variables to store the file descriptor, PID and output
_OMZ_ASYNC_FDS[$handler]=-1
_OMZ_ASYNC_PIDS[$handler]=-1
# Fork a process to fetch the git status and open a pipe to read from it
exec {fd}< <(
# Tell parent process our PID
builtin echo ${sysparams[pid]}
# Set exit code for the handler if used
() { return $ret }
# Run the async function handler
$handler
)
# Save FD for handler
_OMZ_ASYNC_FDS[$handler]=$fd
# 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
# 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
read -u $fd "_OMZ_ASYNC_PIDS[$handler]"
# When the fd is readable, call the response handler
zle -F "$fd" _omz_async_callback
done
}
# Called when new data is ready to be read from the pipe
function _omz_async_callback() {
emulate -L zsh
local fd=$1 # First arg will be fd ready for reading
local err=$2 # Second arg will be passed in case of error
if [[ -z "$err" || "$err" == "hup" ]]; then
# Get handler name from fd
local handler="${(k)_OMZ_ASYNC_FDS[(r)$fd]}"
# Store old output which is supposed to be already printed
local old_output="${_OMZ_ASYNC_OUTPUT[$handler]}"
# Read output from fd
IFS= read -r -u $fd -d '' "_OMZ_ASYNC_OUTPUT[$handler]"
# Repaint prompt if output has changed
if [[ "$old_output" != "${_OMZ_ASYNC_OUTPUT[$handler]}" ]]; then
zle .reset-prompt
zle -R
fi
# Close the fd
exec {fd}<&-
fi
# Always remove the handler
zle -F "$fd"
# Unset global FD variable to prevent closing user created FDs in the precmd hook
_OMZ_ASYNC_FDS[$handler]=-1
_OMZ_ASYNC_PIDS[$handler]=-1
}
autoload -Uz add-zsh-hook
add-zsh-hook precmd _omz_async_request

View file

@ -1,10 +1,14 @@
## Bazaar integration
## Just works with the GIT integration just add $(bzr_prompt_info) to the PROMPT
## Just works with the GIT integration. Add $(bzr_prompt_info) to the PROMPT
function bzr_prompt_info() {
BZR_CB=`bzr nick 2> /dev/null | grep -v "ERROR" | cut -d ":" -f2 | awk -F / '{print "bzr::"$1}'`
if [ -n "$BZR_CB" ]; then
BZR_DIRTY=""
[[ -n `bzr status` ]] && BZR_DIRTY=" %{$fg[red]%} * %{$fg[green]%}"
echo "$ZSH_THEME_SCM_PROMPT_PREFIX$BZR_CB$BZR_DIRTY$ZSH_THEME_GIT_PROMPT_SUFFIX"
local bzr_branch
bzr_branch=$(bzr nick 2>/dev/null) || return
if [[ -n "$bzr_branch" ]]; then
local bzr_dirty=""
if [[ -n $(bzr status 2>/dev/null) ]]; then
bzr_dirty=" %{$fg[red]%}*%{$reset_color%}"
fi
printf "%s%s%s%s" "$ZSH_THEME_SCM_PROMPT_PREFIX" "bzr::${bzr_branch##*:}" "$bzr_dirty" "$ZSH_THEME_GIT_PROMPT_SUFFIX"
fi
}

View file

@ -241,10 +241,18 @@ function _omz::plugin::disable {
# Remove plugins substitution awk script
local awk_subst_plugins="\
gsub(/[ \t]+(${(j:|:)dis_plugins})/, \"\") # with spaces before
gsub(/(${(j:|:)dis_plugins})[ \t]+/, \"\") # with spaces after
gsub(/\((${(j:|:)dis_plugins})\)/, \"\") # without spaces (only plugin)
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
@ -336,20 +344,40 @@ function _omz::plugin::enable {
next
}
# if plugins=() is in multiline form, enable multi flag
# if plugins=() is in multiline form, enable multi flag and indent by default with 2 spaces
/^[ \t]*plugins=\(/ {
multi=1
indent=\" \"
print \$0
next
}
# if multi flag is enabled and we find a valid closing parenthesis,
# add new plugins and disable multi flag
# add new plugins with proper indent and disable multi flag
multi == 1 && /^[^#]*\)/ {
multi=0
sub(/\)/, \" $add_plugins&\")
split(\"$add_plugins\",p,\" \")
for (i in p) {
print indent p[i]
}
print \$0
next
}
# if multi flag is enabled and we didnt find a closing parenthesis,
# get the indentation level to match when adding plugins
multi == 1 && /^[^#]*/ {
indent=\"\"
for (i = 1; i <= length(\$0); i++) {
char=substr(\$0, i, 1)
if (char == \" \" || char == \"\t\") {
indent = indent char
} else {
break
}
}
}
{ print \$0 }
"
@ -389,8 +417,23 @@ function _omz::plugin::info {
local readme
for readme in "$ZSH_CUSTOM/plugins/$1/README.md" "$ZSH/plugins/$1/README.md"; do
if [[ -f "$readme" ]]; then
(( ${+commands[less]} )) && less "$readme" || cat "$readme"
return 0
# If being piped, just cat the README
if [[ ! -t 1 ]]; then
cat "$readme"
return $?
fi
# Enrich the README display depending on the tools we have
# - glow: https://github.com/charmbracelet/glow
# - bat: https://github.com/sharkdp/bat
# - less: typical pager command
case 1 in
${+commands[glow]}) glow -p "$readme" ;;
${+commands[bat]}) bat -l md --style plain "$readme" ;;
${+commands[less]}) less "$readme" ;;
*) cat "$readme" ;;
esac
return $?
fi
done
@ -448,7 +491,7 @@ function _omz::plugin::load {
if [[ ! -f "$base/_$plugin" && ! -f "$base/$plugin.plugin.zsh" ]]; then
_omz::log warn "'$plugin' is not a valid plugin"
continue
# It it is a valid plugin, add its directory to $fpath unless it is already there
# It is a valid plugin, add its directory to $fpath unless it is already there
elif (( ! ${fpath[(Ie)$base]} )); then
fpath=("$base" $fpath)
fi
@ -773,7 +816,17 @@ function _omz::theme::use {
}
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
zstyle -s ':omz:update' verbose verbose_mode || verbose_mode=default

View file

@ -62,7 +62,7 @@ function detect-clipboard() {
function clippaste() { powershell.exe -noprofile -command Get-Clipboard; }
elif [ -n "${WAYLAND_DISPLAY:-}" ] && (( ${+commands[wl-copy]} )) && (( ${+commands[wl-paste]} )); then
function clipcopy() { cat "${1:-/dev/stdin}" | wl-copy &>/dev/null &|; }
function clippaste() { wl-paste; }
function clippaste() { wl-paste --no-newline; }
elif [ -n "${DISPLAY:-}" ] && (( ${+commands[xsel]} )); then
function clipcopy() { cat "${1:-/dev/stdin}" | xsel --clipboard --input; }
function clippaste() { xsel --clipboard --output; }
@ -100,8 +100,8 @@ function detect-clipboard() {
fi
}
# Detect at startup. A non-zero exit here indicates that the dummy clipboards were set,
# which is not really an error. If the user calls them, they will attempt to redetect
# (for example, perhaps the user has now installed xclip) and then either print an error
# or proceed successfully.
detect-clipboard || true
function clipcopy clippaste {
unfunction clipcopy clippaste
detect-clipboard || true # let one retry
"$0" "$@"
}

View file

@ -57,6 +57,16 @@ function takeurl() {
cd "$thedir"
}
function takezip() {
local data thedir
data="$(mktemp)"
curl -L "$1" > "$data"
unzip "$data" -d "./"
thedir="$(unzip -l "$data" | awk 'NR==4 {print $4}' | sed 's/\/.*//')"
rm "$data"
cd "$thedir"
}
function takegit() {
git clone "$1"
cd "$(basename ${1%%.git})"
@ -65,6 +75,8 @@ function takegit() {
function take() {
if [[ $1 =~ ^(https?|ftp).*\.(tar\.(gz|bz2|xz)|tgz)$ ]]; then
takeurl "$1"
elif [[ $1 =~ ^(https?|ftp).*\.(zip)$ ]]; then
takezip "$1"
elif [[ $1 =~ ^([A-Za-z0-9]\+@|https?|git|ssh|ftps?|rsync).*\.git/?$ ]]; then
takegit "$1"
else
@ -160,6 +172,8 @@ zmodload zsh/langinfo
# -P causes spaces to be encoded as '%20' instead of '+'
function omz_urlencode() {
emulate -L zsh
setopt norematchpcre
local -a opts
zparseopts -D -E -a opts r m P
@ -182,6 +196,8 @@ function omz_urlencode() {
fi
# Use LC_CTYPE=C to process text byte-by-byte
# Note that this doesn't work in Termux, as it only has UTF-8 locale.
# Characters will be processed as UTF-8, which is fine for URLs.
local i byte ord LC_ALL=C
export LC_ALL
local reserved=';/?:@&=+$,'
@ -206,6 +222,9 @@ function omz_urlencode() {
else
if [[ "$byte" == " " && -n $spaces_as_plus ]]; then
url_str+="+"
elif [[ "$PREFIX" = *com.termux* ]]; then
# Termux does not have non-UTF8 locales, so just send the UTF-8 character directly
url_str+="$byte"
else
ord=$(( [##16] #byte ))
url_str+="%$ord"

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
# other processes. This environment variable is equivalent to running with `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 "$@"
}
function git_prompt_info() {
function _omz_git_prompt_info() {
# If we are on a folder not tracked by git, get out.
# Otherwise, check for hide-info at global and local repository level
if ! __git_prompt_git rev-parse --git-dir &> /dev/null \
@ -17,6 +19,10 @@ function git_prompt_info() {
return 0
fi
# Get either:
# - the current branch name
# - the tag name if we are on a tag
# - the short SHA of the current commit
local ref
ref=$(__git_prompt_git symbolic-ref --short HEAD 2> /dev/null) \
|| ref=$(__git_prompt_git describe --tags --exact-match HEAD 2> /dev/null) \
@ -33,6 +39,73 @@ function git_prompt_info() {
echo "${ZSH_THEME_GIT_PROMPT_PREFIX}${ref:gs/%/%%}${upstream:gs/%/%%}$(parse_git_dirty)${ZSH_THEME_GIT_PROMPT_SUFFIX}"
}
# Use async version if setting is enabled, or unset but zsh version is at least 5.0.6.
# This avoids async prompt issues caused by previous zsh versions:
# - https://github.com/ohmyzsh/ohmyzsh/issues/12331
# - https://github.com/ohmyzsh/ohmyzsh/issues/12360
# TODO(2024-06-12): @mcornella remove workaround when CentOS 7 reaches EOL
local _style
if zstyle -t ':omz:alpha:lib:git' async-prompt \
|| { is-at-least 5.0.6 && zstyle -T ':omz:alpha:lib:git' async-prompt }; then
function git_prompt_info() {
if [[ -n "${_OMZ_ASYNC_OUTPUT[_omz_git_prompt_info]}" ]]; then
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
}
# Conditionally register the async handler, only if it's needed in $PROMPT
# or any of the other prompt variables
function _defer_async_git_register() {
# Check if git_prompt_info is used in a prompt variable
case "${PS1}:${PS2}:${PS3}:${PS4}:${RPROMPT}:${RPS1}:${RPS2}:${RPS3}:${RPS4}" in
*(\$\(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
;;
esac
add-zsh-hook -d precmd _defer_async_git_register
unset -f _defer_async_git_register
}
# Register the async handler first. This needs to be done before
# the async request prompt is run
precmd_functions=(_defer_async_git_register $precmd_functions)
elif zstyle -s ':omz:alpha:lib:git' async-prompt _style && [[ $_style == "force" ]]; then
function git_prompt_info() {
if [[ -n "${_OMZ_ASYNC_OUTPUT[_omz_git_prompt_info]}" ]]; then
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
}
_omz_register_handler _omz_git_prompt_info
_omz_register_handler _omz_git_prompt_status
else
function git_prompt_info() {
_omz_git_prompt_info
}
function git_prompt_status() {
_omz_git_prompt_status
}
fi
# Checks if working tree is dirty
function parse_git_dirty() {
local STATUS
@ -105,6 +178,18 @@ function git_current_branch() {
echo ${ref#refs/heads/}
}
# Outputs the name of the previously checked out branch
# Usage example: git pull origin $(git_previous_branch)
# rev-parse --symbolic-full-name @{-1} only prints if it is a branch
function git_previous_branch() {
local ref
ref=$(__git_prompt_git rev-parse --quiet --symbolic-full-name @{-1} 2> /dev/null)
local ret=$?
if [[ $ret != 0 ]] || [[ -z $ref ]]; then
return # no git repo or non-branch previous ref
fi
echo ${ref#refs/heads/}
}
# Gets the number of commits ahead from remote
function git_commits_ahead() {
@ -161,7 +246,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"
}
function git_prompt_status() {
function _omz_git_prompt_status() {
[[ "$(__git_prompt_git config --get oh-my-zsh.hide-status 2>/dev/null)" = 1 ]] && return
# Maps a git status prefix to an internal constant
@ -170,7 +255,7 @@ function git_prompt_status() {
prefix_constant_map=(
'\?\? ' 'UNTRACKED'
'A ' 'ADDED'
'M ' 'ADDED'
'M ' 'MODIFIED'
'MM ' 'MODIFIED'
' M ' 'MODIFIED'
'AM ' 'MODIFIED'

View file

@ -10,7 +10,7 @@ else
}
# Ignore these folders (if the necessary grep flags are available)
EXC_FOLDERS="{.bzr,CVS,.git,.hg,.svn,.idea,.tox}"
EXC_FOLDERS="{.bzr,CVS,.git,.hg,.svn,.idea,.tox,.venv,venv}"
# Check for --exclude-dir, otherwise check for --exclude. If --exclude
# isn't available, --color won't be either (they were released at the same
@ -24,8 +24,8 @@ else
if [[ -n "$GREP_OPTIONS" ]]; then
# export grep, egrep and fgrep settings
alias grep="grep $GREP_OPTIONS"
alias egrep="grep -E $GREP_OPTIONS"
alias fgrep="grep -F $GREP_OPTIONS"
alias egrep="grep -E"
alias fgrep="grep -F"
# write to cache file if cache directory is writable
if [[ -w "$ZSH_CACHE_DIR" ]]; then

View file

@ -1,19 +1,27 @@
## History wrapper
function omz_history {
local clear list
zparseopts -E c=clear l=list
# parse arguments and remove from $@
local clear list stamp REPLY
zparseopts -E -D c=clear l=list f=stamp E=stamp i=stamp t:=stamp
if [[ -n "$clear" ]]; then
# if -c provided, clobber the history file
echo -n >| "$HISTFILE"
# confirm action before deleting history
print -nu2 "This action will irreversibly delete your command history. Are you sure? [y/N] "
builtin read -E
[[ "$REPLY" = [yY] ]] || return 0
print -nu2 >| "$HISTFILE"
fc -p "$HISTFILE"
echo >&2 History file deleted.
elif [[ -n "$list" ]]; then
# if -l provided, run as if calling `fc' directly
builtin fc "$@"
print -u2 History file deleted.
elif [[ $# -eq 0 ]]; then
# if no arguments provided, show full history starting from 1
builtin fc $stamp -l 1
else
# unless a number is provided, show all history events (starting from 1)
[[ ${@[-1]-} = *[0-9]* ]] && builtin fc -l "$@" || builtin fc -l "$@" 1
# otherwise, run `fc -l` with a custom format
builtin fc $stamp -l "$@"
fi
}

View file

@ -32,19 +32,26 @@ if [[ -n "${terminfo[knp]}" ]]; then
fi
# Start typing + [Up-Arrow] - fuzzy find history forward
if [[ -n "${terminfo[kcuu1]}" ]]; then
autoload -U up-line-or-beginning-search
zle -N up-line-or-beginning-search
autoload -U up-line-or-beginning-search
zle -N up-line-or-beginning-search
bindkey -M emacs "^[[A" up-line-or-beginning-search
bindkey -M viins "^[[A" up-line-or-beginning-search
bindkey -M vicmd "^[[A" up-line-or-beginning-search
if [[ -n "${terminfo[kcuu1]}" ]]; then
bindkey -M emacs "${terminfo[kcuu1]}" up-line-or-beginning-search
bindkey -M viins "${terminfo[kcuu1]}" up-line-or-beginning-search
bindkey -M vicmd "${terminfo[kcuu1]}" up-line-or-beginning-search
fi
# Start typing + [Down-Arrow] - fuzzy find history backward
if [[ -n "${terminfo[kcud1]}" ]]; then
autoload -U down-line-or-beginning-search
zle -N down-line-or-beginning-search
# Start typing + [Down-Arrow] - fuzzy find history backward
autoload -U down-line-or-beginning-search
zle -N down-line-or-beginning-search
bindkey -M emacs "^[[B" down-line-or-beginning-search
bindkey -M viins "^[[B" down-line-or-beginning-search
bindkey -M vicmd "^[[B" down-line-or-beginning-search
if [[ -n "${terminfo[kcud1]}" ]]; then
bindkey -M emacs "${terminfo[kcud1]}" down-line-or-beginning-search
bindkey -M viins "${terminfo[kcud1]}" down-line-or-beginning-search
bindkey -M vicmd "${terminfo[kcud1]}" down-line-or-beginning-search

View file

@ -19,8 +19,13 @@ setopt multios # enable redirect to multiple streams: echo >file1 >
setopt long_list_jobs # show long list format job notifications
setopt interactivecomments # recognize comments
env_default 'PAGER' 'less'
env_default 'LESS' '-R'
# define pager dependant on what is available (less or more)
if (( ${+commands[less]} )); then
env_default 'PAGER' 'less'
env_default 'LESS' '-R'
elif (( ${+commands[more]} )); then
env_default 'PAGER' 'more'
fi
## super user alias
alias _='sudo '

View file

@ -20,6 +20,7 @@ function chruby_prompt_info \
jenv_prompt_info \
azure_prompt_info \
tf_prompt_info \
conda_prompt_info \
{
return 1
}
@ -40,5 +41,5 @@ ZSH_THEME_RVM_PROMPT_OPTIONS="i v g"
# use this to enable users to see their ruby version, no matter which
# version management system they use
function ruby_prompt_info() {
echo $(rvm_prompt_info || rbenv_prompt_info || chruby_prompt_info)
echo "$(rvm_prompt_info || rbenv_prompt_info || chruby_prompt_info)"
}

View file

@ -7,6 +7,7 @@ typeset -AHg FX FG BG
FX=(
reset "%{%}"
bold "%{%}" no-bold "%{%}"
dim "%{%}" no-dim "%{%}"
italic "%{%}" no-italic "%{%}"
underline "%{%}" no-underline "%{%}"
blink "%{%}" no-blink "%{%}"

View file

@ -17,7 +17,7 @@ function title {
: ${2=$1}
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]1;${1:q}\a" # set tab name
;;
@ -129,7 +129,7 @@ fi
# Don't define the function if we're in an unsupported terminal
case "$TERM" in
# 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*) ;;
*)
# Terminal.app and iTerm2 process OSC 7 correctly
@ -151,7 +151,7 @@ function omz_termsupport_cwd {
URL_PATH="$(omz_urlencode -P $PWD)" || return 1
# Konsole errors if the HOST is provided
[[ -z "$KONSOLE_VERSION" ]] || URL_HOST=""
[[ -z "$KONSOLE_PROFILE_NAME" && -z "$KONSOLE_DBUS_SESSION" ]] || URL_HOST=""
# common control sequence (OSC 7) to set current host and path
printf "\e]7;file://%s%s\e\\" "${URL_HOST}" "${URL_PATH}"

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

@ -1,14 +1,14 @@
# Protect against non-zsh execution of Oh My Zsh (use POSIX syntax here)
[ -n "$ZSH_VERSION" ] || {
# ANSI formatting function (\033[<code>m)
# 0: reset, 1: bold, 4: underline, 22: no bold, 24: no underline, 31: red, 33: yellow
omz_f() {
# ANSI formatting function (\033[<code>m)
# 0: reset, 1: bold, 4: underline, 22: no bold, 24: no underline, 31: red, 33: yellow
omz_f() {
[ $# -gt 0 ] || return
IFS=";" printf "\033[%sm" $*
}
# If stdout is not a terminal ignore all formatting
[ -t 1 ] || omz_f() { :; }
}
# If stdout is not a terminal ignore all formatting
[ -t 1 ] || omz_f() { :; }
# Protect against non-zsh execution of Oh My Zsh (use POSIX syntax here)
[ -n "$ZSH_VERSION" ] || {
omz_ptree() {
# Get process tree of the current process
pid=$$; pids="$pid"
@ -38,14 +38,25 @@
return 1
}
# Check if in emulation mode, if so early return
# https://github.com/ohmyzsh/ohmyzsh/issues/11686
[[ "$(emulate)" = zsh ]] || {
printf "$(omz_f 1 31)Error:$(omz_f 22) Oh My Zsh can't be loaded in \`$(emulate)\` emulation mode.$(omz_f 0)\n" >&2
return 1
}
unset -f omz_f
# If ZSH is not defined, use the current script's directory.
[[ -z "$ZSH" ]] && export ZSH="${${(%):-%x}:a:h}"
[[ -n "$ZSH" ]] || export ZSH="${${(%):-%x}:a:h}"
# Set ZSH_CUSTOM to the path where your custom config files
# and plugins exists, or else we will use the default custom/
[[ -n "$ZSH_CUSTOM" ]] || ZSH_CUSTOM="$ZSH/custom"
# Set ZSH_CACHE_DIR to the path where cache files should be created
# or else we will use the default cache/
if [[ -z "$ZSH_CACHE_DIR" ]]; then
ZSH_CACHE_DIR="$ZSH/cache"
fi
[[ -n "$ZSH_CACHE_DIR" ]] || ZSH_CACHE_DIR="$ZSH/cache"
# Make sure $ZSH_CACHE_DIR is writable, otherwise use a directory in $HOME
if [[ ! -w "$ZSH_CACHE_DIR" ]]; then
@ -54,7 +65,7 @@ fi
# Create cache and completions dir and add to $fpath
mkdir -p "$ZSH_CACHE_DIR/completions"
(( ${fpath[(Ie)"$ZSH_CACHE_DIR/completions"]} )) || fpath=("$ZSH_CACHE_DIR/completions" $fpath)
(( ${fpath[(Ie)$ZSH_CACHE_DIR/completions]} )) || fpath=("$ZSH_CACHE_DIR/completions" $fpath)
# Check for updates on initial load...
source "$ZSH/tools/check_for_upgrade.sh"
@ -62,17 +73,11 @@ source "$ZSH/tools/check_for_upgrade.sh"
# Initializes Oh My Zsh
# add a function path
fpath=("$ZSH/functions" "$ZSH/completions" $fpath)
fpath=($ZSH/{functions,completions} $ZSH_CUSTOM/{functions,completions} $fpath)
# Load all stock functions (from $fpath files) called below.
autoload -U compaudit compinit zrecompile
# Set ZSH_CUSTOM to the path where your custom config files
# and plugins exists, or else we will use the default custom/
if [[ -z "$ZSH_CUSTOM" ]]; then
ZSH_CUSTOM="$ZSH/custom"
fi
is_plugin() {
local base_dir=$1
local name=$2
@ -187,12 +192,12 @@ _omz_source() {
fi
}
# Load all of the config files in ~/oh-my-zsh that end in .zsh
# Load all of the lib files in ~/oh-my-zsh/lib that end in .zsh
# TIP: Add files you don't want in git to .gitignore
for config_file ("$ZSH"/lib/*.zsh); do
_omz_source "lib/${config_file:t}"
for lib_file ("$ZSH"/lib/*.zsh); do
_omz_source "lib/${lib_file:t}"
done
unset custom_config_file
unset lib_file
# Load all of the plugins that were defined in ~/.zshrc
for plugin ($plugins); do

View file

@ -1,9 +1,15 @@
# Do nothing if op is not installed
(( ${+commands[op]} )) || return
# Load op completion
eval "$(op completion zsh)"
compdef _op op
# If the completion file doesn't exist yet, we need to autoload it and
# bind it to `op`. Otherwise, compinit will have already done that.
if [[ ! -f "$ZSH_CACHE_DIR/completions/_op" ]]; then
typeset -g -A _comps
autoload -Uz _op
_comps[op]=_op
fi
op completion zsh >| "$ZSH_CACHE_DIR/completions/_op" &|
# Load opswd function
autoload -Uz opswd

View file

@ -27,7 +27,7 @@ function opswd() {
local password
# Copy the password to the clipboard
if ! password=$(op item get "$service" --fields password 2>/dev/null); then
if ! password=$(op item get "$service" --reveal --fields password 2>/dev/null); then
echo "error: could not obtain password for $service"
return 1
fi

View file

@ -1,8 +0,0 @@
# adb autocomplete plugin
* Adds autocomplete options for all adb commands.
* Add autocomplete for `adb -s`
## Requirements
In order to make this work, you will need to have the Android adb tools set up in your path.

View file

@ -1,67 +0,0 @@
#compdef adb
#autoload
# in order to make this work, you will need to have the android adb tools
# adb zsh completion, based on homebrew completion
local -a _1st_arguments
_1st_arguments=(
'bugreport:return all information from the device that should be included in a bug report.'
'connect:connect to a device via TCP/IP Port 5555 is default.'
'devices:list all connected devices'
'disconnect:disconnect from a TCP/IP device. Port 5555 is default.'
'emu:run emulator console command'
'forward:forward socket connections'
'get-devpath:print the device path'
'get-serialno:print the serial number of the device'
'get-state:print the current state of the device: offline | bootloader | device'
'help:show the help message'
'install:push this package file to the device and install it'
'jdwp:list PIDs of processes hosting a JDWP transport'
'keygen:generate adb public/private key'
'kill-server:kill the server if it is running'
'logcat:view device log'
'pull:copy file/dir from device'
'push:copy file/dir to device'
'reboot:reboots the device, optionally into the bootloader or recovery program'
'reboot-bootloader:reboots the device into the bootloader'
'remount:remounts the partitions on the device read-write'
'root:restarts the adbd daemon with root permissions'
'sideload:push a ZIP to device and install it'
'shell:run remote shell interactively'
'sync:copy host->device only if changed (-l means list but dont copy)'
'start-server:ensure that there is a server running'
'tcpip:restart host adb in tcpip mode'
'uninstall:remove this app package from the device'
'usb:restart the adbd daemon listing on USB'
'version:show version num'
'wait-for-device:block until device is online'
)
local expl
local -a pkgs installed_pkgs
_arguments \
'-s[devices]:specify device:->specify_device' \
'*:: :->subcmds' && return 0
case "$state" in
specify_device)
_values -C 'devices' ${$(adb devices -l|awk 'NR>1&& $1 \
{sub(/ +/," ",$0); \
gsub(":","\\:",$1); \
for(i=1;i<=NF;i++) {
if($i ~ /model:/) { split($i,m,":") } \
else if($i ~ /product:/) { split($i,p,":") } } \
printf "%s[%s(%s)] ",$1, p[2], m[2]}'):-""}
return
;;
esac
if (( CURRENT == 1 )); then
_describe -t commands "adb subcommand" _1st_arguments
return
fi
_files

View file

@ -1,13 +0,0 @@
# The Silver Searcher
This plugin provides completion support for [`ag`](https://github.com/ggreer/the_silver_searcher).
To use it, add ag to the plugins array in your zshrc file.
```zsh
plugins=(... ag)
```
## INSTALLATION NOTES
Besides oh-my-zsh, `ag` needs to be installed by following these steps: https://github.com/ggreer/the_silver_searcher#installing.

View file

@ -1,66 +0,0 @@
#compdef ag
#autoload
typeset -A opt_args
# Took the liberty of not listing every option… specially aliases and -D
_ag () {
local -a _1st_arguments
_1st_arguments=(
'--ackmate:Print results in AckMate-parseable format'
{'-A','--after'}':[LINES] Print lines after match (Default: 2)'
{'-B','--before'}':[LINES] Print lines before match (Default: 2)'
'--break:Print newlines between matches in different files'
'--nobreak:Do not print newlines between matches in different files'
{'-c','--count'}':Only print the number of matches in each file'
'--color:Print color codes in results (Default: On)'
'--nocolor:Do not print color codes in results'
'--color-line-number:Color codes for line numbers (Default: 1;33)'
'--color-match:Color codes for result match numbers (Default: 30;43)'
'--color-path:Color codes for path names (Default: 1;32)'
'--column:Print column numbers in results'
{'-H','--heading'}':Print file names (On unless searching a single file)'
'--noheading:Do not print file names (On unless searching a single file)'
'--line-numbers:Print line numbers even for streams'
{'-C','--context'}':[LINES] Print lines before and after matches (Default: 2)'
'-g:[PATTERN] Print filenames matching PATTERN'
{'-l','--files-with-matches'}':Only print filenames that contain matches'
{'-L','--files-without-matches'}':Only print filenames that do not contain matches'
'--no-numbers:Do not print line numbers'
{'-o','--only-matching'}':Prints only the matching part of the lines'
'--print-long-lines:Print matches on very long lines (Default: 2k characters)'
'--passthrough:When searching a stream, print all lines even if they do not match'
'--silent:Suppress all log messages, including errors'
'--stats:Print stats (files scanned, time taken, etc.)'
'--vimgrep:Print results like vim :vimgrep /pattern/g would'
{'-0','--null'}':Separate filenames with null (for "xargs -0")'
{'-a','--all-types'}':Search all files (does not include hidden files / .gitignore)'
'--depth:[NUM] Search up to NUM directories deep (Default: 25)'
{'-f','--follow'}':Follow symlinks'
{'-G','--file-search-regex'}':[PATTERN] Limit search to filenames matching PATTERN'
'--hidden:Search hidden files (obeys .*ignore files)'
{'-i','--ignore-case'}':Match case insensitively'
'--ignore:[PATTERN] Ignore files/directories matching PATTERN'
{'-m','--max-count'}':[NUM] Skip the rest of a file after NUM matches (Default: 10k)'
{'-p','--path-to-agignore'}':[PATH] Use .agignore file at PATH'
{'-Q','--literal'}':Do not parse PATTERN as a regular expression'
{'-s','--case-sensitive'}':Match case'
{'-S','--smart-case'}':Insensitive match unless PATTERN has uppercase (Default: On)'
'--search-binary:Search binary files for matches'
{'-t','--all-text'}':Search all text files (Hidden files not included)'
{'-u','--unrestricted'}':Search all files (ignore .agignore and _all_)'
{'-U','--skip-vcs-ignores'}':Ignore VCS files (stil obey .agignore)'
{'-v','--invert-match'}':Invert match'
{'-w','--word-regexp'}':Only match whole words'
{'-z','--search-zip'}':Search contents of compressed (e.g., gzip) files'
'--list-file-types:list of supported file types'
)
if [[ $words[-1] =~ "^-" ]]; then
_describe -t commands "ag options" _1st_arguments && ret=0
else
_files && ret=0
fi
}

View file

@ -0,0 +1,9 @@
tap: false
directories:
tests: tests
output: tests/_output
support: tests/_support
time_limit: 0
fail_fast: false
allow_risky: false
verbose: true

View file

@ -2,45 +2,67 @@
This plugin searches the defined aliases and outputs any that match the command inputted. This makes learning new aliases easier.
## Setup
To use it, add `alias-finder` to the `plugins` array of your zshrc file:
```
plugins=(... alias-finder)
```
To enable it for every single command, set zstyle in your `~/.zshrc`.
```zsh
# ~/.zshrc
zstyle ':omz:plugins:alias-finder' autoload yes # disabled by default
zstyle ':omz:plugins:alias-finder' longer yes # disabled by default
zstyle ':omz:plugins:alias-finder' exact yes # disabled by default
zstyle ':omz:plugins:alias-finder' cheaper yes # disabled by default
```
As you can see, options are also available with zstyle.
## Usage
To see if there is an alias defined for the command, pass it as an argument to `alias-finder`. This can also run automatically before each command you input - add `ZSH_ALIAS_FINDER_AUTOMATIC=true` to your zshrc if you want this.
## Options
When you execute a command alias finder will look at your defined aliases and suggest shorter aliases you could have used, for example:
- Use `--longer` or `-l` to allow the aliases to be longer than the input (match aliases if they contain the input).
- Use `--exact` or `-e` to avoid matching aliases that are shorter than the input.
Running the un-aliased `git status` command:
```sh
╭─tim@fox ~/repo/gitopolis main
╰─$ git status
## Examples
gst='git status' # <=== shorter suggestion from alias-finder
On branch main
Your branch is up-to-date with 'origin/main'.
nothing to commit, working tree clean
```
$ alias-finder "git pull"
gl='git pull'
g=git
Running a shorter `git st` alias from `.gitconfig` that it suggested :
```sh
╭─tim@fox ~/repo/gitopolis main
╰─$ git st
gs='git st' # <=== shorter suggestion from alias-finder
## main...origin/main
```
Running the shortest `gs` shell alias that it found:
```sh
╭─tim@fox ~/repo/gitopolis main
╰─$ gs
# <=== no suggestions alias-finder because this is the shortest
## main...origin/main
```
$ alias-finder "web_search google oh my zsh"
google='web_search google'
```
```
$ alias-finder "git commit -v"
gc="git commit -v"
g=git
```
```
$ alias-finder -e "git commit -v"
gc='git commit -v'
```
```
$ alias-finder -l "git commit -v"
gc='git commit -v'
'gc!'='git commit -v --amend'
gca='git commit -v -a'
'gca!'='git commit -v -a --amend'
'gcan!'='git commit -v -a --no-edit --amend'
'gcans!'='git commit -v -a -s --no-edit --amend'
'gcn!'='git commit -v --no-edit --amend'
```
![image](https://github.com/ohmyzsh/ohmyzsh/assets/19378/39642750-fb10-4f1a-b7f9-f36789eeb01b)
### Options
> In order to clarify, let's say `alias a=abc` has source 'abc' and destination 'a'.
- Use `--longer` or `-l` to include aliases where the source is longer than the input (in other words, the source could contain the whole input).
- Use `--exact` or `-e` to avoid aliases where the source is shorter than the input (in other words, the source must be the same with the input).
- Use `--cheaper` or `-c` to avoid aliases where the destination is longer than the input (in other words, the destination must be the shorter than the input).

View file

@ -1,44 +1,59 @@
alias-finder() {
local cmd="" exact="" longer="" wordStart="" wordEnd="" multiWordEnd=""
for i in $@; do
case $i in
local cmd=" " exact="" longer="" cheaper="" wordEnd="'{0,1}$" finder="" filter=""
# build command and options
for c in "$@"; do
case $c in
# TODO: Remove backward compatibility (other than zstyle form)
# set options if exist
-e|--exact) exact=true;;
-l|--longer) longer=true;;
*)
if [[ -z $cmd ]]; then
cmd=$i
else
cmd="$cmd $i"
fi
;;
-c|--cheaper) cheaper=true;;
# concatenate cmd
*) cmd="$cmd$c " ;;
esac
done
cmd=$(sed 's/[].\|$(){}?+*^[]/\\&/g' <<< $cmd) # adds escaping for grep
if (( $(wc -l <<< $cmd) == 1 )); then
zstyle -t ':omz:plugins:alias-finder' longer && longer=true
zstyle -t ':omz:plugins:alias-finder' exact && exact=true
zstyle -t ':omz:plugins:alias-finder' cheaper && cheaper=true
# format cmd for grep
## - replace newlines with spaces
## - trim both ends
## - replace multiple spaces with one space
## - add escaping character to special characters
cmd=$(echo -n "$cmd" | tr '\n' ' ' | xargs | tr -s '[:space:]' | sed 's/[].\|$(){}?+*^[]/\\&/g')
if [[ $longer == true ]]; then
wordEnd="" # remove wordEnd to find longer aliases
fi
# find with alias and grep, removing last word each time until no more words
while [[ $cmd != "" ]]; do
if [[ $longer = true ]]; then
wordStart="'{0,1}"
else
wordEnd="$"
multiWordEnd="'$"
finder="'{0,1}$cmd$wordEnd"
# make filter to find only shorter results than current cmd
if [[ $cheaper == true ]]; then
cmdLen=$(echo -n "$cmd" | wc -c)
filter="^'{0,1}.{0,$((cmdLen - 1))}="
fi
if [[ $cmd == *" "* ]]; then
local finder="'$cmd$multiWordEnd"
else
local finder=$wordStart$cmd$wordEnd
fi
alias | grep -E "=$finder"
if [[ $exact = true || $longer = true ]]; then
break
else
cmd=$(sed -E 's/ {0,1}[^ ]*$//' <<< $cmd) # removes last word
alias | grep -E "$filter" | grep -E "=$finder"
if [[ $exact == true ]]; then
break # because exact case is only one
elif [[ $longer = true ]]; then
break # because above grep command already found every longer aliases during first cycle
fi
cmd=$(sed -E 's/ {0,}[^ ]*$//' <<< "$cmd") # remove last word
done
fi
}
preexec_alias-finder() {
if [[ $ZSH_ALIAS_FINDER_AUTOMATIC = true ]]; then
# TODO: Remove backward compatibility (other than zstyle form)
zstyle -t ':omz:plugins:alias-finder' autoload && alias-finder $1 || if [[ $ZSH_ALIAS_FINDER_AUTOMATIC = true ]]; then
alias-finder $1
fi
}

View file

@ -0,0 +1,2 @@
#!/usr/bin/env zsh
# Write your bootstrap code here

View file

@ -0,0 +1,107 @@
#!/usr/bin/env zunit
@setup {
load ../alias-finder.plugin.zsh
set_git_aliases() {
unalias -a # all
alias g="git"
alias gc="git commit"
alias gcv="git commit -v"
alias gcvs="git commit -v -S"
}
}
@test 'find aliases that contain input' {
set_git_aliases
run alias-finder "git"
assert "${#lines[@]}" equals 1
assert "${lines[1]}" same_as "g=git"
}
@test 'find aliases that contain input with whitespaces at ends' {
set_git_aliases
run alias-finder " git "
assert "${#lines[@]}" equals 1
assert "${lines[1]}" same_as "g=git"
}
@test 'find aliases that contain multiple words' {
set_git_aliases
run alias-finder "git commit -v"
assert "${#lines[@]}" equals 3
assert "${lines[1]}" same_as "gcv='git commit -v'"
assert "${lines[2]}" same_as "gc='git commit'"
assert "${lines[3]}" same_as "g=git"
}
@test 'find alias that is the same with input when --exact option is set' {
set_git_aliases
run alias-finder -e "git"
assert "${#lines[@]}" equals 1
assert "${lines[1]}" same_as "g=git"
}
@test 'find alias that is the same with multiple words input when --exact option is set' {
set_git_aliases
run alias-finder -e "git commit -v"
assert "${#lines[@]}" equals 1
assert "${lines[1]}" same_as "gcv='git commit -v'"
}
@test 'find alias that is the same with or longer than input when --longer option is set' {
set_git_aliases
run alias-finder -l "git"
assert "${#lines[@]}" equals 4
assert "${lines[1]}" same_as "g=git"
assert "${lines[2]}" same_as "gc='git commit'"
assert "${lines[3]}" same_as "gcv='git commit -v'"
assert "${lines[4]}" same_as "gcvs='git commit -v -S'"
}
@test 'find alias that is the same with or longer than multiple words input when --longer option is set' {
set_git_aliases
run alias-finder -l "git commit -v"
assert "${#lines[@]}" equals 2
assert "${lines[1]}" same_as "gcv='git commit -v'"
assert "${lines[2]}" same_as "gcvs='git commit -v -S'"
}
@test 'find aliases including expensive (longer) than input' {
set_git_aliases
alias expensiveCommands="git commit"
run alias-finder "git commit -v"
assert "${#lines[@]}" equals 4
assert "${lines[1]}" same_as "gcv='git commit -v'"
assert "${lines[2]}" same_as "expensiveCommands='git commit'"
assert "${lines[3]}" same_as "gc='git commit'"
assert "${lines[4]}" same_as "g=git"
}
@test 'find aliases excluding expensive (longer) than input when --cheap option is set' {
set_git_aliases
alias expensiveCommands="git commit"
run alias-finder -c "git commit -v"
assert "${#lines[@]}" equals 3
assert "${lines[1]}" same_as "gcv='git commit -v'"
assert "${lines[2]}" same_as "gc='git commit'"
assert "${lines[3]}" same_as "g=git"
}

View file

@ -1,7 +1,5 @@
# Aliases cheatsheet
**Maintainer:** [@hqingyi](https://github.com/hqingyi)
With lots of 3rd-party amazing aliases installed, this plugin helps list the shortcuts
that are currently available based on the plugins you have enabled.
@ -13,11 +11,13 @@ plugins=(aliases)
Requirements: Python needs to be installed.
**Maintainer:** [@hqingyi](https://github.com/hqingyi)
## Usage
- `als`: show all aliases by group
- `als -h/--help`: print help mesage
- `als -h/--help`: print help message
- `als <keyword(s)>`: filter and highlight aliases by `<keyword>`
@ -25,4 +25,4 @@ Requirements: Python needs to be installed.
- `als --groups`: show only group names
![screenshot](https://cloud.githubusercontent.com/assets/3602957/11581913/cb54fb8a-9a82-11e5-846b-5a67f67ad9ad.png)
![screenshot](https://github.com/ohmyzsh/ohmyzsh/assets/66907184/5bfa00ea-5fc3-4e97-8b22-2f74f6b948c7)

View file

@ -1,7 +1,5 @@
# ansible plugin
## Introduction
The `ansible plugin` adds several aliases for useful [ansible](https://docs.ansible.com/ansible/latest/index.html) commands and [aliases](#aliases).
To use it, add `ansible` to the plugins array of your zshrc file:
@ -21,7 +19,6 @@ plugins=(... ansible)
| `acon` | command `ansible-console` |
| `ainv` | command `ansible-inventory` |
| `aplaybook` | command `ansible-playbook` |
| `ainv` | command `ansible-inventory` |
| `adoc` | command `ansible-doc` |
| `agal` | command `ansible-galaxy` |
| `apull` | command `ansible-pull` |

View file

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

View file

@ -0,0 +1,9 @@
# Arduino CLI plugin
This plugin adds completion for the [arduino-cli](https://github.com/arduino/arduino-cli) tool.
To use it, add `arduino-cli` to the plugins array in your zshrc file:
```zsh
plugins=(... arduino-cli)
```

View file

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

View file

@ -1,7 +1,5 @@
## asdf
**Maintainer:** [@RobLoach](https://github.com/RobLoach)
Adds integration with [asdf](https://github.com/asdf-vm/asdf), the extendable version manager, with support for Ruby, Node.js, Elixir, Erlang and more.
### Installation
@ -28,3 +26,7 @@ asdf install nodejs latest
asdf global nodejs latest
asdf local nodejs latest
```
### Maintainer
- [@RobLoach](https://github.com/RobLoach)

View file

@ -2,26 +2,29 @@
ASDF_DIR="${ASDF_DIR:-$HOME/.asdf}"
ASDF_COMPLETIONS="$ASDF_DIR/completions"
# If not found, check for archlinux/AUR package (/opt/asdf-vm/)
if [[ ! -f "$ASDF_DIR/asdf.sh" || ! -f "$ASDF_COMPLETIONS/asdf.bash" ]] && [[ -f "/opt/asdf-vm/asdf.sh" ]]; then
if [[ ! -f "$ASDF_DIR/asdf.sh" || ! -f "$ASDF_COMPLETIONS/_asdf" ]]; then
# If not found, check for archlinux/AUR package (/opt/asdf-vm/)
if [[ -f "/opt/asdf-vm/asdf.sh" ]]; then
ASDF_DIR="/opt/asdf-vm"
ASDF_COMPLETIONS="$ASDF_DIR"
fi
# If not found, check for Homebrew package
if [[ ! -f "$ASDF_DIR/asdf.sh" || ! -f "$ASDF_COMPLETIONS/asdf.bash" ]] && (( $+commands[brew] )); then
brew_prefix="$(brew --prefix asdf)"
ASDF_DIR="${brew_prefix}/libexec"
ASDF_COMPLETIONS="${brew_prefix}/etc/bash_completion.d"
unset brew_prefix
# If not found, check for Homebrew package
elif (( $+commands[brew] )); then
_ASDF_PREFIX="$(brew --prefix asdf)"
ASDF_DIR="${_ASDF_PREFIX}/libexec"
ASDF_COMPLETIONS="${_ASDF_PREFIX}/share/zsh/site-functions"
unset _ASDF_PREFIX
else
return
fi
fi
# Load command
if [[ -f "$ASDF_DIR/asdf.sh" ]]; then
. "$ASDF_DIR/asdf.sh"
source "$ASDF_DIR/asdf.sh"
# Load completions
if [[ -f "$ASDF_COMPLETIONS/asdf.bash" ]]; then
. "$ASDF_COMPLETIONS/asdf.bash"
if [[ -f "$ASDF_COMPLETIONS/_asdf" ]]; then
fpath+=("$ASDF_COMPLETIONS")
autoload -Uz _asdf
compdef _asdf asdf # compdef is already loaded before loading plugins
fi
fi

View file

@ -4,7 +4,9 @@ autojump_paths=(
$HOME/.autojump/share/autojump/autojump.zsh # manual installation
$HOME/.nix-profile/etc/profile.d/autojump.sh # NixOS installation
/run/current-system/sw/share/autojump/autojump.zsh # NixOS installation
/etc/profiles/per-user/$USER/share/autojump/autojump.zsh # Home Manager, NixOS with user-scoped packages
/usr/share/autojump/autojump.zsh # Debian and Ubuntu package
$PREFIX/share/autojump/autojump.zsh # Termux package
/etc/profile.d/autojump.zsh # manual installation
/etc/profile.d/autojump.sh # Gentoo installation
/usr/local/share/autojump/autojump.zsh # FreeBSD installation
@ -12,7 +14,9 @@ autojump_paths=(
/opt/local/etc/profile.d/autojump.sh # macOS with MacPorts
/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/pkg/share/autojump/autojump.zsh # macOS with pkgsrc
/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

View file

@ -16,6 +16,8 @@ plugins=(... aws)
It also sets `$AWS_EB_PROFILE` to `<profile>` for the Elastic Beanstalk CLI. It sets `$AWS_PROFILE_REGION` for display in `aws_prompt_info`.
Run `asp` without arguments to clear the profile.
* `asp [<profile>] login`: If AWS SSO has been configured in your aws profile, it will run the `aws sso login` command following profile selection.
* `asp [<profile>] login [<sso_session>]`: In addition to `asp [<profile>] login`, if SSO session has been configured in your aws profile, it will run the `aws sso login --sso-session <sso_session>` command following profile selection.
* `asp [<profile>] logout`: If AWS SSO has been configured in your aws profile, it will run the `aws sso logout` command following profile selection.
* `asr [<region>]`: sets `$AWS_REGION` and `$AWS_DEFAULT_REGION` (legacy) to `<region>`.
Run `asr` without arguments to clear the profile.
@ -45,6 +47,11 @@ plugins=(... aws)
Some themes might overwrite the value of RPROMPT instead of appending to it, so they'll need to be fixed to
see the AWS profile/region prompt.
* Set `AWS_PROFILE_STATE_ENABLED=true` in your zshrc file if you want the aws profile to persist between shell sessions.
This option might slow down your shell startup time.
By default the state file path is `/tmp/.aws_current_profile`. This means that the state won't survive a reboot or otherwise GC.
You can control the state file path using the `AWS_STATE_FILE` environment variable.
## Theme
The plugin creates an `aws_prompt_info` function that you can use in your theme, which displays

View file

@ -6,10 +6,26 @@ function agr() {
echo $AWS_REGION
}
# Update state file if enabled
function _aws_update_state() {
if [[ "$AWS_PROFILE_STATE_ENABLED" == true ]]; then
test -d $(dirname ${AWS_STATE_FILE}) || exit 1
echo "${AWS_PROFILE} ${AWS_REGION}" > "${AWS_STATE_FILE}"
fi
}
function _aws_clear_state() {
if [[ "$AWS_PROFILE_STATE_ENABLED" == true ]]; then
test -d $(dirname ${AWS_STATE_FILE}) || exit 1
echo -n > "${AWS_STATE_FILE}"
fi
}
# AWS profile selection
function asp() {
if [[ -z "$1" ]]; then
unset AWS_DEFAULT_PROFILE AWS_PROFILE AWS_EB_PROFILE AWS_PROFILE_REGION
_aws_clear_state
echo AWS profile cleared.
return
fi
@ -28,15 +44,24 @@ function asp() {
export AWS_PROFILE_REGION=$(aws configure get region)
_aws_update_state
if [[ "$2" == "login" ]]; then
if [[ -n "$3" ]]; then
aws sso login --sso-session $3
else
aws sso login
fi
elif [[ "$2" == "logout" ]]; then
aws sso logout
fi
}
# AWS region selection
function asr() {
if [[ -z "$1" ]]; then
unset AWS_DEFAULT_REGION AWS_REGION
_aws_update_state
echo AWS region cleared.
return
fi
@ -50,6 +75,7 @@ function asr() {
export AWS_REGION=$1
export AWS_DEFAULT_REGION=$1
_aws_update_state
}
# AWS profile switch
@ -196,8 +222,17 @@ function aws_change_access_key() {
}
function aws_regions() {
local region
if [[ $AWS_DEFAULT_REGION ]];then
region="$AWS_DEFAULT_REGION"
elif [[ $AWS_REGION ]];then
region="$AWS_REGION"
else
region="us-west-1"
fi
if [[ $AWS_DEFAULT_PROFILE || $AWS_PROFILE ]];then
aws ec2 describe-regions |grep RegionName | awk -F ':' '{gsub(/"/, "", $2);gsub(/,/, "", $2);gsub(/ /, "", $2); print $2}'
aws ec2 describe-regions --region $region |grep RegionName | awk -F ':' '{gsub(/"/, "", $2);gsub(/,/, "", $2);gsub(/ /, "", $2); print $2}'
else
echo "You must specify a AWS profile."
fi
@ -240,6 +275,22 @@ if [[ "$SHOW_AWS_PROMPT" != false && "$RPROMPT" != *'$(aws_prompt_info)'* ]]; th
RPROMPT='$(aws_prompt_info)'"$RPROMPT"
fi
if [[ "$AWS_PROFILE_STATE_ENABLED" == true ]]; then
AWS_STATE_FILE="${AWS_STATE_FILE:-/tmp/.aws_current_profile}"
test -s "${AWS_STATE_FILE}" || return
aws_state=($(cat $AWS_STATE_FILE))
export AWS_DEFAULT_PROFILE="${aws_state[1]}"
export AWS_PROFILE="$AWS_DEFAULT_PROFILE"
export AWS_EB_PROFILE="$AWS_DEFAULT_PROFILE"
test -z "${aws_state[2]}" && AWS_REGION=$(aws configure get region)
export AWS_REGION=${AWS_REGION:-$aws_state[2]}
export AWS_DEFAULT_REGION="$AWS_REGION"
fi
# Load awscli completions
# AWS CLI v2 comes with its own autocompletion. Check if that is there, otherwise fall back

View file

@ -12,6 +12,13 @@ Then, add the `battery_pct_prompt` function to your custom theme. For example:
RPROMPT='$(battery_pct_prompt) ...'
```
Also, you set the `BATTERY_CHARGING` variable to your favor.
For example:
```zsh
BATTERY_CHARGING="⚡️"
```
## Requirements
- On Linux, you must have the `acpi` or `acpitool` commands installed on your operating system.

View file

@ -13,6 +13,10 @@
# Author: Avneet Singh (kalsi-avneet) #
# Modified to add support for Android #
###########################################
# Author: Not Pua (im-notpua) #
# Modified to add support for OpenBSD #
###########################################
if [[ "$OSTYPE" = darwin* ]]; then
function battery_is_charging() {
@ -54,7 +58,7 @@ if [[ "$OSTYPE" = darwin* ]]; then
fi
echo "%{$fg[$color]%}[${battery_pct}%%]%{$reset_color%}"
else
echo ""
echo "${BATTERY_CHARGING-⚡️}"
fi
}
@ -139,6 +143,46 @@ elif [[ "$OSTYPE" = linux-android ]] && (( ${+commands[termux-battery-status]} )
echo "%{$fg[$color]%}${battery_pct}%%%{$reset_color%}"
fi
}
elif [[ "$OSTYPE" = openbsd* ]]; then
function battery_is_charging() {
[[ $(apm -b) -eq 3 ]]
}
function battery_pct() {
apm -l
}
function battery_pct_remaining() {
if ! battery_is_charging; then
battery_pct
else
echo "External Power"
fi
}
function battery_time_remaining() {
local remaining_time
remaining_time=$(apm -m)
if [[ $remaining_time -ge 0 ]]; then
((hour = $remaining_time / 60 ))
((minute = $remaining_time % 60 ))
printf %02d:%02d $hour $minute
fi
}
function battery_pct_prompt() {
local battery_pct color
battery_pct=$(battery_pct_remaining)
if battery_is_charging; then
echo "∞"
else
if [[ $battery_pct -gt 50 ]]; then
color='green'
elif [[ $battery_pct -gt 20 ]]; then
color='yellow'
else
color='red'
fi
echo "%{$fg[$color]%}${battery_pct}%%%{$reset_color%}"
fi
}
elif [[ "$OSTYPE" = linux* ]]; then
function battery_is_charging() {
if (( $+commands[acpitool] )); then

View file

@ -1,7 +1,6 @@
# Bazel plugin
This plugin adds completion for [bazel](https://bazel.build), an open-source build and
test tool that scalably supports multi-language and multi-platform projects.
This plugin adds completion and aliases for [bazel](https://bazel.build), an open-source build and test tool that scalably supports multi-language and multi-platform projects.
To use it, add `bazel` to the plugins array in your zshrc file:
@ -12,3 +11,12 @@ plugins=(... bazel)
The plugin has a copy of [the completion script from the git repository][1].
[1]: https://github.com/bazelbuild/bazel/blob/master/scripts/zsh_completion/_bazel
## Aliases
| Alias | Command | Description |
| ------- | -------------------------------------- | ------------------------------------------------------ |
| bzb | `bazel build` | The `bazel build` command |
| bzt | `bazel test` | The `bazel test` command |
| bzr | `bazel run` | The `bazel run` command |
| bzq | `bazel query` | The `bazel query` command |

View file

@ -1,4 +1,4 @@
#compdef bazel
#compdef bazel bazelisk
# Copyright 2015 The Bazel Authors. All rights reserved.
#

View file

@ -0,0 +1,5 @@
# Aliases for bazel
alias bzb='bazel build'
alias bzt='bazel test'
alias bzr='bazel run'
alias bzq='bazel query'

View file

@ -47,7 +47,7 @@ case $state in
"random[Generate random intervals in a genome.]" \
"reldist[Calculate the distribution of relative distances b/w two files.]" \
"sample[Sample random records from file using reservoir sampling.]" \
"shuffle[Randomly redistrubute intervals in a genome.]" \
"shuffle[Randomly redistribute intervals in a genome.]" \
"slop[Adjust the size of intervals.]" \
"sort[Order the intervals in a file.]" \
"subtract[Remove intervals based on overlaps b/w two files.]" \

View file

@ -1,19 +1,19 @@
# bgnotify zsh plugin
cross-platform background notifications for long running commands! Supports OSX and Ubuntu linux.
cross-platform background notifications for long running commands! Supports OSX and Linux.
Standalone homepage: [t413/zsh-background-notify](https://github.com/t413/zsh-background-notify)
----------------------------------
---
## How to use!
## How to use
Just add bgnotify to your plugins list in your `.zshrc`
- On OS X you'll need [terminal-notifier](https://github.com/alloy/terminal-notifier)
* `brew install terminal-notifier` (or `gem install terminal-notifier`)
- On ubuntu you're already all set!
- On windows you can use [notifu](https://www.paralint.com/projects/notifu/) or the Cygwin Ports libnotify package
- On Linux, make sure you have `notify-send` or `kdialog` installed. If you're using Ubuntu you should already be all set!
- On Windows you can use [notifu](https://www.paralint.com/projects/notifu/) or the Cygwin Ports libnotify package
## Screenshots
@ -35,20 +35,30 @@ Just add bgnotify to your plugins list in your `.zshrc`
One can configure a few things:
- `bgnotify_bell` enabled or disables the terminal bell (default true)
- `bgnotify_threshold` sets the notification threshold time (default 6 seconds)
- `function bgnotify_formatted` lets you change the notification
- `function bgnotify_formatted` lets you change the notification. You can for instance customize the message and pass in an icon.
- `bgnotify_extraargs` appends extra args to notifier (e.g. `-e` for notify-send to create a transient notification)
Use these by adding a function definition before the your call to source. Example:
~~~ sh
```sh
bgnotify_bell=false ## disable terminal bell
bgnotify_threshold=4 ## set your own notification threshold
function bgnotify_formatted {
## $1=exit_status, $2=command, $3=elapsed_time
[ $1 -eq 0 ] && title="Holy Smokes Batman!" || title="Holy Graf Zeppelin!"
bgnotify "$title -- after $3 s" "$2";
# Humanly readable elapsed time
local elapsed="$(( $3 % 60 ))s"
(( $3 < 60 )) || elapsed="$((( $3 % 3600) / 60 ))m $elapsed"
(( $3 < 3600 )) || elapsed="$(( $3 / 3600 ))h $elapsed"
[ $1 -eq 0 ] && title="Holy Smokes Batman" || title="Holy Graf Zeppelin"
[ $1 -eq 0 ] && icon="$HOME/icons/success.png" || icon="$HOME/icons/fail.png"
bgnotify "$title - took ${elapsed}" "$2" "$icon"
}
plugins=(git bgnotify) ## add to plugins list
source $ZSH/oh-my-zsh.sh ## existing source call
~~~
```

View file

@ -21,13 +21,12 @@ function bgnotify_end {
local elapsed=$(( EPOCHSECONDS - bgnotify_timestamp ))
# check time elapsed
[[ $bgnotify_timestamp -gt 0 ]] || return
[[ $elapsed -ge $bgnotify_threshold ]] || return
[[ $bgnotify_timestamp -gt 0 ]] || return 0
[[ $elapsed -ge $bgnotify_threshold ]] || return 0
# check if Terminal app is not active
[[ $(bgnotify_appid) != "$bgnotify_termid" ]] || return
[[ $(bgnotify_appid) != "$bgnotify_termid" ]] || return 0
printf '\a' # beep sound
bgnotify_formatted "$exit_status" "$bgnotify_lastcmd" "$elapsed"
} always {
bgnotify_timestamp=0
@ -52,53 +51,89 @@ function bgnotify_formatted {
(( $3 < 60 )) || elapsed="$((( $3 % 3600) / 60 ))m $elapsed"
(( $3 < 3600 )) || elapsed="$(( $3 / 3600 ))h $elapsed"
if [[ $1 -eq 0 ]]; then
bgnotify "#win (took $elapsed)" "$2"
[[ $bgnotify_bell = true ]] && printf '\a' # beep sound
if [[ $exit_status -eq 0 ]]; then
bgnotify "#win (took $elapsed)" "$cmd"
else
bgnotify "#fail (took $elapsed)" "$2"
bgnotify "#fail (took $elapsed)" "$cmd"
fi
}
# for macOS, output is "app ID, window ID" (com.googlecode.iterm2, 116)
function bgnotify_appid {
if (( ${+commands[osascript]} )); then
osascript -e 'tell application (path to frontmost application as text) to get the {id, id of front window}' 2>/dev/null
elif (( ${+commands[xprop]} )); then
osascript -e "tell application id \"$(bgnotify_programid)\" to get the {id, frontmost, id of front window, visible of front window}" 2>/dev/null
elif [[ -n $WAYLAND_DISPLAY ]] && (( ${+commands[swaymsg]} )); then # wayland+sway
local app_id=$(bgnotify_find_sway_appid)
[[ -n "$app_id" ]] && echo "$app_id" || echo $EPOCHSECONDS
elif [[ -z $WAYLAND_DISPLAY ]] && [[ -n $DISPLAY ]] && (( ${+commands[xprop]} )); then
xprop -root _NET_ACTIVE_WINDOW 2>/dev/null | cut -d' ' -f5
else
echo $EPOCHSECONDS
fi
}
function bgnotify {
# $1: title, $2: message
if (( ${+commands[terminal-notifier]} )); then # macOS
local term_id="${bgnotify_termid%%,*}" # remove window id
if [[ -z "$term_id" ]]; then
case "$TERM_PROGRAM" in
iTerm.app) term_id='com.googlecode.iterm2' ;;
Apple_Terminal) term_id='com.apple.terminal' ;;
esac
fi
if [[ -z "$term_id" ]]; then
terminal-notifier -message "$2" -title "$1" &>/dev/null
function bgnotify_find_sway_appid {
# output is "app_id,container_id", for example "Alacritty,1694"
# see example swaymsg output: https://github.com/ohmyzsh/ohmyzsh/files/13463939/output.json
if (( ${+commands[jq]} )); then
swaymsg -t get_tree | jq '.. | select(.type?) | select(.focused==true) | {app_id, id} | join(",")'
else
terminal-notifier -message "$2" -title "$1" -activate "$term_id" -sender "$term_id" &>/dev/null
swaymsg -t get_tree | awk '
BEGIN { Id = ""; Appid = ""; FocusNesting = -1; Nesting = 0 }
{
# Enter a block
if ($0 ~ /.*{$/) Nesting++
# Exit a block. If Nesting is now less than FocusNesting, we have the data we are looking for
if ($0 ~ /^[[:blank:]]*}.*/) { Nesting--; if (FocusNesting > 0 && Nesting < FocusNesting) exit 0 }
# Save the Id, it is potentially what we are looking for
if ($0 ~ /^[[:blank:]]*"id": [0-9]*,?$/) { sub(/^[[:blank:]]*"id": /, ""); sub(/,$/, ""); Id = $0 }
# Save the Appid, it is potentially what we are looking for
if ($0 ~ /^[[:blank:]]*"app_id": ".*",?$/) { sub(/^[[:blank:]]*"app_id": "/, ""); sub(/",$/, ""); Appid = $0 }
# Window is focused, this nesting block contains the Id and Appid we want!
if ($0 ~ /^[[:blank:]]*"focused": true,?$/) { FocusNesting = Nesting }
}
END {
if (Appid != "" && Id != "" && FocusNesting != -1) print Appid "," Id
else print ""
}'
fi
}
function bgnotify_programid {
case "$TERM_PROGRAM" in
iTerm.app) echo 'com.googlecode.iterm2' ;;
Apple_Terminal) echo 'com.apple.terminal' ;;
esac
}
function bgnotify {
local title="$1"
local message="$2"
local icon="$3"
if (( ${+commands[terminal-notifier]} )); then # macOS
local term_id=$(bgnotify_programid)
terminal-notifier -message "$message" -title "$title" ${=icon:+-appIcon "$icon"} ${=term_id:+-activate "$term_id"} ${=bgnotify_extraargs:-} &>/dev/null
elif (( ${+commands[growlnotify]} )); then # macOS growl
growlnotify -m "$1" "$2"
elif (( ${+commands[notify-send]} )); then # GNOME
notify-send "$1" "$2"
growlnotify -m "$title" "$message" ${=bgnotify_extraargs:-}
elif (( ${+commands[notify-send]} )); then
notify-send "$title" "$message" ${=icon:+--icon "$icon"} ${=bgnotify_extraargs:-}
elif (( ${+commands[kdialog]} )); then # KDE
kdialog --title "$1" --passivepopup "$2" 5
kdialog --title "$title" --passivepopup "$message" 5 ${=bgnotify_extraargs:-}
elif (( ${+commands[notifu]} )); then # cygwin
notifu /m "$2" /p "$1"
notifu /m "$message" /p "$title" ${=icon:+/i "$icon"} ${=bgnotify_extraargs:-}
fi
}
## Defaults
# enable terminal bell on notify by default
bgnotify_bell=${bgnotify_bell:-true}
# notify if command took longer than 5s by default
bgnotify_threshold=${bgnotify_threshold:-5}

View file

@ -10,32 +10,53 @@ plugins=(... brew)
## Shellenv
If `brew` is not found in the PATH, this plugin will attempt to find it in common
locations, and execute `brew shellenv` to set the environment appropriately.
This plugin will also export `HOMEBREW_PREFIX="$(brew --prefix)"` if not previously
defined for convenience.
If `brew` is not found in the PATH, this plugin will attempt to find it in common locations, and execute
`brew shellenv` to set the environment appropriately. This plugin will also export
`HOMEBREW_PREFIX="$(brew --prefix)"` if not previously defined for convenience.
In case you installed `brew` in a non-common location, you can still set `BREW_LOCATION` variable pointing to
the `brew` binary before sourcing `oh-my-zsh.sh` and it'll set up the environment.
## Aliases
| Alias | Command | Description |
| -------- | --------------------------------------- | ------------------------------------------------------------------- |
| `bcubc` | `brew upgrade --cask && brew cleanup` | Update outdated casks, then run cleanup. |
| -------- | --------------------------------------- | --------------------------------------------------------------------- |
| `ba` | `brew autoremove` | Uninstall unnecessary formulae. |
| `bci` | `brew info --cask` | Display information about the given cask. |
| `bcin` | `brew install --cask` | Install the given cask. |
| `bcl` | `brew list --cask` | List installed casks. |
| `bcn` | `brew cleanup` | Run cleanup. |
| `bco` | `brew outdated --cask` | Report all outdated casks. |
| `bcrin` | `brew reinstall --cask` | Reinstall the given cask. |
| `bcubc` | `brew upgrade --cask && brew cleanup` | Upgrade outdated casks, then run cleanup. |
| `bcubo` | `brew update && brew outdated --cask` | Update Homebrew data, then list outdated casks. |
| `bcup` | `brew upgrade --cask` | Upgrade all outdated casks. |
| `bfu` | `brew upgrade --formula` | Upgrade only formulae (not casks). |
| `bi` | `brew install` | Install a formula. |
| `bl` | `brew list` | List all installed formulae. |
| `bo` | `brew outdated` | List installed formulae that have an updated version available. |
| `brewp` | `brew pin` | Pin a specified formula so that it's not upgraded. |
| `brews` | `brew list -1` | List installed formulae or the installed files for a given formula. |
| `brewsp` | `brew list --pinned` | List pinned formulae, or show the version of a given formula. |
| `bubc` | `brew upgrade && brew cleanup` | Upgrade outdated formulae and casks, then run cleanup. |
| `bugbc` | `brew upgrade --greedy && brew cleanup` | Upgrade outdated formulae and casks (greedy), then run cleanup. |
| `bsl` | `brew services list` | List all running services. |
| `bsoff` | `brew services stop` | Stop the service and unregister it from launching at login (or boot). |
| `bsoffa` | `bsoff --all` | Stop all started services. |
| `bson` | `brew services start` | Start the service and register it to launch at login (or boot). |
| `bsona` | `bson --all` | Start all stopped services. |
| `bsr` | `brew services run` | Run the service without registering to launch at login (or boot). |
| `bsra` | `bsr --all` | Run all stopped services. |
| `bu` | `brew update` | Update brew and all installed formulae. |
| `bubo` | `brew update && brew outdated` | Update Homebrew data, then list outdated formulae and casks. |
| `bubu` | `bubo && bubc` | Do the last two operations above. |
| `bfu` | `brew upgrade --formula` | Upgrade only formulas (not casks). |
| `bubu` | `bubo && bup` | Do the last two operations above. |
| `bugbc` | `brew upgrade --greedy && brew cleanup` | Upgrade outdated formulae and casks (greedy), then run cleanup. |
| `bup` | `brew upgrade` | Upgrade outdated, unpinned brews. |
| `buz` | `brew uninstall --zap` | Remove all files associated with a cask. |
## Completion
This plugin configures paths with Homebrew's completion functions automatically, so you don't need to do it manually. See: https://docs.brew.sh/Shell-Completion#configuring-completions-in-zsh.
This plugin configures paths with Homebrew's completion functions automatically, so you don't need to do it
manually. See: https://docs.brew.sh/Shell-Completion#configuring-completions-in-zsh.
With the release of Homebrew 1.0, they decided to bundle the zsh completion as part of the
brew installation, so we no longer ship it with the brew plugin; now it only has brew
aliases. If you find that brew completion no longer works, make sure you have your Homebrew
installation fully up to date.
With the release of Homebrew 1.0, they decided to bundle the zsh completion as part of the brew installation,
so we no longer ship it with the brew plugin; now it only has brew aliases. If you find that brew completion
no longer works, make sure you have your Homebrew installation fully up to date.

View file

@ -1,5 +1,10 @@
if (( ! $+commands[brew] )); then
if [[ -x /opt/homebrew/bin/brew ]]; then
if [[ -n "$BREW_LOCATION" ]]; then
if [[ ! -x "$BREW_LOCATION" ]]; then
echo "[oh-my-zsh] $BREW_LOCATION is not executable"
return
fi
elif [[ -x /opt/homebrew/bin/brew ]]; then
BREW_LOCATION="/opt/homebrew/bin/brew"
elif [[ -x /usr/local/bin/brew ]]; then
BREW_LOCATION="/usr/local/bin/brew"
@ -19,7 +24,7 @@ if (( ! $+commands[brew] )); then
fi
if [[ -z "$HOMEBREW_PREFIX" ]]; then
# Maintain compatability with potential custom user profiles, where we had
# Maintain compatibility with potential custom user profiles, where we had
# previously relied on always sourcing shellenv. OMZ plugins should not rely
# on this to be defined due to out of order processing.
export HOMEBREW_PREFIX="$(brew --prefix)"
@ -29,17 +34,35 @@ if [[ -d "$HOMEBREW_PREFIX/share/zsh/site-functions" ]]; then
fpath+=("$HOMEBREW_PREFIX/share/zsh/site-functions")
fi
alias ba='brew autoremove'
alias bci='brew info --cask'
alias bcin='brew install --cask'
alias bcl='brew list --cask'
alias bcn='brew cleanup'
alias bco='brew outdated --cask'
alias bcrin='brew reinstall --cask'
alias bcubc='brew upgrade --cask && brew cleanup'
alias bcubo='brew update && brew outdated --cask'
alias bcubc='brew upgrade --cask && brew cleanup'
alias bcup='brew upgrade --cask'
alias bfu='brew upgrade --formula'
alias bi='brew install'
alias bl='brew list'
alias bo='brew outdated'
alias brewp='brew pin'
alias brewsp='brew list --pinned'
alias bubc='brew upgrade && brew cleanup'
alias bugbc='brew upgrade --greedy && brew cleanup'
alias bsl='brew services list'
alias bsoff='brew services stop'
alias bsoffa='bsoff --all'
alias bson='brew services start'
alias bsona='bson --all'
alias bsr='brew services run'
alias bsra='bsr --all'
alias bu='brew update'
alias bubo='brew update && brew outdated'
alias bubu='bubo && bubc'
alias bubu='bubo && bup'
alias bubug='bubo && bugbc'
alias bfu='brew upgrade --formula'
alias bugbc='brew upgrade --greedy && brew cleanup'
alias bup='brew upgrade'
alias buz='brew uninstall --zap'
function brews() {

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

@ -0,0 +1,9 @@
# Buf plugin
This plugin adds completion for [Buf CLI](https://github.com/bufbuild/buf), a tool working with Protocol Buffers.
To use it, add `buf` to the plugins array in your zshrc file:
```zsh
plugins=(... buf)
```

View file

@ -0,0 +1,14 @@
# Autocompletion for the Buf CLI (buf).
if (( !$+commands[buf] )); then
return
fi
# If the completion file doesn't exist yet, we need to autoload it and
# bind it to `buf`. Otherwise, compinit will have already done that.
if [[ ! -f "$ZSH_CACHE_DIR/completions/_buf" ]]; then
typeset -g -A _comps
autoload -Uz _buf
_comps[buf]=_buf
fi
# Generate and load buf completion
buf completion zsh >! "$ZSH_CACHE_DIR/completions/_buf" &|

20
plugins/bun/README.md Normal file
View file

@ -0,0 +1,20 @@
# Bun Plugin
This plugin sets up completion for [Bun](https://bun.sh).
To use it, add `bun` to the plugins array in your zshrc file:
```zsh
plugins=(... bun)
```
This plugin does not add any aliases.
## Cache
This plugin caches the completion script and is automatically updated when the
plugin is loaded, which is usually when you start up a new terminal emulator.
The cache is stored at:
- `$ZSH_CACHE_DIR/completions/_bun_` completions script

View file

@ -0,0 +1,14 @@
# If Bun is not found, don't do the rest of the script
if (( ! $+commands[bun] )); then
return
fi
# If the completion file doesn't exist yet, we need to autoload it and
# bind it to `bun`. Otherwise, compinit will have already done that.
if [[ ! -f "$ZSH_CACHE_DIR/completions/_bun" ]]; then
typeset -g -A _comps
autoload -Uz _bun
_comps[bun]=_bun
fi
SHELL=zsh bun completions >| "$ZSH_CACHE_DIR/completions/_bun" &|

View file

@ -1,4 +1,4 @@
#compdef bundle
#compdef bundle bundler
local curcontext="$curcontext" state line _gems _opts ret=1

View file

@ -1,6 +1,7 @@
# catimg
Plugin for displaying images on the terminal using the the `catimg.sh` script provided by [posva](https://github.com/posva/catimg)
Plugin for displaying images on the terminal using the `catimg.sh` script provided by
[posva](https://github.com/posva/catimg)
To use it, add `catimg` to the plugins array in your zshrc file:
@ -10,7 +11,7 @@ plugins=(... catimg)
## Requirements
- `convert` (ImageMagick)
- `magick convert` (ImageMagick)
## Functions

View file

@ -9,9 +9,11 @@
function catimg() {
if [[ -x `which convert` ]]; then
zsh $ZSH/plugins/catimg/catimg.sh $@
if (( $+commands[magick] )); then
CONVERT_CMD="magick" zsh $ZSH/plugins/catimg/catimg.sh $@
elif (( $+commands[convert] )); then
CONVERT_CMD="convert" zsh $ZSH/plugins/catimg/catimg.sh $@
else
echo "catimg need convert (ImageMagick) to work)"
echo "catimg need magick/convert (ImageMagick) to work)"
fi
}

View file

@ -7,6 +7,10 @@
# GitHub: https://github.com/posva/catimg #
################################################################################
# this should come from outside, either `magick` or `convert`
# from imagemagick v7 and ahead `convert` is deprecated
: ${CONVERT_CMD:=convert}
function help() {
echo "Usage catimg [-h] [-w width] [-c char] img"
echo "By default char is \" \" and w is the terminal width"
@ -43,23 +47,23 @@ if [ ! "$WIDTH" ]; then
else
COLS=$(expr $WIDTH "/" $(echo -n "$CHAR" | wc -c))
fi
WIDTH=$(convert "$IMG" -print "%w\n" /dev/null)
WIDTH=$($CONVERT_CMD "$IMG" -print "%w\n" /dev/null)
if [ "$WIDTH" -gt "$COLS" ]; then
WIDTH=$COLS
fi
REMAP=""
if convert "$IMG" -resize $COLS\> +dither -remap $COLOR_FILE /dev/null ; then
if $CONVERT_CMD "$IMG" -resize $COLS\> +dither -remap $COLOR_FILE /dev/null ; then
REMAP="-remap $COLOR_FILE"
else
echo "The version of convert is too old, don't expect good results :(" >&2
#convert "$IMG" -colors 256 PNG8:tmp.png
#IMG="tmp.png"
# $CONVERT_CMD "$IMG" -colors 256 PNG8:tmp.png
# IMG="tmp.png"
fi
# Display the image
I=0
convert "$IMG" -resize $COLS\> +dither `echo $REMAP` txt:- 2>/dev/null |
$CONVERT_CMD "$IMG" -resize $COLS\> +dither `echo $REMAP` txt:- 2>/dev/null |
sed -e 's/.*none.*/NO NO NO/g' -e '1d;s/^.*(\(.*\)[,)].*$/\1/g;y/,/ /' |
while read R G B f; do
if [ ! "$R" = "NO" ]; then

11
plugins/chezmoi/README.md Normal file
View file

@ -0,0 +1,11 @@
# chezmoi Plugin
## Introduction
This `chezmoi` plugin sets up completion for [chezmoi](https://chezmoi.io).
To use it, add `chezmoi` to the plugins array of your zshrc file:
```bash
plugins=(... chezmoi)
```

View file

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

View file

@ -1,6 +1,6 @@
# chucknorris
Chuck Norris fortunes plugin for Oh My Zsh. Perfectly suitable as MOTD.
Fortunes plugin for Chuck Norris for Oh My Zsh. Perfectly suitable as MOTD.
To use it add `chucknorris` to the plugins array in you zshrc file.

View file

@ -36,6 +36,7 @@ function colored() {
# Prefer `less` whenever available, since we specifically configured
# environment for it.
environment+=( PAGER="${commands[less]:-$PAGER}" )
environment+=( GROFF_NO_SGR=1 )
# See ./nroff script.
if [[ "$OSTYPE" = solaris* ]]; then

View file

@ -42,12 +42,12 @@ colorize_cat() {
ZSH_COLORIZE_STYLE="emacs"
fi
# Use stdin if no arguments have been passed.
if [ $# -eq 0 ]; then
# Use stdin if stdin is not attached to a terminal.
if [ ! -t 0 ]; then
if [[ "$ZSH_COLORIZE_TOOL" == "pygmentize" ]]; then
pygmentize -O style="$ZSH_COLORIZE_STYLE" -g
else
chroma --style="$ZSH_COLORIZE_STYLE" --formatter="${ZSH_COLORIZE_CHROMA_FORMATTER:-terminal}"
chroma --style="$ZSH_COLORIZE_STYLE" --formatter="${ZSH_COLORIZE_CHROMA_FORMATTER:-terminal}" "$@"
fi
return $?
fi

View file

@ -30,5 +30,6 @@ It works out of the box with the command-not-found packages for:
- [NixOS](https://github.com/NixOS/nixpkgs/tree/master/nixos/modules/programs/command-not-found)
- [Termux](https://github.com/termux/command-not-found)
- [SUSE](https://www.unix.com/man-page/suse/1/command-not-found/)
- [Gentoo](https://github.com/AndrewAmmerlaan/command-not-found-gentoo/tree/main)
You can add support for other platforms by submitting a Pull Request.

View file

@ -3,9 +3,10 @@
for file (
# Arch Linux. Must have pkgfile installed: https://wiki.archlinux.org/index.php/Pkgfile#Command_not_found
/usr/share/doc/pkgfile/command-not-found.zsh
# macOS (M1 and classic Homebrew): https://github.com/Homebrew/homebrew-command-not-found
# Homebrew: https://github.com/Homebrew/homebrew-command-not-found
/opt/homebrew/Library/Taps/homebrew/homebrew-command-not-found/handler.sh
/usr/local/Homebrew/Library/Taps/homebrew/homebrew-command-not-found/handler.sh
/home/linuxbrew/.linuxbrew/Homebrew/Library/Taps/homebrew/homebrew-command-not-found/handler.sh
); do
if [[ -r "$file" ]]; then
source "$file"

View file

@ -0,0 +1,44 @@
# conda-env
The plugin displays information of the created virtual container of conda and allows background theming.
To use it, add `conda-env` to the plugins array of your zshrc file:
```
plugins=(... conda-env)
```
The plugin creates a `conda_prompt_info` function that you can use in your theme, which displays the
basename of the current `$CONDA_DEFAULT_ENV`.
You can use this prompt function in your themes, by adding it to the `PROMPT` or `RPROMPT` variables. See [Example](#example) for more information.
## Settings
It uses two variables to control how the information is shown:
- `ZSH_THEME_CONDA_PREFIX`: sets the prefix of the CONDA_DEFAULT_ENV.
Defaults to `[`.
- `ZSH_THEME_CONDA_SUFFIX`: sets the suffix of the CONDA_DEFAULT_ENV.
Defaults to `]`.
## Example
```sh
ZSH_THEME_CONDA_PREFIX='conda:%F{green}'
ZSH_THEME_CONDA_SUFFIX='%f'
RPROMPT='$(conda_prompt_info)'
```
## `CONDA_CHANGEPS1`
This plugin also automatically sets the `CONDA_CHANGEPS1` variable to `false` to avoid conda changing the prompt
automatically. This has the same effect as running `conda config --set changeps1 false`.
You can override this behavior by adding `unset CONDA_CHANGEPS1` in your `.zshrc` file, after Oh My Zsh has been
sourced.
References:
- https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#determining-your-current-environment
- https://conda.io/projects/conda/en/latest/user-guide/configuration/use-condarc.html#precedence

View file

@ -0,0 +1,9 @@
function conda_prompt_info(){
[[ -n ${CONDA_DEFAULT_ENV} ]] || return
echo "${ZSH_THEME_CONDA_PREFIX=[}${CONDA_DEFAULT_ENV:t:gs/%/%%}${ZSH_THEME_CONDA_SUFFIX=]}"
}
# Has the same effect as `conda config --set changeps1 false`
# - https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#determining-your-current-environment
# - https://conda.io/projects/conda/en/latest/user-guide/configuration/use-condarc.html#precedence
export CONDA_CHANGEPS1=false

37
plugins/conda/README.md Normal file
View file

@ -0,0 +1,37 @@
# conda plugin
The conda plugin provides [aliases](#aliases) for `conda`, usually installed via [anaconda](https://www.anaconda.com/) or [miniconda](https://docs.conda.io/en/latest/miniconda.html).
To use it, add `conda` to the plugins array in your zshrc file:
```zsh
plugins=(... conda)
```
## Aliases
| Alias | Command | Description |
| :------- | :-------------------------------------- | :------------------------------------------------------------------------------ |
| `cna` | `conda activate` | Activate the specified conda environment |
| `cnab` | `conda activate base` | Activate the base conda environment |
| `cncf` | `conda env create -f` | Create a new conda environment from a YAML file |
| `cncn` | `conda create -y -n` | Create a new conda environment with the given name |
| `cnconf` | `conda config` | View or modify conda configuration |
| `cncp` | `conda create -y -p` | Create a new conda environment with the given prefix |
| `cncr` | `conda create -n` | Create new virtual environment with given name |
| `cncss` | `conda config --show-source` | Show the locations of conda configuration sources |
| `cnde` | `conda deactivate` | Deactivate the current conda environment |
| `cnel` | `conda env list` | List all available conda environments |
| `cni` | `conda install` | Install given package |
| `cniy` | `conda install -y` | Install given package without confirmation |
| `cnl` | `conda list` | List installed packages in the current environment |
| `cnle` | `conda list --export` | Export the list of installed packages in the current environment |
| `cnles` | `conda list --explicit > spec-file.txt` | Export the list of installed packages in the current environment to a spec file |
| `cnr` | `conda remove` | Remove given package |
| `cnrn` | `conda remove -y -all -n` | Remove all packages in the specified environment |
| `cnrp` | `conda remove -y -all -p` | Remove all packages in the specified prefix |
| `cnry` | `conda remove -y` | Remove given package without confirmation |
| `cnsr` | `conda search` | Search conda repositories for package |
| `cnu` | `conda update` | Update conda package manager |
| `cnua` | `conda update --all` | Update all installed packages |
| `cnuc` | `conda update conda` | Update conda package manager |

View file

@ -0,0 +1,23 @@
alias cna='conda activate'
alias cnab='conda activate base'
alias cncf='conda env create -f'
alias cncn='conda create -y -n'
alias cnconf='conda config'
alias cncp='conda create -y -p'
alias cncr='conda create -n'
alias cncss='conda config --show-source'
alias cnde='conda deactivate'
alias cnel='conda env list'
alias cni='conda install'
alias cniy='conda install -y'
alias cnl='conda list'
alias cnle='conda list --export'
alias cnles='conda list --explicit > spec-file.txt'
alias cnr='conda remove'
alias cnrn='conda remove -y -all -n'
alias cnrp='conda remove -y -all -p'
alias cnry='conda remove -y'
alias cnsr='conda search'
alias cnu='conda update'
alias cnua='conda update --all'
alias cnuc='conda update conda'

View file

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

View file

@ -1,13 +1,11 @@
# dbt plugin
## Introduction
The `dbt plugin` adds several aliases for useful [dbt](https://docs.getdbt.com/) commands and
[aliases](#aliases).
To use it, add `dbt` to the plugins array of your zshrc file:
```
```zsh
plugins=(... dbt)
```
@ -26,4 +24,4 @@ plugins=(... dbt)
## Maintainer
### [msempere](https://github.com/msempere)
- [msempere](https://github.com/msempere)

View file

@ -13,7 +13,12 @@ plugins=(... debian)
- `$apt_pref`: use aptitude or apt if installed, fallback is apt-get.
- `$apt_upgr`: use upgrade or safe-upgrade (for aptitude).
Set `$apt_pref` and `$apt_upgr` to whatever command you want (before sourcing Oh My Zsh) to override this behavior.
Set **both** `$apt_pref` and `$apt_upgr` to whatever command you want (before sourcing Oh My Zsh) to override this behavior, e.g.:
```sh
apt_pref='apt'
apt_upgr='full-upgrade'
```
## Common Aliases

View file

@ -37,13 +37,13 @@ Say you opened these directories on the terminal:
3 ~
```
By pressing <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Left</kbd>, the current working directory or `$CWD` will be from `oh-my-zsh` to `Hacktoberfest`. Press it again and it will be at `Projects`.
By pressing <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Left</kbd>, the current working directory or `$PWD` will be from `oh-my-zsh` to `Hacktoberfest`. Press it again and it will be at `Projects`.
And by pressing <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Right</kbd>, the `$CWD` will be from `Projects` to `Hacktoberfest`. Press it again and it will be at `oh-my-zsh`.
And by pressing <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Right</kbd>, the `$PWD` will be from `Projects` to `Hacktoberfest`. Press it again and it will be at `oh-my-zsh`.
Here's a example history table with the same accessed directories like above:
| Current `$CWD` | Key press | New `$CWD` |
| Current `$PWD` | Key press | New `$PWD` |
| --------------- | ----------------------------------------------------- | --------------- |
| `oh-my-zsh` | <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Left</kbd> | `Hacktoberfest` |
| `Hacktoberfest` | <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Left</kbd> | `Projects` |
@ -53,7 +53,7 @@ Here's a example history table with the same accessed directories like above:
| `Hacktoberfest` | <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Right</kbd> | `oh-my-zsh` |
| `oh-my-zsh` | <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Right</kbd> | `~` |
Note the last traversal, when pressing <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Right</kbd> on a last known `$CWD`, it will change back to the first known `$CWD`, which in the example is `~`.
Note the last traversal, when pressing <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Right</kbd> on a last known `$PWD`, it will change back to the first known `$PWD`, which in the example is `~`.
Here's an asciinema cast demonstrating the example above:
@ -62,17 +62,21 @@ Here's an asciinema cast demonstrating the example above:
## Functions
| Function | Description |
| -------------------- | --------------------------------------------------------------------------------------------------------- |
| `insert-cycledleft` | Change `$CWD` to the previous known stack, binded on <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Left</kbd> |
| `insert-cycledright` | Change `$CWD` to the next known stack, binded on <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Right</kbd> |
| -------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `insert-cycledleft` | Change `$PWD` to the previous known stack, bound to <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Left</kbd> |
| `insert-cycledright` | Change `$PWD` to the next known stack, bound to <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Right</kbd> |
| `insert-cycledup` | Change `$PWD` to the parent folder, bound to <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Up</kbd> |
| `insert-cycleddown` | Change `$PWD` to the first alphabetical child folder, bound to <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Down</kbd> |
## Rebinding keys
You can bind these functions to other key sequences, as long as you know the bindkey sequence. For example, these commands bind to <kbd>Alt</kbd> + <kbd>Shift</kbd> + <kbd>Left</kbd> / <kbd>Right</kbd> in `xterm-256color`:
You can bind these functions to other key sequences, as long as you know the bindkey sequence. For example, these commands bind to <kbd>Alt</kbd> + <kbd>Shift</kbd> + <kbd>key</kbd> in `xterm-256color`:
```zsh
bindkey '^[[1;4D' insert-cycledleft
bindkey '^[[1;4C' insert-cycledright
bindkey "\e[1;4A" insert-cycledup
bindkey "\e[1;4B" insert-cycleddown
```
You can get the bindkey sequence by pressing <kbd>Ctrl</kbd> + <kbd>V</kbd>, then pressing the keyboard shortcut you want to use.

View file

@ -8,7 +8,16 @@
# pushd +N: start counting from left of `dirs' output
# pushd -N: start counting from right of `dirs' output
# Either switch to a directory from dirstack, using +N or -N syntax
# or switch to a directory by path, using `switch-to-dir -- <path>`
switch-to-dir () {
# If $1 is --, then treat $2 as a directory path
if [[ $1 == -- ]]; then
# We use `-q` because we don't want chpwd to run, we'll do it manually
[[ -d "$2" ]] && builtin pushd -q "$2" &>/dev/null
return $?
fi
setopt localoptions nopushdminus
[[ ${#dirstack} -eq 0 ]] && return 1
@ -22,10 +31,10 @@ switch-to-dir () {
}
insert-cycledleft () {
switch-to-dir +1 || return
switch-to-dir +1 || return $?
local fn
for fn (chpwd $chpwd_functions precmd $precmd_functions); do
for fn in chpwd $chpwd_functions precmd $precmd_functions; do
(( $+functions[$fn] )) && $fn
done
zle reset-prompt
@ -33,22 +42,46 @@ insert-cycledleft () {
zle -N insert-cycledleft
insert-cycledright () {
switch-to-dir -0 || return
switch-to-dir -0 || return $?
local fn
for fn (chpwd $chpwd_functions precmd $precmd_functions); do
for fn in chpwd $chpwd_functions precmd $precmd_functions; do
(( $+functions[$fn] )) && $fn
done
zle reset-prompt
}
zle -N insert-cycledright
insert-cycledup () {
switch-to-dir -- .. || return $?
local fn
for fn in chpwd $chpwd_functions precmd $precmd_functions; do
(( $+functions[$fn] )) && $fn
done
zle reset-prompt
}
zle -N insert-cycledup
insert-cycleddown () {
switch-to-dir -- "$(find . -mindepth 1 -maxdepth 1 -type d | sort -n | head -n 1)" || return $?
local fn
for fn in chpwd $chpwd_functions precmd $precmd_functions; do
(( $+functions[$fn] )) && $fn
done
zle reset-prompt
}
zle -N insert-cycleddown
# These sequences work for xterm, Apple Terminal.app, and probably others.
# Not for rxvt-unicode, but it doesn't seem differentiate Ctrl-Shift-Arrow
# from plain Shift-Arrow, at least by default.
#
# iTerm2 does not have these key combinations defined by default; you will need
# to add them under "Keys" in your profile if you want to use this. You can do
# this conveniently by loading the "xterm with Numeric Keypad" preset.
bindkey "\e[1;6D" insert-cycledleft
bindkey "\e[1;6C" insert-cycledright
bindkey "\e[1;6D" insert-cycledleft # Ctrl+Shift+Left
bindkey "\e[1;6C" insert-cycledright # Ctrl+Shift+Right
bindkey "\e[1;6A" insert-cycledup # Ctrl+Shift+Up
bindkey "\e[1;6B" insert-cycleddown # Ctrl+Shift+Down

View file

@ -7,10 +7,10 @@ _direnv_hook() {
trap - SIGINT;
}
typeset -ag precmd_functions;
if [[ -z ${precmd_functions[(r)_direnv_hook]} ]]; then
if [[ -z "${precmd_functions[(r)_direnv_hook]+1}" ]]; then
precmd_functions=( _direnv_hook ${precmd_functions[@]} )
fi
typeset -ag chpwd_functions;
if [[ -z ${chpwd_functions[(r)_direnv_hook]} ]]; then
if [[ -z "${chpwd_functions[(r)_direnv_hook]+1}" ]]; then
chpwd_functions=( _direnv_hook ${chpwd_functions[@]} )
fi

View file

@ -10,6 +10,9 @@ To use it, add `dnf` to the plugins array in your zshrc file:
plugins=(... dnf)
```
Classic `dnf` is getting superseded by `dnf5`; this plugin detects the presence
of `dnf5` and uses it as drop-in alternative to the slower `dnf`.
## Aliases
| Alias | Command | Description |

View file

@ -1,15 +1,19 @@
## Aliases
local dnfprog="dnf"
alias dnfl="dnf list" # List packages
alias dnfli="dnf list installed" # List installed packages
alias dnfgl="dnf grouplist" # List package groups
alias dnfmc="dnf makecache" # Generate metadata cache
alias dnfp="dnf info" # Show package information
alias dnfs="dnf search" # Search package
# Prefer dnf5 if installed
command -v dnf5 > /dev/null && dnfprog=dnf5
alias dnfu="sudo dnf upgrade" # Upgrade package
alias dnfi="sudo dnf install" # Install package
alias dnfgi="sudo dnf groupinstall" # Install package group
alias dnfr="sudo dnf remove" # Remove package
alias dnfgr="sudo dnf groupremove" # Remove package group
alias dnfc="sudo dnf clean all" # Clean cache
alias dnfl="${dnfprog} list" # List packages
alias dnfli="${dnfprog} list installed" # List installed packages
alias dnfgl="${dnfprog} grouplist" # List package groups
alias dnfmc="${dnfprog} makecache" # Generate metadata cache
alias dnfp="${dnfprog} info" # Show package information
alias dnfs="${dnfprog} search" # Search package
alias dnfu="sudo ${dnfprog} upgrade" # Upgrade package
alias dnfi="sudo ${dnfprog} install" # Install package
alias dnfgi="sudo ${dnfprog} groupinstall" # Install package group
alias dnfr="sudo ${dnfprog} remove" # Remove package
alias dnfgr="sudo ${dnfprog} groupremove" # Remove package group
alias dnfc="sudo ${dnfprog} clean all" # Clean cache

View file

@ -12,7 +12,7 @@ plugins=(... docker-compose)
## Aliases
| Alias | Command | Description |
|-----------|--------------------------------|----------------------------------------------------------------------------------|
|-----------|----------------------------------|----------------------------------------------------------------------------------|
| dco | `docker-compose` | Docker-compose main command |
| dcb | `docker-compose build` | Build containers |
| dce | `docker-compose exec` | Execute command inside a container |
@ -28,6 +28,7 @@ plugins=(... docker-compose)
| dcdn | `docker-compose down` | Stop and remove containers |
| dcl | `docker-compose logs` | Show logs of container |
| dclf | `docker-compose logs -f` | Show logs and follow output |
| dclF | `docker-compose logs -f --tail0` | Just follow recent logs |
| dcpull | `docker-compose pull` | Pull image of a service |
| dcstart | `docker-compose start` | Start a container |
| dck | `docker-compose kill` | Kills containers |

View file

@ -128,7 +128,7 @@ __docker-compose_subcommand() {
'--resolve-image-digests[Pin image tags to digests.]' \
'--services[Print the service names, one per line.]' \
'--volumes[Print the volume names, one per line.]' \
'--hash[Print the service config hash, one per line. Set "service1,service2" for a list of specified services.]' \ && ret=0
'--hash[Print the service config hash, one per line. Set "service1,service2" for a list of specified services.]' && ret=0
;;
(create)
_arguments \

View file

@ -1,5 +1,8 @@
# support Compose v2 as docker CLI plugin
(( ${+commands[docker-compose]} )) && dccmd='docker-compose' || dccmd='docker compose'
# Support Compose v2 as docker CLI plugin
#
# This tests that the (old) docker-compose command is in $PATH and that
# it resolves to an existing executable file if it's a symlink.
[[ -x "${commands[docker-compose]:A}" ]] && dccmd='docker-compose' || dccmd='docker compose'
alias dco="$dccmd"
alias dcb="$dccmd build"
@ -16,6 +19,7 @@ alias dcupdb="$dccmd up -d --build"
alias dcdn="$dccmd down"
alias dcl="$dccmd logs"
alias dclf="$dccmd logs -f"
alias dclF="$dccmd logs -f --tail 0"
alias dcpull="$dccmd pull"
alias dcstart="$dccmd start"
alias dck="$dccmd kill"

View file

@ -1,19 +0,0 @@
# docker-machine plugin for oh my zsh
### Usage
#### docker-vm
Will create a docker-machine with the name "dev" (required only once)
To create a second machine call "docker-vm foobar" or pass any other name
#### docker-up
This will start your "dev" docker-machine (if necessary) and set it as the active one
To start a named machine use "docker-up foobar"
#### docker-switch dev
Use this to activate a running docker-machine (or to switch between multiple machines)
You need to call either this or docker-up when opening a new terminal
#### docker-stop
This will stop your "dev" docker-machine
To stop a named machine use "docker-stop foobar"

View file

@ -1,359 +0,0 @@
#compdef docker-machine
# Description
# -----------
# zsh completion for docker-machine
# https://github.com/leonhartX/docker-machine-zsh-completion
# -------------------------------------------------------------------------
# Version
# -------
# 0.1.1
# -------------------------------------------------------------------------
# Authors
# -------
# * Ke Xu <leonhartx.k@gmail.com>
# -------------------------------------------------------------------------
# Inspiration
# -----------
# * @sdurrheimer docker-compose-zsh-completion https://github.com/sdurrheimer/docker-compose-zsh-completion
# * @ilkka _docker-machine
__docker-machine_get_hosts() {
[[ $PREFIX = -* ]] && return 1
local state
declare -a hosts
state=$1; shift
if [[ $state != all ]]; then
hosts=(${(f)"$(_call_program commands docker-machine ls -q --filter state=$state)"})
else
hosts=(${(f)"$(_call_program commands docker-machine ls -q)"})
fi
_describe 'host' hosts "$@" && ret=0
return ret
}
__docker-machine_hosts_with_state() {
declare -a hosts
hosts=(${(f)"$(_call_program commands docker-machine ls -f '{{.Name}}\:{{.DriverName}}\({{.State}}\)\ {{.URL}}')"})
_describe 'host' hosts
}
__docker-machine_hosts_all() {
__docker-machine_get_hosts all "$@"
}
__docker-machine_hosts_running() {
__docker-machine_get_hosts Running "$@"
}
__docker-machine_get_swarm() {
declare -a swarms
swarms=(${(f)"$(_call_program commands docker-machine ls -f {{.Swarm}} | awk '{print $1}')"})
_describe 'swarm' swarms
}
__docker-machine_hosts_and_files() {
_alternative "hosts:host:__docker-machine_hosts_all -qS ':'" 'files:files:_path_files'
}
__docker-machine_filters() {
[[ $PREFIX = -* ]] && return 1
integer ret=1
if compset -P '*='; then
case "${${words[-1]%=*}#*=}" in
(driver)
_describe -t driver-filter-opts "driver filter" opts_driver && ret=0
;;
(swarm)
__docker-machine_get_swarm && ret=0
;;
(state)
opts_state=('Running' 'Paused' 'Saved' 'Stopped' 'Stopping' 'Starting' 'Error')
_describe -t state-filter-opts "state filter" opts_state && ret=0
;;
(name)
__docker-machine_hosts_all && ret=0
;;
(label)
_message 'label' && ret=0
;;
*)
_message 'value' && ret=0
;;
esac
else
opts=('driver' 'swarm' 'state' 'name' 'label')
_describe -t filter-opts "filter" opts -qS "=" && ret=0
fi
return ret
}
__get_swarm_discovery() {
declare -a masters services
local service
services=()
masters=($(docker-machine ls -f {{.Swarm}} |grep '(master)' |awk '{print $1}'))
for master in $masters; do
service=${${${(f)"$(_call_program commands docker-machine inspect -f '{{.HostOptions.SwarmOptions.Discovery}}:{{.Name}}' $master)"}/:/\\:}}
services=($services $service)
done
_describe -t services "swarm service" services && ret=0
return ret
}
__get_create_argument() {
typeset -g docker_machine_driver
if [[ CURRENT -le 2 ]]; then
docker_machine_driver="none"
elif [[ CURRENT > 2 && $words[CURRENT-2] = '-d' || $words[CURRENT-2] = '--driver' ]]; then
docker_machine_driver=$words[CURRENT-1]
elif [[ $words[CURRENT-1] =~ '^(-d|--driver)=' ]]; then
docker_machine_driver=${${words[CURRENT-1]}/*=/}
fi
local driver_opt_cmd
local -a opts_provider opts_common opts_read_argument
opts_read_argument=(
": :->argument"
)
opts_common=(
$opts_help \
'(--driver -d)'{--driver=,-d=}'[Driver to create machine with]:dirver:->driver-option' \
'--engine-install-url=[Custom URL to use for engine installation]:url' \
'*--engine-opt=[Specify arbitrary flags to include with the created engine in the form flag=value]:flag' \
'*--engine-insecure-registry=[Specify insecure registries to allow with the created engine]:registry' \
'*--engine-registry-mirror=[Specify registry mirrors to use]:mirror' \
'*--engine-label=[Specify labels for the created engine]:label' \
'--engine-storage-driver=[Specify a storage driver to use with the engine]:storage-driver:->storage-driver-option' \
'*--engine-env=[Specify environment variables to set in the engine]:environment' \
'--swarm[Configure Machine with Swarm]' \
'--swarm-image=[Specify Docker image to use for Swarm]:image' \
'--swarm-master[Configure Machine to be a Swarm master]' \
'--swarm-discovery=[Discovery service to use with Swarm]:service:->swarm-service' \
'--swarm-strategy=[Define a default scheduling strategy for Swarm]:strategy:(spread binpack random)' \
'*--swarm-opt=[Define arbitrary flags for swarm]:flag' \
'*--swarm-join-opt=[Define arbitrary flags for Swarm join]:flag' \
'--swarm-host=[ip/socket to listen on for Swarm master]:host' \
'--swarm-addr=[addr to advertise for Swarm (default: detect and use the machine IP)]:address' \
'--swarm-experimental[Enable Swarm experimental features]' \
'*--tls-san=[Support extra SANs for TLS certs]:option'
)
driver_opt_cmd="docker-machine create -d $docker_machine_driver | grep $docker_machine_driver | sed -e 's/\(--.*\)\ *\[\1[^]]*\]/*\1/g' -e 's/\(\[[^]]*\)/\\\\\\1\\\\/g' -e 's/\".*\"\(.*\)/\1/g' | awk '{printf \"%s[\", \$1; for(i=2;i<=NF;i++) {printf \"%s \", \$i}; print \"]\"}'"
if [[ $docker_machine_driver != "none" ]]; then
opts_provider=(${(f)"$(_call_program commands $driver_opt_cmd)"})
_arguments \
$opts_provider \
$opts_read_argument \
$opts_common && ret=0
else
_arguments $opts_common && ret=0
fi
case $state in
(driver-option)
_describe -t driver-option "driver" opts_driver && ret=0
;;
(storage-driver-option)
_describe -t storage-driver-option "storage driver" opts_storage_driver && ret=0
;;
(swarm-service)
__get_swarm_discovery && ret=0
;;
(argument)
ret=0
;;
esac
return ret
}
__docker-machine_subcommand() {
local -a opts_help
opts_help=("(- :)--help[Print usage]")
local -a opts_only_host opts_driver opts_storage_driver opts_state
opts_only_host=(
"$opts_help"
"*:host:__docker-machine_hosts_all"
)
opts_driver=('amazonec2' 'azure' 'digitalocean' 'exoscale' 'generic' 'google' 'hyperv' 'none' 'openstack' 'rackspace' 'softlayer' 'virtualbox' 'vmwarefusion' 'vmwarevcloudair' 'vmwarevsphere')
opts_storage_driver=('overlay' 'aufs' 'btrfs' 'devicemapper' 'vfs' 'zfs')
integer ret=1
case "$words[1]" in
(active)
_arguments \
$opts_help \
'(--timeout -t)'{--timeout=,-t=}'[Timeout in seconds, default to 10s]:seconds' && ret=0
;;
(config)
_arguments \
$opts_help \
'--swarm[Display the Swarm config instead of the Docker daemon]' \
"*:host:__docker-machine_hosts_all" && ret=0
;;
(create)
__get_create_argument
;;
(env)
_arguments \
$opts_help \
'--swarm[Display the Swarm config instead of the Docker daemon]' \
'--shell=[Force environment to be configured for a specified shell: \[fish, cmd, powershell\], default is auto-detect]:shell' \
'(--unset -u)'{--unset,-u}'[Unset variables instead of setting them]' \
'--no-proxy[Add machine IP to NO_PROXY environment variable]' \
'*:host:__docker-machine_hosts_running' && ret=0
;;
(help)
_arguments ':subcommand:__docker-machine_commands' && ret=0
;;
(inspect)
_arguments \
$opts_help \
'(--format -f)'{--format=,-f=}'[Format the output using the given go template]:template' \
'*:host:__docker-machine_hosts_all' && ret=0
;;
(ip)
_arguments \
$opts_help \
'*:host:__docker-machine_hosts_running' && ret=0
;;
(kill)
_arguments \
$opts_help \
'*:host:__docker-machine_hosts_with_state' && ret=0
;;
(ls)
_arguments \
$opts_help \
'(--quiet -q)'{--quiet,-q}'[Enable quiet mode]' \
'*--filter=[Filter output based on conditions provided]:filter:->filter-options' \
'(--timeout -t)'{--timeout=,-t=}'[Timeout in seconds, default to 10s]:seconds' \
'(--format -f)'{--format=,-f=}'[Pretty-print machines using a Go template]:template' && ret=0
case $state in
(filter-options)
__docker-machine_filters && ret=0
;;
esac
;;
(provision)
_arguments $opts_only_host && ret=0
;;
(regenerate-certs)
_arguments \
$opts_help \
'(--force -f)'{--force,-f}'[Force rebuild and do not prompt]' \
'*:host:__docker-machine_hosts_all' && ret=0
;;
(restart)
_arguments \
$opts_help \
'*:host:__docker-machine_hosts_with_state' && ret=0
;;
(rm)
_arguments \
$opts_help \
'(--force -f)'{--force,-f}'[Remove local configuration even if machine cannot be removed, also implies an automatic yes (`-y`)]' \
'-y[Assumes automatic yes to proceed with remove, without prompting further user confirmation]' \
'*:host:__docker-machine_hosts_with_state' && ret=0
;;
(scp)
_arguments \
$opts_help \
'(--recursive -r)'{--recursive,-r}'[Copy files recursively (required to copy directories))]' \
'*:files:__docker-machine_hosts_and_files' && ret=0
;;
(ssh)
_arguments \
$opts_help \
'*:host:__docker-machine_hosts_running' && ret=0
;;
(start)
_arguments \
$opts_help \
'*:host:__docker-machine_hosts_with_state' && ret=0
;;
(status)
_arguments $opts_only_host && ret=0
;;
(stop)
_arguments \
$opts_help \
'*:host:__docker-machine_hosts_with_state' && ret=0
;;
(upgrade)
_arguments $opts_only_host && ret=0
;;
(url)
_arguments \
$opts_help \
'*:host:__docker-machine_hosts_running' && ret=0
;;
esac
return ret
}
__docker-machine_commands() {
local cache_policy
zstyle -s ":completion:${curcontext}:" cache-policy cache_policy
if [[ -z "$cache_policy" ]]; then
zstyle ":completion:${curcontext}:" cache-policy __docker-machine_caching_policy
fi
if ( [[ ${+_docker_machine_subcommands} -eq 0 ]] || _cache_invalid docker_machine_subcommands) \
&& ! _retrieve_cache docker_machine_subcommands;
then
local -a lines
lines=(${(f)"$(_call_program commands docker-machine 2>&1)"})
_docker_machine_subcommands=(${${${lines[$((${lines[(i)Commands:]} + 1)),${lines[(I) *]}]}## #}/$'\t'##/:})
(( $#_docker_machine_subcommands > 0 )) && _store_cache docker_machine_subcommands _docker_machine_subcommands
fi
_describe -t docker-machine-commands "docker-machine command" _docker_machine_subcommands
}
__docker-machine_caching_policy() {
oldp=( "$1"(Nmh+1) )
(( $#oldp ))
}
_docker-machine() {
if [[ $service != docker-machine ]]; then
_call_function - _$service
return
fi
local curcontext="$curcontext" state line
integer ret=1
typeset -A opt_args
_arguments -C \
"(- :)"{-h,--help}"[Show help]" \
"(-D --debug)"{-D,--debug}"[Enable debug mode]" \
'(-s --storage-path)'{-s,--storage-path}'[Configures storage path]:file:_files' \
'--tls-ca-cert[CA to verify remotes against]:file:_files' \
'--tls-ca-key[Private key to generate certificates]:file:_files' \
'--tls-client-cert[Client cert to use for TLS]:file:_files' \
'--tls-client-key[Private key used in client TLS auth]:file:_files' \
'--github-api-token[Token to use for requests to the GitHub API]' \
'--native-ssh[Use the native (Go-based) SSH implementation.]' \
'--bugsnag-api-token[Bugsnag API token for crash reporting]' \
'(- :)'{-v,--version}'[Print the version]' \
"(-): :->command" \
"(-)*:: :->option-or-argument" && ret=0
case $state in
(command)
__docker-machine_commands && ret=0
;;
(option-or-argument)
curcontext=${curcontext%:*:*}:docker-machine-$words[1]:
__docker-machine_subcommand && ret=0
ret=0
;;
esac
return ret
}
_docker-machine "$@"

View file

@ -1,33 +0,0 @@
DEFAULT_MACHINE="default"
docker-up() {
if [ -z "$1" ]
then
docker-machine start "${DEFAULT_MACHINE}"
eval $(docker-machine env "${DEFAULT_MACHINE}")
else
docker-machine start $1
eval $(docker-machine env $1)
fi
echo $DOCKER_HOST
}
docker-stop() {
if [ -z "$1" ]
then
docker-machine stop "${DEFAULT_MACHINE}"
else
docker-machine stop $1
fi
}
docker-switch() {
eval $(docker-machine env $1)
echo $DOCKER_HOST
}
docker-vm() {
if [ -z "$1" ]
then
docker-machine create -d virtualbox --virtualbox-disk-size 20000 --virtualbox-memory 4096 --virtualbox-cpu-count 2 "${DEFAULT_MACHINE}"
else
docker-machine create -d virtualbox --virtualbox-disk-size 20000 --virtualbox-memory 4096 --virtualbox-cpu-count 2 $1
fi
}

View file

@ -6,6 +6,7 @@ alias dib='docker image build'
alias dii='docker image inspect'
alias dils='docker image ls'
alias dipu='docker image push'
alias dipru='docker image prune -a'
alias dirm='docker image rm'
alias dit='docker image tag'
alias dkil='docker kill'
@ -18,6 +19,8 @@ alias dni='docker network inspect'
alias dnls='docker network ls'
alias dnrm='docker network rm'
alias dpo='docker container port'
alias dps='docker ps'
alias dpsa='docker ps -a'
alias dpu='docker pull'
alias dpsh='docker push'
alias dr='docker container run'
@ -54,7 +57,7 @@ if (( ! $+commands[docker] )); then
return
fi
# Standarized $0 handling
# Standardized $0 handling
# https://zdharma-continuum.github.io/Zsh-100-Commits-Club/Zsh-Plugin-Standard.html
0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}"
0="${${(M)0:#/*}:-$PWD/$0}"
@ -75,6 +78,6 @@ fi
! is-at-least 23.0.0 ${${(s:,:z)"$(command docker --version)"}[3]}; then
command cp "${0:h}/completions/_docker" "$ZSH_CACHE_DIR/completions/_docker"
else
command docker completion zsh >| "$ZSH_CACHE_DIR/completions/_docker"
command docker completion zsh | tee "$ZSH_CACHE_DIR/completions/_docker" > /dev/null
fi
} &|

View file

@ -1,22 +1,14 @@
# This scripts is copied from (MIT License):
# https://github.com/dotnet/toolset/blob/master/scripts/register-completions.zsh
# https://raw.githubusercontent.com/dotnet/sdk/main/scripts/register-completions.zsh
_dotnet_zsh_complete()
{
local completions=("$(dotnet complete "$words")")
# If the completion list is empty, just continue with filename selection
if [ -z "$completions" ]
then
_arguments '*::arguments: _normal'
return
fi
# This is not a variable assignment, don't remove spaces!
_values = "${(ps:\n:)completions}"
#compdef dotnet
_dotnet_completion() {
local -a completions=("${(@f)$(dotnet complete "${words}")}")
compadd -a completions
_files
}
compdef _dotnet_zsh_complete dotnet
compdef _dotnet_completion dotnet
# Aliases bellow are here for backwards compatibility
# added by Shaun Tabone (https://github.com/xontab)

View file

@ -27,4 +27,4 @@ The plugin uses a custom launcher (which we'll call here `$EMACS_LAUNCHER`) that
| eeval | `$EMACS_LAUNCHER --eval` | Same as `M-x eval` but from outside Emacs |
| eframe | `emacsclient --alternate-editor="" --create-frame` | Create new X frame |
| efile | - | Print the path to the file open in the current buffer |
| ecd | - | Print the directory of the file open in the the current buffer |
| ecd | - | Print the directory of the file open in the current buffer |

View file

@ -60,7 +60,7 @@ function efile {
}
# Write to standard output the directory of the file
# opened in the the current buffer
# opened in the current buffer
function ecd {
local file
file="$(efile)" || return $?

Some files were not shown because too many files have changed in this diff Show more