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

Merge branch 'ohmyzsh:master' into master

This commit is contained in:
Jorge Francisco Varela Gutiérrez 2023-12-31 10:46:51 -06:00 committed by GitHub
commit e6e7e187e1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
303 changed files with 8698 additions and 3215 deletions

3
.github/CODEOWNERS vendored
View file

@ -1,6 +1,5 @@
# Plugin owners
plugins/archlinux/ @ratijas
plugins/aws/ @maksyms
plugins/genpass/ @atoponce
plugins/git-lfs/ @hellovietduc
plugins/gitfast/ @felipec
@ -10,3 +9,5 @@ plugins/shell-proxy/ @septs
plugins/universalarchive/ @Konfekt
plugins/wp-cli/ @joshmedeski
plugins/zoxide/ @ajeetdsouza
plugins/starship/ @axieax
plugins/dbt/ @msempere

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

@ -0,0 +1,20 @@
dependencies:
plugins/gitfast:
repo: felipec/git-completion
branch: master
version: tag:v2.0
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/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

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

@ -0,0 +1,29 @@
name: Update dependencies
on:
workflow_dispatch: {}
# schedule:
# - cron: '34 3 * * */8'
jobs:
check:
name: Check for updates
runs-on: ubuntu-latest
if: github.repository == 'ohmyzsh/ohmyzsh'
steps:
- name: Checkout
uses: actions/checkout@v4
- 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: 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,2 @@
PyYAML~=6.0.1
requests~=2.31.0

View file

@ -0,0 +1,450 @@
import os
import subprocess
import sys
import requests
import shutil
import yaml
from copy import deepcopy
from typing import Optional, TypedDict
# 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"
import timeit
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: Optional[str]
postcopy: Optional[str]
class DependencyYAML(TypedDict):
dependencies: dict[str, DependencyDict]
class UpdateStatus(TypedDict):
has_updates: bool
version: Optional[str]
compare_url: Optional[str]
head_ref: Optional[str]
head_url: Optional[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, {})
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"]:
short_sha = status["head_ref"][:8]
new_version = status["version"] if is_tag else short_sha
try:
# Create new branch
branch = Git.create_branch(self.path, new_version)
# 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
Git.add_and_commit(self.name, short_sha)
# 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}", file=sys.stderr)
print(e.stderr, file=sys.stderr)
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(f"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 create_branch(path: str, version: 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
branch_name = f"update/{path}/{version}"
CommandRunner.run_or_fail(["git", "checkout", "-b", branch_name], stage="CreateBranch")
return branch_name
@staticmethod
def add_and_commit(scope: str, version: str):
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)
@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) -> UpdateStatus:
# 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)
# 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 = data[-1]
latest_tag = latest_ref["ref"].replace("refs/tags/", "")
if latest_tag == current_tag:
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) -> UpdateStatus:
# TODO: add support for semver updating (based on tags)
# Check if upstream github repo has a new version
# GitHub API URL for comparing two commits
url = f"https://api.github.com/repos/{repo}/compare/{version}...{branch}"
# 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:
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(f"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()

56
.github/workflows/installer.yml vendored Normal file
View file

@ -0,0 +1,56 @@
name: Test and Deploy installer
on:
workflow_dispatch: {}
push:
paths:
- 'tools/install.sh'
- '.github/workflows/installer/**'
- '.github/workflows/installer.yml'
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: false
permissions:
contents: read # to checkout
jobs:
test:
name: Test installer
if: github.repository == 'ohmyzsh/ohmyzsh'
runs-on: ${{ matrix.os }}
strategy:
matrix:
os:
- ubuntu-latest
- macos-latest
steps:
- name: Set up git repository
uses: actions/checkout@v3
- name: Install zsh
if: runner.os == 'Linux'
run: sudo apt-get update; sudo apt-get install zsh
- name: Test installer
run: sh ./tools/install.sh
deploy:
name: Deploy installer in install.ohmyz.sh
if: github.ref == 'refs/heads/master'
runs-on: ubuntu-latest
environment: vercel
needs:
- test
steps:
- name: Checkout
uses: actions/checkout@v3
- 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 deploy --prod -t "$VERCEL_TOKEN"

View file

@ -0,0 +1 @@
install.sh

View file

@ -0,0 +1,2 @@
/*
!/install.sh

23
.github/workflows/installer/vercel.json vendored Normal file
View file

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

View file

@ -7,29 +7,26 @@ on:
branches:
- master
push:
branches:
branches:
- master
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
permissions:
contents: read # to fetch code (actions/checkout)
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@v2
uses: actions/checkout@v3
- name: Install zsh
if: runner.os == 'Linux'
run: sudo apt-get update; sudo apt-get install zsh
- name: Test installer
run: sh ./tools/install.sh
- name: Check syntax
run: |
for file in ./oh-my-zsh.sh \

View file

@ -9,14 +9,21 @@ concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
permissions: {}
jobs:
add-to-project:
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
@ -26,24 +33,25 @@ jobs:
gh api graphql -f query='
query($org: String!, $number: Int!) {
organization(login: $org){
projectNext(number: $number) {
projectV2(number: $number) {
id
fields(first:20) {
nodes {
id
name
... on ProjectV2Field {
id
name
}
}
}
}
}
}
' -f org=$ORGANIZATION -F number=$PROJECT_NUMBER > project_data.json
}' -f org=$ORGANIZATION -F number=$PROJECT_NUMBER > project_data.json
# Parse project data
cat >> $GITHUB_ENV <<EOF
PROJECT_ID=$(jq '.data.organization.projectNext.id' project_data.json)
PLUGIN_FIELD_ID=$(jq '.data.organization.projectNext.fields.nodes[] | select(.name == "Plugin") | .id' project_data.json)
THEME_FIELD_ID=$(jq '.data.organization.projectNext.fields.nodes[] | select(.name == "Theme") | .id' project_data.json)
PROJECT_ID=$(jq '.data.organization.projectV2.id' project_data.json)
PLUGIN_FIELD_ID=$(jq '.data.organization.projectV2.fields.nodes[] | select(.name == "Plugin") | .id' project_data.json)
THEME_FIELD_ID=$(jq '.data.organization.projectV2.fields.nodes[] | select(.name == "Theme") | .id' project_data.json)
EOF
- name: Add to project
@ -52,13 +60,13 @@ jobs:
run: |
item_id="$(gh api graphql -f query='
mutation($project: ID!, $content: ID!) {
addProjectNextItem(input: {projectId: $project, contentId: $content}) {
projectNextItem {
addProjectV2ItemById(input: {projectId: $project, contentId: $content}) {
item {
id
}
}
}
' -f project=$PROJECT_ID -f content=$ISSUE_OR_PR_ID --jq '.data.addProjectNextItem.projectNextItem.id')"
' -f project=$PROJECT_ID -f content=$ISSUE_OR_PR_ID --jq '.data.addProjectV2ItemById.item.id')"
echo "ITEM_ID=$item_id" >> $GITHUB_ENV
@ -107,23 +115,27 @@ jobs:
$theme_field: ID!
$theme_value: String!
) {
set_plugin: updateProjectNextItemField(input: {
set_plugin: updateProjectV2ItemFieldValue(input: {
projectId: $project
itemId: $item
fieldId: $plugin_field
value: $plugin_value
value: {
text: $plugin_value
}
}) {
projectNextItem {
projectV2Item {
id
}
}
set_theme: updateProjectNextItemField(input: {
set_theme: updateProjectV2ItemFieldValue(input: {
projectId: $project
itemId: $item
fieldId: $theme_field
value: $theme_value
value: {
text: $theme_value
}
}) {
projectNextItem {
projectV2Item {
id
}
}
@ -132,4 +144,3 @@ jobs:
-f plugin_field=$PLUGIN_FIELD_ID -f plugin_value=$PLUGIN \
-f theme_field=$THEME_FIELD_ID -f theme_value=$THEME \
--silent

4
.gitignore vendored
View file

@ -6,3 +6,7 @@ cache/
log/
*.swp
.DS_Store
# editor configs
.vscode
.idea

4
.prettierrc Normal file
View file

@ -0,0 +1,4 @@
{
"printWidth": 110,
"proseWrap": "always"
}

View file

@ -35,13 +35,13 @@ you would make is not already covered.
Please be so kind as to [search](#use-the-search-luke) for any open issue already covering
your problem.
If you find one, comment on it so we can know there are more people experiencing it.
If you find one, comment on it, so we know more people are experiencing it.
If not, look at the [Troubleshooting](https://github.com/ohmyzsh/ohmyzsh/wiki/Troubleshooting)
page for instructions on how to gather data to better debug your problem.
Then, you can go ahead and create an issue with as much detail as you can provide.
It should include the data gathered as indicated above, along with:
It should include the data gathered as indicated above, along with the following:
1. How to reproduce the problem
2. What the correct behavior should be
@ -57,7 +57,7 @@ We will do our very best to help you.
Please be so kind as to [search](#use-the-search-luke) for any open issue already covering
your suggestion.
If you find one, comment on it so we can know there are more people supporting it.
If you find one, comment on it, so we know more people are supporting it.
If not, you can go ahead and create an issue. Please copy to anyone relevant (e.g. plugin
maintainers) by mentioning their GitHub handle (starting with `@`) in your message.
@ -84,7 +84,7 @@ your [problem](#you-have-a-problem), and any pending/merged/rejected PR covering
If the solution is already reported, try it out and +1 the pull request if the
solution works ok. On the other hand, if you think your solution is better, post
it with a reference to the other one so we can have both solutions to compare.
it with reference to the other one so we can have both solutions to compare.
If not, then go ahead and submit a PR. Please copy to anyone relevant (e.g. plugin
maintainers) by mentioning their GitHub handle (starting with `@`) in your message.
@ -113,14 +113,14 @@ This has become an issue for two opposing reasons:
- Some users want to have their personal aliases in Oh My Zsh.
- Some users don't want any aliases at all and feel that there are too many.
Because of this, from now on we're requiring that new aliases follow these conditions:
Because of this, from now on, we require that new aliases follow these conditions:
1. They will be used by many people, not just a few.
2. The aliases will be used many times and for common tasks.
3. Prefer one generic alias over many specific ones.
4. When justifying the need for an alias, talk about workflows where you'll use it,
preferably in combination with other aliases.
5. If there exists a command with the same name, look for a different alias name.
5. If a command with the same name exists, look for a different alias name.
This list is not exhaustive! Please remember that your alias will be in the machines of many people,
so it should be justified why they should have it.
@ -214,7 +214,7 @@ type(scope)!: subject
```
- `subject`: a brief description of the changes. This will be displayed in the changelog. If you need
to specify other details you can use the commit body but it won't be visible.
to specify other details, you can use the commit body, but it won't be visible.
Formatting tricks: the commit subject may contain:
@ -231,9 +231,9 @@ type(scope)!: subject
### Style
Try to keep the first commit line short. This is harder to do using this commit style but try to be
concise and if you need more space, you can use the commit body. Try to make sure that the commit
subject is clear and precise enough that users will know what change by just looking at the changelog.
Try to keep the first commit line short. It's harder to do using this commit style but try to be
concise, and if you need more space, you can use the commit body. Try to make sure that the commit
subject is clear and precise enough that users will know what changed by just looking at the changelog.
----

152
README.md
View file

@ -13,38 +13,42 @@ Finally, you'll begin to get the sort of attention that you have always felt you
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).
[![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)
- [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)
- [Getting Updates](#getting-updates)
- [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)
@ -55,9 +59,21 @@ 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)
- `curl` or `wget` should be installed
- `git` should be installed (recommended v2.4.11 or higher)
@ -72,9 +88,17 @@ 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)"` |
Alternatively, the installer is also mirrored outside GitHub. Using this URL instead may be required if you're in a country like India or China, that blocks `raw.githubusercontent.com`:
| 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/)"` |
_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
#### 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,
@ -85,6 +109,8 @@ 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
@ -123,7 +149,7 @@ Each built-in plugin includes a **README**, documenting it. This README should s
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)._
@ -194,7 +220,7 @@ like this:
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
@ -204,7 +230,9 @@ the default shell, and it also won't run `zsh` when the installation has finishe
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.
#### Installing From A Forked Repository
The install script also accepts these variables to allow installation of a different repository:
@ -229,19 +257,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.
@ -249,7 +277,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)
@ -257,7 +285,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,7 +296,7 @@ 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`.
### 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.
@ -276,6 +304,72 @@ If you have many functions that go well together, you can put them as a `XYZ.plu
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
<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
(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`:
```zsh
zstyle ':omz:lib:theme-and-appearance' gnu-ls yes
```
_Note: this is not compatible with `DISABLE_LS_COLORS=true`_
### 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.
```sh
# Skip all aliases, in lib files and enabled plugins
zstyle ':omz:*' aliases no
# Skip all aliases in lib files
zstyle ':omz:lib:*' aliases no
# Skip only aliases defined in the directories.zsh lib file
zstyle ':omz:lib:directories' aliases no
# Skip all plugin aliases
zstyle ':omz:plugins:*' aliases no
# Skip only the aliases from the git plugin
zstyle ':omz:plugins:git' aliases no
```
You can combine these in other ways taking into account that more specific scopes takes precedence:
```sh
# Skip all plugin aliases, except for the git plugin
zstyle ':omz:plugins:*' aliases no
zstyle ':omz:plugins:git' aliases yes
```
A previous version of this feature was using the setting below, which has been removed:
```sh
zstyle ':omz:directories' aliases no
```
Instead, you can now use the following:
```sh
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.
> 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.
## 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**:
@ -307,6 +401,18 @@ zstyle ':omz:update' frequency 7
zstyle ':omz:update' frequency 0
```
### Updates Verbosity
You can also limit the update verbosity with the following settings:
```sh
zstyle ':omz:update' verbose default # default update prompt
zstyle ':omz:update' verbose minimal # only few lines
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:
@ -323,7 +429,7 @@ Oh My Zsh isn't for everyone. We'll miss you, but we want to make this an easy b
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).
@ -333,7 +439,7 @@ We also need people to test out pull requests. So take a look through [the open
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.
@ -364,4 +470,4 @@ 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](https://www.planetargon.com/skills/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](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).

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 email the maintainers directly at: [**security@ohmyz.sh**](mailto:security@ohmyz.sh),
or using the link to [privately report a vulnerability with GitHub](https://github.com/ohmyzsh/ohmyzsh/security/advisories/new).
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.

View file

@ -1,10 +1,12 @@
# You can put files here to add functionality separated per file, which
# will be ignored by git.
# Files on the custom/ directory will be automatically loaded by the init
# script, in alphabetical order.
# For example: add yourself some shortcuts to projects you often work on.
#
# Put files in this folder to add your own custom functionality.
# See: https://github.com/ohmyzsh/ohmyzsh/wiki/Customization
#
# Files in the custom/ directory will be:
# - loaded automatically by the init script, in alphabetical order
# - loaded last, after all built-ins in the lib/ directory, to override them
# - ignored by git by default
#
# Example: add custom/shortcuts.zsh for shortcuts to your local projects
#
# brainstormr=~/Projects/development/planetargon/brainstormr
# cd $brainstormr
#

View file

@ -1,2 +1,3 @@
# Add your own custom plugins in the custom/plugins directory. Plugins placed
# here will override ones with the same name in the main plugins directory.
# See: https://github.com/ohmyzsh/ohmyzsh/wiki/Customization#overriding-and-adding-plugins

View file

@ -1,4 +1,6 @@
# Put your custom themes in this folder.
# See: https://github.com/ohmyzsh/ohmyzsh/wiki/Customization#overriding-and-adding-themes
#
# Example:
PROMPT="%{$fg[red]%}%n%{$reset_color%}@%{$fg[blue]%}%m %{$fg[yellow]%}%~ %{$reset_color%}%% "

View file

@ -11,7 +11,7 @@ function omz {
# Subcommand functions start with _ so that they don't
# appear as completion entries when looking for `omz`
(( $+functions[_omz::$command] )) || {
(( ${+functions[_omz::$command]} )) || {
_omz::help
return 1
}
@ -241,21 +241,21 @@ function _omz::plugin::disable {
# Remove plugins substitution awk script
local awk_subst_plugins="\
gsub(/\s+(${(j:|:)dis_plugins})/, \"\") # with spaces before
gsub(/(${(j:|:)dis_plugins})\s+/, \"\") # with spaces after
gsub(/[ \t]+(${(j:|:)dis_plugins})/, \"\") # with spaces before
gsub(/(${(j:|:)dis_plugins})[ \t]+/, \"\") # with spaces after
gsub(/\((${(j:|:)dis_plugins})\)/, \"\") # without spaces (only plugin)
"
# Disable plugins awk script
local awk_script="
# if plugins=() is in oneline form, substitute disabled plugins and go to next line
/^\s*plugins=\([^#]+\).*\$/ {
/^[ \t]*plugins=\([^#]+\).*\$/ {
$awk_subst_plugins
print \$0
next
}
# if plugins=() is in multiline form, enable multi flag and disable plugins if they're there
/^\s*plugins=\(/ {
/^[ \t]*plugins=\(/ {
multi=1
$awk_subst_plugins
print \$0
@ -330,14 +330,14 @@ function _omz::plugin::enable {
# Enable plugins awk script
local awk_script="
# if plugins=() is in oneline form, substitute ) with new plugins and go to the next line
/^\s*plugins=\([^#]+\).*\$/ {
/^[ \t]*plugins=\([^#]+\).*\$/ {
sub(/\)/, \" $add_plugins&\")
print \$0
next
}
# if plugins=() is in multiline form, enable multi flag
/^\s*plugins=\(/ {
/^[ \t]*plugins=\(/ {
multi=1
}
@ -416,14 +416,14 @@ function _omz::plugin::list {
if (( ${#custom_plugins} )); then
print -P "%U%BCustom plugins%b%u:"
print -l ${(q-)custom_plugins} | column -x
print -lac ${(q-)custom_plugins}
fi
if (( ${#builtin_plugins} )); then
(( ${#custom_plugins} )) && echo # add a line of separation
print -P "%U%BBuilt-in plugins%b%u:"
print -l ${(q-)builtin_plugins} | column -x
print -lac ${(q-)builtin_plugins}
fi
}
@ -674,13 +674,13 @@ function _omz::theme::list {
# Print custom themes if there are any
if (( ${#custom_themes} )); then
print -P "%U%BCustom themes%b%u:"
print -l ${(q-)custom_themes} | column -x
print -lac ${(q-)custom_themes}
echo
fi
# Print built-in themes
print -P "%U%BBuilt-in themes%b%u:"
print -l ${(q-)builtin_themes} | column -x
print -lac ${(q-)builtin_themes}
}
function _omz::theme::set {
@ -699,9 +699,9 @@ function _omz::theme::set {
# Enable theme in .zshrc
local awk_script='
!set && /^\s*ZSH_THEME=[^#]+.*$/ {
!set && /^[ \t]*ZSH_THEME=[^#]+.*$/ {
set=1
sub(/^\s*ZSH_THEME=[^#]+.*$/, "ZSH_THEME=\"'$1'\" # set by `omz`")
sub(/^[ \t]*ZSH_THEME=[^#]+.*$/, "ZSH_THEME=\"'$1'\" # set by `omz`")
print $0
next
}
@ -776,10 +776,11 @@ function _omz::update {
local last_commit=$(builtin cd -q "$ZSH"; git rev-parse HEAD)
# Run update script
zstyle -s ':omz:update' verbose verbose_mode || verbose_mode=default
if [[ "$1" != --unattended ]]; then
ZSH="$ZSH" command zsh -f "$ZSH/tools/upgrade.sh" --interactive || return $?
ZSH="$ZSH" command zsh -f "$ZSH/tools/upgrade.sh" -i -v $verbose_mode || return $?
else
ZSH="$ZSH" command zsh -f "$ZSH/tools/upgrade.sh" || return $?
ZSH="$ZSH" command zsh -f "$ZSH/tools/upgrade.sh" -v $verbose_mode || return $?
fi
# Update last updated file

View file

@ -57,9 +57,12 @@ function detect-clipboard() {
elif [[ "${OSTYPE}" == (cygwin|msys)* ]]; then
function clipcopy() { cat "${1:-/dev/stdin}" > /dev/clipboard; }
function clippaste() { cat /dev/clipboard; }
elif (( $+commands[clip.exe] )) && (( $+commands[powershell.exe] )); then
function clipcopy() { cat "${1:-/dev/stdin}" | clip.exe; }
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; }
@ -81,9 +84,6 @@ function detect-clipboard() {
elif [ -n "${TMUX:-}" ] && (( ${+commands[tmux]} )); then
function clipcopy() { tmux load-buffer "${1:--}"; }
function clippaste() { tmux save-buffer -; }
elif [[ $(uname -r) = *icrosoft* ]]; then
function clipcopy() { cat "${1:-/dev/stdin}" | clip.exe; }
function clippaste() { powershell.exe -noprofile -command Get-Clipboard; }
else
function _retry_clipboard_detection_or_fail() {
local clipcmd="${1}"; shift
@ -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

@ -18,9 +18,9 @@ if [[ "$CASE_SENSITIVE" = true ]]; then
zstyle ':completion:*' matcher-list 'r:|=*' 'l:|=* r:|=*'
else
if [[ "$HYPHEN_INSENSITIVE" = true ]]; then
zstyle ':completion:*' matcher-list 'm:{a-zA-Z-_}={A-Za-z_-}' 'r:|=*' 'l:|=* r:|=*'
zstyle ':completion:*' matcher-list 'm:{[:lower:][:upper:]-_}={[:upper:][:lower:]_-}' 'r:|=*' 'l:|=* r:|=*'
else
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}' 'r:|=*' 'l:|=* r:|=*'
zstyle ':completion:*' matcher-list 'm:{[:lower:][:upper:]}={[:upper:][:lower:]}' 'r:|=*' 'l:|=* r:|=*'
fi
fi
unset CASE_SENSITIVE HYPHEN_INSENSITIVE

View file

@ -1,13 +1,8 @@
if [[ "$ENABLE_CORRECTION" == "true" ]]; then
alias cp='nocorrect cp'
alias ebuild='nocorrect ebuild'
alias gist='nocorrect gist'
alias heroku='nocorrect heroku'
alias hpodder='nocorrect hpodder'
alias man='nocorrect man'
alias mkdir='nocorrect mkdir'
alias mv='nocorrect mv'
alias mysql='nocorrect mysql'
alias sudo='nocorrect sudo'
alias su='nocorrect su'

View file

@ -1,8 +1,10 @@
# Changing/making/removing directory
setopt auto_cd
setopt auto_pushd
setopt pushd_ignore_dups
setopt pushdminus
alias -g ...='../..'
alias -g ....='../../..'
alias -g .....='../../../..'

View file

@ -5,7 +5,7 @@ function zsh_stats() {
}
function uninstall_oh_my_zsh() {
env ZSH="$ZSH" sh "$ZSH/tools/uninstall.sh"
command env ZSH="$ZSH" sh "$ZSH/tools/uninstall.sh"
}
function upgrade_oh_my_zsh() {
@ -30,6 +30,13 @@ function open_command() {
;;
esac
# If a URL is passed, $BROWSER might be set to a local browser within SSH.
# See https://github.com/ohmyzsh/ohmyzsh/issues/11098
if [[ -n "$BROWSER" && "$1" = (http|https)://* ]]; then
"$BROWSER" "$@"
return
fi
${=open_cmd} "$@" &>/dev/null
}
@ -56,7 +63,7 @@ function takegit() {
}
function take() {
if [[ $1 =~ ^(https?|ftp).*\.tar\.(gz|bz2|xz)$ ]]; then
if [[ $1 =~ ^(https?|ftp).*\.(tar\.(gz|bz2|xz)|tgz)$ ]]; then
takeurl "$1"
elif [[ $1 =~ ^([A-Za-z0-9]\+@|https?|git|ssh|ftps?|rsync).*\.git/?$ ]]; then
takegit "$1"
@ -175,6 +182,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=';/?:@&=+$,'
@ -199,6 +208,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

@ -19,6 +19,7 @@ function git_prompt_info() {
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) \
|| ref=$(__git_prompt_git rev-parse --short HEAD 2> /dev/null) \
|| return 0

View file

@ -24,8 +24,8 @@ else
if [[ -n "$GREP_OPTIONS" ]]; then
# export grep, egrep and fgrep settings
alias grep="grep $GREP_OPTIONS"
alias egrep="egrep $GREP_OPTIONS"
alias fgrep="fgrep $GREP_OPTIONS"
alias egrep="grep -E $GREP_OPTIONS"
alias fgrep="grep -F $GREP_OPTIONS"
# write to cache file if cache directory is writable
if [[ -w "$ZSH_CACHE_DIR" ]]; then

View file

@ -15,11 +15,17 @@ if [[ $DISABLE_MAGIC_FUNCTIONS != true ]]; then
done
fi
## jobs
setopt long_list_jobs
setopt multios # enable redirect to multiple streams: echo >file1 >file2
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 '
@ -30,6 +36,3 @@ if (( $+commands[ack-grep] )); then
elif (( $+commands[ack] )); then
alias afind='ack -il'
fi
# recognize comments
setopt interactivecomments

View file

@ -18,6 +18,7 @@ function chruby_prompt_info \
vi_mode_prompt_info \
virtualenv_prompt_info \
jenv_prompt_info \
azure_prompt_info \
tf_prompt_info \
{
return 1

View file

@ -17,7 +17,7 @@ function title {
: ${2=$1}
case "$TERM" in
cygwin|xterm*|putty*|rxvt*|konsole*|ansi|mlterm*|alacritty|st*|foot)
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
;;
@ -109,28 +109,55 @@ if [[ -z "$INSIDE_EMACS" || "$INSIDE_EMACS" = vterm ]]; then
add-zsh-hook preexec omz_termsupport_preexec
fi
# Keep Apple Terminal.app's current working directory updated
# Based on this answer: https://superuser.com/a/315029
# With extra fixes to handle multibyte chars and non-UTF-8 locales
# Keep terminal emulator's current working directory correct,
# even if the current working directory path contains symbolic links
#
# References:
# - Apple's Terminal.app: https://superuser.com/a/315029
# - iTerm2: https://iterm2.com/documentation-escape-codes.html (iTerm2 Extension / CurrentDir+RemoteHost)
# - Konsole: https://bugs.kde.org/show_bug.cgi?id=327720#c1
# - libvte (gnome-terminal, mate-terminal, …): https://bugzilla.gnome.org/show_bug.cgi?id=675987#c14
# Apparently it had a bug before ~2012 were it would display the unknown OSC 7 code
#
# As of May 2021 mlterm, PuTTY, rxvt, screen, termux & xterm simply ignore the unknown OSC.
if [[ "$TERM_PROGRAM" == "Apple_Terminal" ]] && [[ -z "$INSIDE_EMACS" ]]; then
# Emits the control sequence to notify Terminal.app of the cwd
# Identifies the directory using a file: URI scheme, including
# the host name to disambiguate local vs. remote paths.
function update_terminalapp_cwd() {
emulate -L zsh
# Percent-encode the host and path names.
local URL_HOST URL_PATH
URL_HOST="$(omz_urlencode -P $HOST)" || return 1
URL_PATH="$(omz_urlencode -P $PWD)" || return 1
# Undocumented Terminal.app-specific control sequence
printf '\e]7;%s\a' "file://$URL_HOST$URL_PATH"
}
# Use a precmd hook instead of a chpwd hook to avoid contaminating output
add-zsh-hook precmd update_terminalapp_cwd
# Run once to get initial cwd set
update_terminalapp_cwd
# Don't define the function if we're inside Emacs or in an SSH session (#11696)
if [[ -n "$INSIDE_EMACS" || -n "$SSH_CLIENT" || -n "$SSH_TTY" ]]; then
return
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*) ;;
contour*|foot*) ;;
*)
# Terminal.app and iTerm2 process OSC 7 correctly
case "$TERM_PROGRAM" in
Apple_Terminal|iTerm.app) ;;
*) return ;;
esac ;;
esac
# Emits the control sequence to notify many terminal emulators
# of the cwd
#
# Identifies the directory using a file: URI scheme, including
# the host name to disambiguate local vs. remote paths.
function omz_termsupport_cwd {
# Percent-encode the host and path names.
local URL_HOST URL_PATH
URL_HOST="$(omz_urlencode -P $HOST)" || return 1
URL_PATH="$(omz_urlencode -P $PWD)" || return 1
# Konsole errors if the HOST is provided
[[ -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}"
}
# Use a precmd hook instead of a chpwd hook to avoid contaminating output
# i.e. when a script or function changes directory without `cd -q`, chpwd
# will be called the output may be swallowed by the script or function.
add-zsh-hook precmd omz_termsupport_cwd

View file

@ -1,59 +1,81 @@
# ls colors
# Sets color variable such as $fg, $bg, $color and $reset_color
autoload -U colors && colors
# Enable ls colors
# Expand variables and commands in PROMPT variables
setopt prompt_subst
# Prompt function theming defaults
ZSH_THEME_GIT_PROMPT_PREFIX="git:(" # Beginning of the git prompt, before the branch name
ZSH_THEME_GIT_PROMPT_SUFFIX=")" # End of the git prompt
ZSH_THEME_GIT_PROMPT_DIRTY="*" # Text to display if the branch is dirty
ZSH_THEME_GIT_PROMPT_CLEAN="" # Text to display if the branch is clean
ZSH_THEME_RUBY_PROMPT_PREFIX="("
ZSH_THEME_RUBY_PROMPT_SUFFIX=")"
# Use diff --color if available
if command diff --color /dev/null{,} &>/dev/null; then
function diff {
command diff --color "$@"
}
fi
# Don't set ls coloring if disabled
[[ "$DISABLE_LS_COLORS" != true ]] || return 0
# Default coloring for BSD-based ls
export LSCOLORS="Gxfxcxdxbxegedabagacad"
# TODO organise this chaotic logic
if [[ "$DISABLE_LS_COLORS" != "true" ]]; then
# Find the option for using colors in ls, depending on the version
if [[ "$OSTYPE" == netbsd* ]]; then
# On NetBSD, test if "gls" (GNU ls) is installed (this one supports colors);
# otherwise, leave ls as is, because NetBSD's ls doesn't support -G
gls --color -d . &>/dev/null && alias ls='gls --color=tty'
elif [[ "$OSTYPE" == openbsd* ]]; then
# On OpenBSD, "gls" (ls from GNU coreutils) and "colorls" (ls from base,
# with color and multibyte support) are available from ports. "colorls"
# will be installed on purpose and can't be pulled in by installing
# coreutils, so prefer it to "gls".
gls --color -d . &>/dev/null && alias ls='gls --color=tty'
colorls -G -d . &>/dev/null && alias ls='colorls -G'
elif [[ "$OSTYPE" == (darwin|freebsd)* ]]; then
# this is a good alias, it works by default just using $LSCOLORS
ls -G . &>/dev/null && alias ls='ls -G'
# only use coreutils ls if there is a dircolors customization present ($LS_COLORS or .dircolors file)
# otherwise, gls will use the default color scheme which is ugly af
[[ -n "$LS_COLORS" || -f "$HOME/.dircolors" ]] && gls --color -d . &>/dev/null && alias ls='gls --color=tty'
# Default coloring for GNU-based ls
if [[ -z "$LS_COLORS" ]]; then
# Define LS_COLORS via dircolors if available. Otherwise, set a default
# equivalent to LSCOLORS (generated via https://geoff.greer.fm/lscolors)
if (( $+commands[dircolors] )); then
[[ -f "$HOME/.dircolors" ]] \
&& source <(dircolors -b "$HOME/.dircolors") \
|| source <(dircolors -b)
else
# For GNU ls, we use the default ls color theme. They can later be overwritten by themes.
if [[ -z "$LS_COLORS" ]]; then
(( $+commands[dircolors] )) && eval "$(dircolors -b)"
fi
ls --color -d . &>/dev/null && alias ls='ls --color=tty' || { ls -G . &>/dev/null && alias ls='ls -G' }
# Take advantage of $LS_COLORS for completion as well.
zstyle ':completion:*' list-colors "${(s.:.)LS_COLORS}"
export LS_COLORS="di=1;36:ln=35:so=32:pi=33:ex=31:bd=34;46:cd=34;43:su=30;41:sg=30;46:tw=30;42:ow=30;43"
fi
fi
# enable diff color if possible.
if command diff --color /dev/null /dev/null &>/dev/null; then
alias diff='diff --color'
fi
function test-ls-args {
local cmd="$1" # ls, gls, colorls, ...
local args="${@[2,-1]}" # arguments except the first one
command "$cmd" "$args" /dev/null &>/dev/null
}
setopt auto_cd
setopt multios
setopt prompt_subst
# Find the option for using colors in ls, depending on the version
case "$OSTYPE" in
netbsd*)
# On NetBSD, test if `gls` (GNU ls) is installed (this one supports colors);
# otherwise, leave ls as is, because NetBSD's ls doesn't support -G
test-ls-args gls --color && alias ls='gls --color=tty'
;;
openbsd*)
# On OpenBSD, `gls` (ls from GNU coreutils) and `colorls` (ls from base,
# with color and multibyte support) are available from ports.
# `colorls` will be installed on purpose and can't be pulled in by installing
# coreutils (which might be installed for ), so prefer it to `gls`.
test-ls-args gls --color && alias ls='gls --color=tty'
test-ls-args colorls -G && alias ls='colorls -G'
;;
(darwin|freebsd)*)
# This alias works by default just using $LSCOLORS
test-ls-args ls -G && alias ls='ls -G'
# Only use GNU ls if installed and there are user defaults for $LS_COLORS,
# as the default coloring scheme is not very pretty
zstyle -t ':omz:lib:theme-and-appearance' gnu-ls \
&& test-ls-args gls --color \
&& alias ls='gls --color=tty'
;;
*)
if test-ls-args ls --color; then
alias ls='ls --color=tty'
elif test-ls-args ls -G; then
alias ls='ls -G'
fi
;;
esac
[[ -n "$WINDOW" ]] && SCREEN_NO="%B$WINDOW%b " || SCREEN_NO=""
# git theming default: Variables for theming the git info prompt
ZSH_THEME_GIT_PROMPT_PREFIX="git:(" # Prefix at the very beginning of the prompt, before the branch name
ZSH_THEME_GIT_PROMPT_SUFFIX=")" # At the very end of the prompt
ZSH_THEME_GIT_PROMPT_DIRTY="*" # Text to display if the branch is dirty
ZSH_THEME_GIT_PROMPT_CLEAN="" # Text to display if the branch is clean
ZSH_THEME_RUBY_PROMPT_PREFIX="("
ZSH_THEME_RUBY_PROMPT_SUFFIX=")"
unfunction test-ls-args

View file

@ -38,7 +38,7 @@
# due to malicious input as a consequence of CVE-2021-45444, which affects
# zsh versions from 5.0.3 to 5.8.
#
autoload -Uz +X regexp-replace VCS_INFO_formats 2>/dev/null || return
autoload -Uz +X regexp-replace VCS_INFO_formats 2>/dev/null || return 0
# We use $tmp here because it's already a local variable in VCS_INFO_formats
typeset PATCH='for tmp (base base-name branch misc revision subdir) hook_com[$tmp]="${hook_com[$tmp]//\%/%%}"'

View file

@ -1,14 +1,14 @@
# 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() { :; }
# 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() {
[ $# -gt 0 ] || return
IFS=";" printf "\033[%sm" $*
}
# If stdout is not a terminal ignore all formatting
[ -t 1 ] || omz_f() { :; }
omz_ptree() {
# Get process tree of the current process
pid=$$; pids="$pid"
@ -38,6 +38,15 @@
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}"
@ -57,9 +66,7 @@ mkdir -p "$ZSH_CACHE_DIR/completions"
(( ${fpath[(Ie)"$ZSH_CACHE_DIR/completions"]} )) || fpath=("$ZSH_CACHE_DIR/completions" $fpath)
# Check for updates on initial load...
if [[ "$DISABLE_AUTO_UPDATE" != true ]]; then
source "$ZSH/tools/check_for_upgrade.sh"
fi
source "$ZSH/tools/check_for_upgrade.sh"
# Initializes Oh My Zsh
@ -67,7 +74,7 @@ fi
fpath=("$ZSH/functions" "$ZSH/completions" $fpath)
# Load all stock functions (from $fpath files) called below.
autoload -U compaudit compinit
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/
@ -142,22 +149,63 @@ EOF
fi
unset zcompdump_revision zcompdump_fpath zcompdump_refresh
# Load all of the config files in ~/oh-my-zsh that end in .zsh
# zcompile the completion dump file if the .zwc is older or missing.
if command mkdir "${ZSH_COMPDUMP}.lock" 2>/dev/null; then
zrecompile -q -p "$ZSH_COMPDUMP"
command rm -rf "$ZSH_COMPDUMP.zwc.old" "${ZSH_COMPDUMP}.lock"
fi
_omz_source() {
local context filepath="$1"
# Construct zstyle context based on path
case "$filepath" in
lib/*) context="lib:${filepath:t:r}" ;; # :t = lib_name.zsh, :r = lib_name
plugins/*) context="plugins:${filepath:h:t}" ;; # :h = plugins/plugin_name, :t = plugin_name
esac
local disable_aliases=0
zstyle -T ":omz:${context}" aliases || disable_aliases=1
# Back up alias names prior to sourcing
local -A aliases_pre galiases_pre
if (( disable_aliases )); then
aliases_pre=("${(@kv)aliases}")
galiases_pre=("${(@kv)galiases}")
fi
# Source file from $ZSH_CUSTOM if it exists, otherwise from $ZSH
if [[ -f "$ZSH_CUSTOM/$filepath" ]]; then
source "$ZSH_CUSTOM/$filepath"
elif [[ -f "$ZSH/$filepath" ]]; then
source "$ZSH/$filepath"
fi
# Unset all aliases that don't appear in the backed up list of aliases
if (( disable_aliases )); then
if (( #aliases_pre )); then
aliases=("${(@kv)aliases_pre}")
else
(( #aliases )) && unalias "${(@k)aliases}"
fi
if (( #galiases_pre )); then
galiases=("${(@kv)galiases_pre}")
else
(( #galiases )) && unalias "${(@k)galiases}"
fi
fi
}
# 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
custom_config_file="$ZSH_CUSTOM/lib/${config_file:t}"
[[ -f "$custom_config_file" ]] && config_file="$custom_config_file"
source "$config_file"
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
if [[ -f "$ZSH_CUSTOM/plugins/$plugin/$plugin.plugin.zsh" ]]; then
source "$ZSH_CUSTOM/plugins/$plugin/$plugin.plugin.zsh"
elif [[ -f "$ZSH/plugins/$plugin/$plugin.plugin.zsh" ]]; then
source "$ZSH/plugins/$plugin/$plugin.plugin.zsh"
fi
_omz_source "plugins/$plugin/$plugin.plugin.zsh"
done
unset plugin
@ -185,3 +233,6 @@ if [[ -n "$ZSH_THEME" ]]; then
echo "[oh-my-zsh] theme '$ZSH_THEME' not found"
fi
fi
# set completion colors to be the same as `ls`, after theme has been loaded
[[ -z "$LS_COLORS" ]] || zstyle ':completion:*' list-colors "${(s.:.)LS_COLORS}"

View file

@ -14,16 +14,18 @@ clipboard.
## `opswd`
The `opswd` command is a wrapper around the `op` command. It takes a service
name as an argument and copies the password for that service to the clipboard.
name as an argument and copies the username, then the password for that service
to the clipboard, after confirmation on the user part.
If the service also contains a TOTP, it is copied to the clipboard after 10 seconds.
Finally, after 20 seconds, the clipboard is cleared.
If the service also contains a TOTP, it is copied to the clipboard after confirmation
on the user part. Finally, after 20 seconds, the clipboard is cleared.
The function has completion support, so you can use tab completion to select
which service you want to get.
For example, `opswd github.com` will put your GitHub username into your clipboard. Then,
it will ask for confirmation to continue, and copy the password to your clipboard. Finally,
if a TOTP is available, it will be copied to the clipboard after your confirmation.
For example, `opswd github.com` will put your GitHub password into your clipboard, and if
a TOTP is available, it will be copied to the clipboard after 10 seconds.
This function has completion support, so you can use tab completion to select which
service you want to get.
> NOTE: you need to be signed in for `opswd` to work. If you are using biometric unlock,
> 1Password CLI will automatically prompt you to sign in. See:

View file

@ -14,6 +14,17 @@ function opswd() {
# If not logged in, print error and return
op user list > /dev/null || return
local username
# Copy the username to the clipboard
if ! username=$(op item get "$service" --fields username 2>/dev/null); then
echo "error: could not obtain username for $service"
return 1
fi
echo -n "$username" | clipcopy
echo "✔ username for service $service copied to the clipboard. Press Enter to continue"
read
local password
# Copy the password to the clipboard
if ! password=$(op item get "$service" --fields password 2>/dev/null); then
@ -22,12 +33,13 @@ function opswd() {
fi
echo -n "$password" | clipcopy
echo "✔ password for $service copied to clipboard"
echo "✔ password for $service copied to clipboard. Press Enter to continue"
read
# If there's a one time password, copy it to the clipboard after 10 seconds
# If there's a one time password, copy it to the clipboard
local totp
if totp=$(op item get --otp "$service" 2>/dev/null) && [[ -n "$totp" ]]; then
sleep 10 && echo -n "$totp" | clipcopy
echo -n "$totp" | clipcopy
echo "✔ TOTP for $service copied to clipboard"
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,32 @@
This plugin searches the defined aliases and outputs any that match the command inputted. This makes learning new aliases easier.
## Usage
To use it, add `alias-finder` to the `plugins` array of your zshrc file:
```
plugins=(... alias-finder)
```
## 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.
To enable it for every single command, set zstyle in your `~/.zshrc`.
## Options
```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.
### 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).
- 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.
## Examples
```
$ alias-finder "git pull"
gl='git pull'
g=git
```
```
$ 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'
```

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
while [[ $cmd != "" ]]; do
if [[ $longer = true ]]; then
wordStart="'{0,1}"
else
wordEnd="$"
multiWordEnd="'$"
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
fi
done
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
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
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
}
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

@ -15,8 +15,14 @@ Requirements: Python needs to be installed.
## Usage
- `acs`: show all aliases by group.
- `als`: show all aliases by group
- `acs <keyword>`: filter aliases by `<keyword>` and highlight.
- `als -h/--help`: print help message
![screenshot](https://cloud.githubusercontent.com/assets/3602957/11581913/cb54fb8a-9a82-11e5-846b-5a67f67ad9ad.png)
- `als <keyword(s)>`: filter and highlight aliases by `<keyword>`
- `als -g <group>/--group <group>`: show only aliases for group `<group>`. Multiple uses of the flag show all groups
- `als --groups`: show only group names
![screenshot](https://github.com/ohmyzsh/ohmyzsh/assets/66907184/5bfa00ea-5fc3-4e97-8b22-2f74f6b948c7)

View file

@ -4,7 +4,7 @@
0="${${(M)0:#/*}:-$PWD/$0}"
eval '
function acs(){
function als(){
(( $+commands[python3] )) || {
echo "[error] No python executable detected"
return

View file

@ -2,6 +2,7 @@
import sys
import itertools
import termcolor
import argparse
def parse(line):
left = line[0:line.find('=')].strip()
@ -14,6 +15,7 @@ def parse(line):
def cheatsheet(lines):
exps = [ parse(line) for line in lines ]
exps.sort(key=lambda exp:exp[2])
cheatsheet = {'_default': []}
for key, group in itertools.groupby(exps, lambda exp:exp[2]):
group_list = [ item for item in group ]
@ -26,7 +28,7 @@ def cheatsheet(lines):
target_aliases.extend(group_list)
return cheatsheet
def pretty_print_group(key, aliases, highlight=None):
def pretty_print_group(key, aliases, highlight=None, only_groupname=False):
if len(aliases) == 0:
return
group_hl_formatter = lambda g, hl: termcolor.colored(hl, 'yellow').join([termcolor.colored(part, 'red') for part in ('[%s]' % g).split(hl)])
@ -35,21 +37,33 @@ def pretty_print_group(key, aliases, highlight=None):
alias_formatter = lambda alias: termcolor.colored('\t%s = %s' % alias[0:2], 'green')
if highlight and len(highlight)>0:
print (group_hl_formatter(key, highlight))
print ('\n'.join([alias_hl_formatter(alias, highlight) for alias in aliases]))
if not only_groupname:
print ('\n'.join([alias_hl_formatter(alias, highlight) for alias in aliases]))
else:
print (group_formatter(key))
print ('\n'.join([alias_formatter(alias) for alias in aliases]))
if not only_groupname:
print ('\n'.join([alias_formatter(alias) for alias in aliases]))
print ('')
def pretty_print(cheatsheet, wfilter):
def pretty_print(cheatsheet, wfilter, group_list=None, groups_only=False):
sorted_key = sorted(cheatsheet.keys())
for key in sorted_key:
if group_list and key not in group_list:
continue
aliases = cheatsheet.get(key)
if not wfilter:
pretty_print_group(key, aliases, wfilter)
pretty_print_group(key, aliases, wfilter, groups_only)
else:
pretty_print_group(key, [ alias for alias in aliases if alias[0].find(wfilter)>-1 or alias[1].find(wfilter)>-1], wfilter)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Pretty print aliases.", prog="als")
parser.add_argument('filter', nargs="*", metavar="<keyword>", help="search aliases matching keywords")
parser.add_argument('-g', '--group', dest="group_list", action='append', help="only print aliases in given groups")
parser.add_argument('--groups', dest='groups_only', action='store_true', help="only print alias groups")
args = parser.parse_args()
lines = sys.stdin.readlines()
pretty_print(cheatsheet(lines), sys.argv[1] if len(sys.argv)>1 else None)
group_list = args.group_list or None
wfilter = " ".join(args.filter) or None
pretty_print(cheatsheet(lines), wfilter, group_list, args.groups_only)

View file

@ -181,3 +181,4 @@ whether the package manager is installed, checked in the following order:
- Ybalrid (Arthur Brainville) - ybalrid@ybalrid.info
- Jeff M. Hubbard - jeffmhubbard@gmail.com
- K. Harishankar(harishnkr) - hari2menon1234@gmail.com
- WH-2099 - wh2099@outlook.com

View file

@ -23,30 +23,27 @@ alias pacfiles='pacman -F'
alias pacls='pacman -Ql'
alias pacown='pacman -Qo'
alias pacupd="sudo pacman -Sy"
alias upgrade='sudo pacman -Syu'
function paclist() {
# Based on https://bbs.archlinux.org/viewtopic.php?id=93683
pacman -Qqe | \
xargs -I '{}' \
expac "${bold_color}% 20n ${fg_no_bold[white]}%d${reset_color}" '{}'
pacman -Qqe | xargs -I{} -P0 --no-run-if-empty pacman -Qs --color=auto "^{}\$"
}
function pacdisowned() {
local tmp db fs
tmp=${TMPDIR-/tmp}/pacman-disowned-$UID-$$
db=$tmp/db
fs=$tmp/fs
local tmp_dir db fs
tmp_dir=$(mktemp --directory)
db=$tmp_dir/db
fs=$tmp_dir/fs
mkdir "$tmp"
trap 'rm -rf "$tmp"' EXIT
trap "rm -rf $tmp_dir" EXIT
pacman -Qlq | sort -u > "$db"
find /bin /etc /lib /sbin /usr ! -name lost+found \
find /etc /usr ! -name lost+found \
\( -type d -printf '%p/\n' -o -print \) | sort > "$fs"
comm -23 "$fs" "$db"
rm -rf $tmp_dir
}
alias pacmanallkeys='sudo pacman-key --refresh-keys'
@ -109,7 +106,6 @@ if (( $+commands[aura] )); then
alias auupd="sudo aura -Sy"
alias auupg='sudo sh -c "aura -Syu && aura -Au"'
alias ausu='sudo sh -c "aura -Syu --no-confirm && aura -Au --no-confirm"'
alias upgrade='sudo aura -Syu'
# extra bonus specially for aura
alias auown="aura -Qqo"
@ -136,7 +132,6 @@ if (( $+commands[pacaur] )); then
alias painsd='pacaur -S --asdeps'
alias pamir='pacaur -Syy'
alias paupd="pacaur -Sy"
alias upgrade='pacaur -Syu'
fi
if (( $+commands[trizen] )); then
@ -158,7 +153,6 @@ if (( $+commands[trizen] )); then
alias trinsd='trizen -S --asdeps'
alias trmir='trizen -Syy'
alias trupd="trizen -Sy"
alias upgrade='trizen -Syu'
fi
if (( $+commands[yay] )); then
@ -180,5 +174,30 @@ if (( $+commands[yay] )); then
alias yainsd='yay -S --asdeps'
alias yamir='yay -Syy'
alias yaupd="yay -Sy"
alias upgrade='yay -Syu'
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 : ).*')"
if [ $installedver != $currentver ]; then
echo " Arch Linux PGP Keyring is out of date."
echo " Updating before full system upgrade."
sudo pacman -Sy --needed --noconfirm archlinux-keyring
else
echo " Arch Linux PGP Keyring is up to date."
echo " Proceeding with full system upgrade."
fi
if (( $+commands[yay] )); then
yay -Syu
elif (( $+commands[trizen] )); then
trizen -Syu
elif (( $+commands[pacaur] )); then
pacaur -Syu
elif (( $+commands[aura] )); then
sudo aura -Syu
else
sudo pacman -Syu
fi
}

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

@ -0,0 +1,20 @@
# Argo CD plugin
This plugin adds completion for the [Argo CD](https://argoproj.github.io/cd/) CLI.
To use it, add `argocd` to the plugins array in your zshrc file:
```zsh
plugins=(... argocd)
```
This plugin does not add any aliases.
## Cache
This plugin caches the completion script and is automatically updated asynchronously when the plugin is
loaded, which is usually when you start up a new terminal emulator.
The cache is stored at:
- `$ZSH_CACHE/completions/_argocd` completions script

View file

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

View file

@ -6,22 +6,25 @@ Adds integration with [asdf](https://github.com/asdf-vm/asdf), the extendable ve
### Installation
1. Enable the plugin by adding it to your `plugins` definition in `~/.zshrc`.
1. [Download asdf](https://asdf-vm.com/guide/getting-started.html#_2-download-asdf) by running the following:
```
git clone https://github.com/asdf-vm/asdf.git ~/.asdf
```
2. [Enable asdf](https://asdf-vm.com/guide/getting-started.html#_3-install-asdf) by adding it to your `plugins` definition in `~/.zshrc`.
```
plugins=(asdf)
```
2. [Install asdf](https://github.com/asdf-vm/asdf#setup) by running the following:
```
git clone https://github.com/asdf-vm/asdf.git ~/.asdf
```
### Usage
See the [asdf usage documentation](https://github.com/asdf-vm/asdf#usage) for information on how to use asdf:
See the [asdf documentation](https://asdf-vm.com/guide/getting-started.html#_4-install-a-plugin) for information on how to use asdf:
```
asdf plugin-add nodejs git@github.com:asdf-vm/asdf-nodejs.git
asdf install nodejs 5.9.1
asdf plugin add nodejs https://github.com/asdf-vm/asdf-nodejs.git
asdf install nodejs latest
asdf global nodejs latest
asdf local nodejs latest
```

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
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 [[ ! -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"
# 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

@ -17,9 +17,13 @@ if ! type autoenv_init >/dev/null; then
/usr/local/bin
/usr/share/autoenv-git
~/Library/Python/bin
.venv/bin
venv/bin
env/bin
.env/bin
)
for d ( $install_locations ); do
if [[ -e $d/activate.sh ]]; then
if [[ -e $d/activate || -e $d/activate.sh ]]; then
autoenv_dir=$d
break
fi
@ -29,13 +33,13 @@ if ! type autoenv_init >/dev/null; then
# Look for Homebrew path as a last resort
if [[ -z "$autoenv_dir" ]] && (( $+commands[brew] )); then
d=$(brew --prefix)/opt/autoenv
if [[ -e $d/activate.sh ]]; then
if [[ -e $d/activate || -e $d/activate.sh ]]; then
autoenv_dir=$d
fi
fi
# Complain if autoenv is not installed
if [[ -z $autoenv_dir ]]; then
if [[ -z $autoenv_dir ]]; then
cat <<END >&2
-------- AUTOENV ---------
Could not locate autoenv installation.
@ -46,7 +50,11 @@ END
return 1
fi
# Load autoenv
source $autoenv_dir/activate.sh
if [[ -e $autoenv_dir/activate ]]; then
source $autoenv_dir/activate
else
source $autoenv_dir/activate.sh
fi
fi
}
[[ $? != 0 ]] && return $?

View file

@ -1,17 +1,18 @@
declare -a autojump_paths
autojump_paths=(
$HOME/.autojump/etc/profile.d/autojump.zsh # manual installation
$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
/usr/share/autojump/autojump.zsh # Debian and Ubuntu package
/etc/profile.d/autojump.zsh # manual installation
/etc/profile.d/autojump.sh # Gentoo installation
/usr/local/share/autojump/autojump.zsh # FreeBSD installation
/usr/pkg/share/autojump/autojump.zsh # NetBSD installation
/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)
$HOME/.autojump/etc/profile.d/autojump.zsh # manual installation
$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
/usr/share/autojump/autojump.zsh # Debian and Ubuntu package
/etc/profile.d/autojump.zsh # manual installation
/etc/profile.d/autojump.sh # Gentoo installation
/usr/local/share/autojump/autojump.zsh # FreeBSD installation
/usr/pkg/share/autojump/autojump.zsh # NetBSD installation
/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)
/etc/profiles/per-user/$USER/etc/profile.d/autojump.sh # macOS Nix, Home Manager and flakes
)
for file in $autojump_paths; do

View file

@ -1,7 +1,8 @@
# aws
This plugin provides completion support for [awscli](https://docs.aws.amazon.com/cli/latest/reference/index.html)
and a few utilities to manage AWS profiles and display them in the prompt.
This plugin provides completion support for [awscli v2](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/index.html)
and a few utilities to manage AWS profiles/regions and display them in the prompt.
[awscli v1](https://docs.aws.amazon.com/cli/latest/userguide/cliv2-migration.html) is no longer supported.
To use it, add `aws` to the plugins array in your zshrc file.
@ -12,9 +13,14 @@ plugins=(... aws)
## Plugin commands
* `asp [<profile>]`: sets `$AWS_PROFILE` and `$AWS_DEFAULT_PROFILE` (legacy) to `<profile>`.
It also sets `$AWS_EB_PROFILE` to `<profile>` for the Elastic Beanstalk CLI.
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`: 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.
* `acp [<profile>] [<mfa_token>]`: in addition to `asp` functionality, it actually changes
the profile by assuming the role specified in the `<profile>` configuration. It supports
@ -25,25 +31,36 @@ plugins=(... aws)
* `agp`: gets the current value of `$AWS_PROFILE`.
* `agr`: gets the current value of `$AWS_REGION`.
* `aws_change_access_key`: changes the AWS access key of a profile.
* `aws_profiles`: lists the available profiles in the `$AWS_CONFIG_FILE` (default: `~/.aws/config`).
Used to provide completion for the `asp` function.
* `aws_regions`: lists the available regions.
Used to provide completion for the `asr` function.
## Plugin options
* Set `SHOW_AWS_PROMPT=false` in your zshrc file if you want to prevent the plugin from modifying your RPROMPT.
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 prompt.
see the AWS profile/region prompt.
## Theme
The plugin creates an `aws_prompt_info` function that you can use in your theme, which displays
the current `$AWS_PROFILE`. It uses two variables to control how that is shown:
the current `$AWS_PROFILE` and `$AWS_REGION`. It uses four variables to control how that is shown:
* ZSH_THEME_AWS_PREFIX: sets the prefix of the AWS_PROFILE. Defaults to `<aws:`.
* ZSH_THEME_AWS_PROFILE_PREFIX: sets the prefix of the AWS_PROFILE. Defaults to `<aws:`.
* ZSH_THEME_AWS_SUFFIX: sets the suffix of the AWS_PROFILE. Defaults to `>`.
* ZSH_THEME_AWS_PROFILE_SUFFIX: sets the suffix of the AWS_PROFILE. Defaults to `>`.
* ZSH_THEME_AWS_REGION_PREFIX: sets the prefix of the AWS_REGION. Defaults to `<region:`.
* ZSH_THEME_AWS_REGION_SUFFIX: sets the suffix of the AWS_REGION. Defaults to `>`.
* ZSH_THEME_AWS_DIVIDER: sets the divider between ZSH_THEME_AWS_PROFILE_SUFFIX and ZSH_THEME_AWS_REGION_PREFIX. Defaults to ` ` (single space).
## Configuration
@ -53,7 +70,7 @@ the current `$AWS_PROFILE`. It uses two variables to control how that is shown:
Source profile credentials in `~/.aws/credentials`:
```
```ini
[source-profile-name]
aws_access_key_id = ...
aws_secret_access_key = ...
@ -61,7 +78,7 @@ aws_secret_access_key = ...
Role configuration in `~/.aws/config`:
```
```ini
[profile source-profile-name]
mfa_serial = arn:aws:iam::111111111111:mfa/myuser
region = us-east-1

View file

@ -2,10 +2,14 @@ function agp() {
echo $AWS_PROFILE
}
function agr() {
echo $AWS_REGION
}
# AWS profile selection
function asp() {
if [[ -z "$1" ]]; then
unset AWS_DEFAULT_PROFILE AWS_PROFILE AWS_EB_PROFILE
unset AWS_DEFAULT_PROFILE AWS_PROFILE AWS_EB_PROFILE AWS_PROFILE_REGION
echo AWS profile cleared.
return
fi
@ -22,11 +26,38 @@ function asp() {
export AWS_PROFILE=$1
export AWS_EB_PROFILE=$1
export AWS_PROFILE_REGION=$(aws configure get region)
if [[ "$2" == "login" ]]; then
aws sso login
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
echo AWS region cleared.
return
fi
local -a available_regions
available_regions=($(aws_regions))
if [[ -z "${available_regions[(r)$1]}" ]]; then
echo "${fg[red]}Available regions: \n$(aws_regions)"
return 1
fi
export AWS_REGION=$1
export AWS_DEFAULT_REGION=$1
}
# AWS profile switch
function acp() {
if [[ -z "$1" ]]; then
@ -135,21 +166,60 @@ function aws_change_access_key() {
return 1
fi
echo "Insert the credentials when asked."
asp "$1" || return 1
AWS_PAGER="" aws iam create-access-key
AWS_PAGER="" aws configure --profile "$1"
local profile="$1"
# Get current access key
local original_aws_access_key_id="$(aws configure get aws_access_key_id --profile $profile)"
echo "You can now safely delete the old access key running \`aws iam delete-access-key --access-key-id ID\`"
asp "$profile" || return 1
echo "Generating a new access key pair for you now."
if aws --no-cli-pager iam create-access-key; then
echo "Insert the newly generated credentials when asked."
aws --no-cli-pager configure --profile $profile
else
echo "Current access keys:"
aws --no-cli-pager iam list-access-keys
echo "Profile \"${profile}\" is currently using the $original_aws_access_key_id key. You can delete an old access key by running \`aws --profile $profile iam delete-access-key --access-key-id AccessKeyId\`"
return 1
fi
read -q "yn?Would you like to disable your previous access key (${original_aws_access_key_id}) now? "
case $yn in
[Yy]*)
echo -n "\nDisabling access key ${original_aws_access_key_id}..."
if aws --no-cli-pager iam update-access-key --access-key-id ${original_aws_access_key_id} --status Inactive; then
echo "done."
else
echo "\nFailed to disable ${original_aws_access_key_id} key."
fi
;;
*)
echo ""
;;
esac
echo "You can now safely delete the old access key by running \`aws --profile $profile iam delete-access-key --access-key-id ${original_aws_access_key_id}\`"
echo "Your current keys are:"
AWS_PAGER="" aws iam list-access-keys
aws --no-cli-pager iam list-access-keys
}
function aws_regions() {
if [[ $AWS_DEFAULT_PROFILE || $AWS_PROFILE ]];then
aws ec2 describe-regions |grep RegionName | awk -F ':' '{gsub(/"/, "", $2);gsub(/,/, "", $2);gsub(/ /, "", $2); print $2}'
else
echo "You must specify a AWS profile."
fi
}
function aws_profiles() {
aws --no-cli-pager configure list-profiles 2> /dev/null && return
[[ -r "${AWS_CONFIG_FILE:-$HOME/.aws/config}" ]] || return 1
grep --color=never -Eo '\[.*\]' "${AWS_CONFIG_FILE:-$HOME/.aws/config}" | sed -E 's/^[[:space:]]*\[(profile)?[[:space:]]*([^[:space:]]+)\][[:space:]]*$/\2/g'
}
function _aws_regions() {
reply=($(aws_regions))
}
compctl -K _aws_regions asr
function _aws_profiles() {
reply=($(aws_profiles))
}
@ -157,15 +227,25 @@ compctl -K _aws_profiles asp acp aws_change_access_key
# AWS prompt
function aws_prompt_info() {
[[ -n "$AWS_PROFILE" ]] || return
echo "${ZSH_THEME_AWS_PREFIX=<aws:}${AWS_PROFILE:gs/%/%%}${ZSH_THEME_AWS_SUFFIX=>}"
local _aws_to_show
local region="${AWS_REGION:-${AWS_DEFAULT_REGION:-$AWS_PROFILE_REGION}}"
if [[ -n "$AWS_PROFILE" ]];then
_aws_to_show+="${ZSH_THEME_AWS_PROFILE_PREFIX="<aws:"}${AWS_PROFILE}${ZSH_THEME_AWS_PROFILE_SUFFIX=">"}"
fi
if [[ -n "$region" ]]; then
[[ -n "$_aws_to_show" ]] && _aws_to_show+="${ZSH_THEME_AWS_DIVIDER=" "}"
_aws_to_show+="${ZSH_THEME_AWS_REGION_PREFIX="<region:"}${region}${ZSH_THEME_AWS_REGION_SUFFIX=">"}"
fi
echo "$_aws_to_show"
}
if [[ "$SHOW_AWS_PROMPT" != false && "$RPROMPT" != *'$(aws_prompt_info)'* ]]; then
RPROMPT='$(aws_prompt_info)'"$RPROMPT"
fi
# Load awscli completions
# AWS CLI v2 comes with its own autocompletion. Check if that is there, otherwise fall back
@ -210,3 +290,4 @@ else
[[ -r $_aws_zsh_completer_path ]] && source $_aws_zsh_completer_path
unset _aws_zsh_completer_path _brew_prefix
fi

49
plugins/azure/README.md Normal file
View file

@ -0,0 +1,49 @@
# azure
This plugin provides completion support for [azure cli](https://docs.microsoft.com/en-us/cli/azure/)
and a few utilities to manage azure subscriptions and display them in the prompt.
To use it, add `azure` to the plugins array in your zshrc file.
```zsh
plugins=(... azure)
```
## Plugin commands
* `az_subscriptions`: lists the available subscriptions in the `AZURE_CONFIG_DIR` (default: `~/.azure/`).
Used to provide completion for the `azss` function.
* `azgs`: gets the current value of `$azure_subscription`.
* `azss [<subscription>]`: sets the `$azure_subscription`.
NOTE : because azure keeps the state of active subscription in ${AZURE_CONFIG_DIR:-$HOME/.azure/azureProfile.json}, the prompt command requires `jq` to be enabled to parse the file. If jq is not in the path the prompt will show nothing
## Theme
The plugin creates an `azure_prompt_info` function that you can use in your theme, which displays
the current `$azure_subscription`. It uses two variables to control how that is shown:
- ZSH_THEME_AZURE_PREFIX: sets the prefix of the azure_subscription. Defaults to `<az:`.
- ZSH_THEME_azure_SUFFIX: sets the suffix of the azure_subscription. Defaults to `>`.
```
RPROMPT='$(azure_prompt_info)'
```
## Develop
On ubuntu get a working environment with :
` docker run -it -v $(pwd):/mnt -w /mnt ubuntu bash`
```
apt install -y curl jq zsh git vim
sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
curl -sL https://aka.ms/InstallAzureCLIDeb | bash
```

View file

@ -0,0 +1,60 @@
# AZ Get Subscriptions
function azgs() {
az account show --output tsv --query 'name' 2>/dev/null
}
# AZ Subscription Selection
alias azss="az account set --subscription"
function az_subscriptions() {
az account list --all --output tsv --query '[*].name' 2> /dev/null
}
function _az_subscriptions() {
reply=($(az_subscriptions))
}
compctl -K _az_subscriptions azss
# Azure prompt
function azure_prompt_info() {
[[ ! -f "${AZURE_CONFIG_DIR:-$HOME/.azure}/azureProfile.json" ]] && return
# azgs is too expensive, if we have jq, we enable the prompt
(( $+commands[jq] )) || return 1
azgs=$(jq -r '.subscriptions[] | select(.isDefault==true) .name' "${AZURE_CONFIG_DIR:-$HOME/.azure}/azureProfile.json")
echo "${ZSH_THEME_AZURE_PREFIX:=<az:}${azgs}${ZSH_THEME_AZURE_SUFFIX:=>}"
}
# Load az completions
function _az-homebrew-installed() {
# check if Homebrew is installed
(( $+commands[brew] )) || return 1
# if so, we assume it's default way to install brew
if [[ ${commands[brew]:t2} == bin/brew ]]; then
_brew_prefix="${commands[brew]:h:h}" # remove trailing /bin/brew
else
# ok, it is not in the default prefix
# this call to brew is expensive (about 400 ms), so at least let's make it only once
_brew_prefix=$(brew --prefix)
fi
}
# get az.completion.sh location from $PATH
_az_zsh_completer_path="$commands[az_zsh_completer.sh]"
# otherwise check common locations
if [[ -z $_az_zsh_completer_path ]]; then
# Homebrew
if _az-homebrew-installed; then
_az_zsh_completer_path=$_brew_prefix/etc/bash_completion.d/az
# Linux
else
_az_zsh_completer_path=/etc/bash_completion.d/azure-cli
fi
fi
[[ -r $_az_zsh_completer_path ]] && autoload -U +X bashcompinit && bashcompinit && source $_az_zsh_completer_path
unset _az_zsh_completer_path _brew_prefix

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() {
@ -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,4 +1,4 @@
#compdef bazel
#compdef bazel bazelisk
# Copyright 2015 The Bazel Authors. All rights reserved.
#

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,29 @@ 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.
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

@ -1,93 +1,141 @@
#!/usr/bin/env zsh
## setup ##
## Setup
[[ -o interactive ]] || return #interactive only!
zmodload zsh/datetime || { print "can't load zsh/datetime"; return } # faster than date()
autoload -Uz add-zsh-hook || { print "can't add zsh hook!"; return }
[[ -o interactive ]] || return # don't load on non-interactive shells
[[ -z "$SSH_CLIENT" && -z "$SSH_TTY" ]] || return # don't load on a SSH connection
(( ${+bgnotify_threshold} )) || bgnotify_threshold=5 #default 10 seconds
zmodload zsh/datetime # faster than `date`
## definitions ##
## Zsh Hooks
if ! (type bgnotify_formatted | grep -q 'function'); then ## allow custom function override
function bgnotify_formatted { ## args: (exit_status, command, elapsed_seconds)
elapsed="$(( $3 % 60 ))s"
(( $3 >= 60 )) && elapsed="$((( $3 % 3600) / 60 ))m $elapsed"
(( $3 >= 3600 )) && elapsed="$(( $3 / 3600 ))h $elapsed"
[ $1 -eq 0 ] && bgnotify "#win (took $elapsed)" "$2" || bgnotify "#fail (took $elapsed)" "$2"
}
fi
currentAppId () {
if (( $+commands[osascript] )); then
osascript -e 'tell application (path to frontmost application as text) to id' 2>/dev/null
fi
}
currentWindowId () {
if hash osascript 2>/dev/null; then #osx
osascript -e 'tell application (path to frontmost application as text) to id of front window' 2&> /dev/null || echo "0"
elif (hash notify-send 2>/dev/null || hash kdialog 2>/dev/null); then #ubuntu!
xprop -root 2> /dev/null | awk '/NET_ACTIVE_WINDOW/{print $5;exit} END{exit !$5}' || echo "0"
else
echo $EPOCHSECONDS #fallback for windows
fi
}
bgnotify () { ## args: (title, subtitle)
if hash terminal-notifier 2>/dev/null; then #osx
local term_id="$bgnotify_appid"
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
## now call terminal-notifier, (hopefully with $term_id!)
if [[ -z "$term_id" ]]; then
terminal-notifier -message "$2" -title "$1" >/dev/null
else
terminal-notifier -message "$2" -title "$1" -activate "$term_id" -sender "$term_id" >/dev/null
fi
elif hash growlnotify 2>/dev/null; then #osx growl
growlnotify -m "$1" "$2"
elif hash notify-send 2>/dev/null; then #ubuntu gnome!
notify-send "$1" "$2"
elif hash kdialog 2>/dev/null; then #ubuntu kde!
kdialog --title "$1" --passivepopup "$2" 5
elif hash notifu 2>/dev/null; then #cygwyn support!
notifu /m "$2" /p "$1"
fi
}
## Zsh hooks ##
bgnotify_begin() {
function bgnotify_begin {
bgnotify_timestamp=$EPOCHSECONDS
bgnotify_lastcmd="${1:-$2}"
bgnotify_appid="$(currentAppId)"
bgnotify_windowid=$(currentWindowId)
}
bgnotify_end() {
didexit=$?
elapsed=$(( EPOCHSECONDS - bgnotify_timestamp ))
past_threshold=$(( elapsed >= bgnotify_threshold ))
if (( bgnotify_timestamp > 0 )) && (( past_threshold )); then
if [[ $(currentAppId) != "$bgnotify_appid" || $(currentWindowId) != "$bgnotify_windowid" ]]; then
print -n "\a"
bgnotify_formatted "$didexit" "$bgnotify_lastcmd" "$elapsed"
fi
function bgnotify_end {
{
local exit_status=$?
local elapsed=$(( EPOCHSECONDS - bgnotify_timestamp ))
# check time elapsed
[[ $bgnotify_timestamp -gt 0 ]] || return 0
[[ $elapsed -ge $bgnotify_threshold ]] || return 0
# check if Terminal app is not active
[[ $(bgnotify_appid) != "$bgnotify_termid" ]] || return 0
bgnotify_formatted "$exit_status" "$bgnotify_lastcmd" "$elapsed"
} always {
bgnotify_timestamp=0
}
}
autoload -Uz add-zsh-hook
add-zsh-hook preexec bgnotify_begin
add-zsh-hook precmd bgnotify_end
## Functions
# allow custom function override
(( ${+functions[bgnotify_formatted]} )) || \
function bgnotify_formatted {
local exit_status=$1
local cmd="$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"
[[ $bgnotify_bell = true ]] && printf '\a' # beep sound
if [[ $exit_status -eq 0 ]]; then
bgnotify "#win (took $elapsed)" "$cmd"
else
bgnotify "#fail (took $elapsed)" "$cmd"
fi
bgnotify_timestamp=0 #reset it to 0!
}
## only enable if a local (non-ssh) connection
if [ -z "$SSH_CLIENT" ] && [ -z "$SSH_TTY" ]; then
add-zsh-hook preexec bgnotify_begin
add-zsh-hook precmd bgnotify_end
fi
function bgnotify_appid {
if (( ${+commands[osascript]} )); 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_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
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" -sender "$term_id"} &>/dev/null
elif (( ${+commands[growlnotify]} )); then # macOS growl
growlnotify -m "$title" "$message"
elif (( ${+commands[notify-send]} )); then
notify-send "$title" "$message" ${=icon:+--icon "$icon"}
elif (( ${+commands[kdialog]} )); then # KDE
kdialog --title "$title" --passivepopup "$message" 5
elif (( ${+commands[notifu]} )); then # cygwin
notifu /m "$message" /p "$title" ${=icon:+/i "$icon"}
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}
# bgnotify_appid is slow in macOS and the terminal ID won't change, so cache it at startup
bgnotify_termid="$(bgnotify_appid)"

View file

@ -10,25 +10,34 @@ plugins=(... brew)
## Shellenv
This plugin also executes `brew shellenv` at plugin load to set up many useful variables, such as `HOMEBREW_PREFIX` or `HOMEBREW_REPOSITORY`.
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. |
| `bcubo` | `brew update && brew outdated --cask` | Update Homebrew data, then list outdated casks. |
| `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. |
| `bubo` | `brew update && brew outdated` | Update Homebrew data, then list outdated formulae and casks. |
| `bubu` | `bubo && bubc` | Do the last two operations above. |
| `buf` | `brew upgrade --formula` | Upgrade only formulas (not casks). |
| Alias | Command | Description |
| -------- | --------------------------------------- | ------------------------------------------------------------------- |
| `bcubc` | `brew upgrade --cask && brew cleanup` | Update outdated casks, then run cleanup. |
| `bcubo` | `brew update && brew outdated --cask` | Update Homebrew data, then list outdated casks. |
| `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. |
| `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). |
| `buz` | `brew uninstall --zap` | Remove all files associated with a cask. |
## Completion
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.
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.

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"
@ -10,30 +15,41 @@ if (( ! $+commands[brew] )); then
else
return
fi
# Only add Homebrew installation to PATH, MANPATH, and INFOPATH if brew is
# not already on the path, to prevent duplicate entries. This aligns with
# the behavior of the brew installer.sh post-install steps.
eval "$("$BREW_LOCATION" shellenv)"
unset BREW_LOCATION
fi
if [[ -z "$HOMEBREW_PREFIX" ]]; then
if [[ -z $BREW_LOCATION ]]; then
eval "$(brew shellenv)"
else
eval "$("$BREW_LOCATION" shellenv)"
fi
# Maintain compatability 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)"
fi
unset BREW_LOCATION
if [[ -d "$HOMEBREW_PREFIX/share/zsh/site-functions" ]]; then
fpath+=("$HOMEBREW_PREFIX/share/zsh/site-functions")
fi
alias bcubc='brew upgrade --cask && brew cleanup'
alias bcubo='brew update && brew outdated --cask'
alias bcubc='brew upgrade --cask && brew cleanup'
alias brewp='brew pin'
alias brewsp='brew list --pinned'
alias bubc='brew upgrade && brew cleanup'
alias bugbc='brew upgrade --greedy && brew cleanup'
alias bubo='brew update && brew outdated'
alias bubu='bubo && bubc'
alias buf='brew upgrade --formula'
alias bubug='bubo && bugbc'
alias bfu='brew upgrade --formula'
alias buz='brew uninstall --zap'
function brews() {
local formulae="$(brew leaves | xargs brew deps --installed --for-each)"
local casks="$(brew list --cask)"
local casks="$(brew list --cask 2>/dev/null)"
local blue="$(tput setaf 4)"
local bold="$(tput bold)"

View file

@ -0,0 +1,26 @@
# Bridgetown plugin
This plugin adds some aliases and autocompletion for common [Bridgetown](https://bridgetownrb.com/) commands.
To use it, add `bridgetown` to the plugins array in your zshrc file:
```zsh
plugins=(... bridgetown)
```
## Aliases
| Alias | Command |
|-------|----------------------------|
| br | `bridgetown` |
| bra | `bin/bridgetown apply` |
| brb | `bin/bridgetown build` |
| brc | `bin/bridgetown console` |
| brclean | `bin/bridgetown clean` |
| brd | `bin/bridgetown deploy` |
| brdoc | `bin/bridgetown doctor` |
| brh | `bin/bridgetown help` |
| brn | `bridgetown new` |
| brp | `bridgetown plugins` |
| brpl | `bridgetown plugins list` |
| brs | `bin/bridgetown start` |

View file

@ -0,0 +1,12 @@
alias br='bridgetown'
alias bra='bin/bridgetown apply'
alias brb='bin/bridgetown build'
alias brc='bin/bridgetown console'
alias brclean='bin/bridgetown clean'
alias brd='bin/bridgetown deploy'
alias brdoc='bin/bridgetown doctor'
alias brh='bin/bridgetown help'
alias brn='bridgetown new'
alias brp='bridgetown plugins'
alias brpl='bridgetown plugins list'
alias brs='bin/bridgetown start'

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
bun completions >| "$ZSH_CACHE_DIR/completions/_bun" &|

View file

@ -1,10 +1,10 @@
# CakePHP 3 basic command completion
_cakephp3_get_command_list () {
bin/cake Completion commands
bin/cake completion commands
}
_cakephp3_get_sub_command_list () {
bin/cake Completion subcommands ${words[2]}
bin/cake completion subcommands ${words[2]}
}
_cakephp3_get_3rd_argument () {
@ -34,5 +34,5 @@ compdef _cakephp3 cake
#Alias
alias c3='bin/cake'
alias c3cache='bin/cake orm_cache clear'
alias c3cache='bin/cake schema_cache clear'
alias c3migrate='bin/cake migrations migrate'

View file

@ -1,6 +1,6 @@
#compdef coffee
# ------------------------------------------------------------------------------
# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users
# Copyright (c) 2011 GitHub zsh-users - https://github.com/zsh-users
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without

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

@ -23,7 +23,7 @@ colorize_check_requirements() {
if [[ ${available_tools[(Ie)$ZSH_COLORIZE_TOOL]} -eq 0 ]]; then
echo "ZSH_COLORIZE_TOOL '$ZSH_COLORIZE_TOOL' not recognized. Available options are 'pygmentize' and 'chroma'." >&2
return 1
elif (( $+commands["$ZSH_COLORIZE_TOOL"] )); then
elif ! (( $+commands[$ZSH_COLORIZE_TOOL] )); then
echo "Package '$ZSH_COLORIZE_TOOL' is not installed!" >&2
return 1
fi

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"

29
plugins/dbt/README.md Normal file
View file

@ -0,0 +1,29 @@
# 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:
```
plugins=(... dbt)
```
## Aliases
| Alias | Command | Description |
| ------ | ------------------------------------------------ | ---------------------------------------------------- |
| dbtlm | `dbt ls -s state:modified` | List modified models only |
| dbtrm | `dbt run -s state:modified` | Run modified models only |
| dbttm | `dbt test -m state:modified` | Test modified models only |
| dbtrtm | `dbtrm && dbttm` | Run and test modified models only |
| dbtrs | `dbt clean; dbt deps; dbt seed` | Re-seed data |
| dbtfrt | `dbtrs; dbt run --full-refresh; dbt test` | Perform a full fresh run with tests |
| dbtcds | `dbt docs generate; dbt docs serve` | Generate docs without compiling |
| dbtds | `dbt docs generate --no-compile; dbt docs serve` | Generate and serve docs skipping doc. re-compilation |
## Maintainer
### [msempere](https://github.com/msempere)

View file

@ -0,0 +1,23 @@
# list modified models only
alias dbtlm="dbt ls -s state:modified"
# run modified models only
alias dbtrm="dbt run -s state:modified"
# test modified models only
alias dbttm="dbt test -m state:modified"
# run and test modified models only
alias dbtrtm="dbtrm && dbttm"
# re-seed data
alias dbtrs="dbt clean; dbt deps; dbt seed"
# perform a full fresh run with tests
alias dbtfrt="dbtrs; dbt run --full-refresh; dbt test"
# generate and serve docs
alias dbtcds="dbt docs generate; dbt docs serve"
# generate and serve docs skipping doc. re-compilation
alias dbtds="dbt docs generate --no-compile; dbt docs serve"

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
@ -30,26 +35,25 @@ Set `$apt_pref` and `$apt_upgr` to whatever command you want (before sourcing Oh
## Superuser Operations Aliases
| Alias | Command | Description |
| -------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `aac` | `sudo $apt_pref autoclean` | Clears out the local repository of retrieved package files |
| `aar` | `sudo $apt_pref autoremove` | Removes packages installed automatically that are no longer needed |
| `abd` | `sudo $apt_pref build-dep` | Installs all dependencies for building packages |
| `ac` | `sudo $apt_pref clean` | Clears out the local repository of retrieved package files except lock files |
| `ad` | `sudo $apt_pref update` | Updates the package lists for upgrades for packages |
| `adg` | `sudo $apt_pref update && sudo $apt_pref $apt_upgr` | Update and upgrade packages |
| `ads` | `sudo apt-get dselect-upgrade` | Installs packages from list and removes all not in the list |
| `adu` | `sudo $apt_pref update && sudo $apt_pref dist-upgrade` | Smart upgrade that handles dependencies |
| `afu` | `sudo apt-file update` | Update the files in packages |
| `ai` | `sudo $apt_pref install` | Command-line tool to install package |
| `ail` | `sed -e 's/ */ /g' -e 's/ *//' \| cut -s -d ' ' -f 1 \| xargs sudo $apt_pref install` | Install all packages given on the command line while using only the first word of each line |
| `alu` | `sudo apt update && apt list -u && sudo apt upgrade` | Update, list and upgrade packages |
| `ap` | `sudo $apt_pref purge` | Removes packages along with configuration files |
| `ar` | `sudo $apt_pref remove` | Removes packages, keeps the configuration files |
| `au` | `sudo $apt_pref $apt_upgr` | Install package upgrades |
| `di` | `sudo dpkg -i` | Install all .deb files in the current directory |
| `dia` | `sudo dpkg -i ./*.deb` | Install all .deb files in the current directory |
| `kclean` | `sudo aptitude remove -P ?and(~i~nlinux-(ima\|hea) ?not(~n$(uname -r)))` | Remove ALL kernel images and headers EXCEPT the one in use |
| Alias | Command | Description |
| -------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `aac` | `sudo $apt_pref autoclean` | Clears out the local repository of retrieved package files |
| `aar` | `sudo $apt_pref autoremove` | Removes packages installed automatically that are no longer needed |
| `abd` | `sudo $apt_pref build-dep` | Installs all dependencies for building packages |
| `ac` | `sudo $apt_pref clean` | Clears out the local repository of retrieved package files except lock files |
| `ad` | `sudo $apt_pref update` | Updates the package lists for upgrades for packages |
| `adg` | `sudo $apt_pref update && sudo $apt_pref $apt_upgr` | Update and upgrade packages |
| `ads` | `sudo apt-get dselect-upgrade` | Installs packages from list and removes all not in the list |
| `adu` | `sudo $apt_pref update && sudo $apt_pref dist-upgrade` | Smart upgrade that handles dependencies |
| `afu` | `sudo apt-file update` | Update the files in packages |
| `ai` | `sudo $apt_pref install` | Command-line tool to install package |
| `ail` | `sed -e 's/ */ /g' -e 's/ *//' \| cut -s -d ' ' -f 1 \| xargs sudo $apt_pref install` | Install all packages given on the command line while using only the first word of each line |
| `alu` | `sudo apt update && apt list -u && sudo apt upgrade` | Update, list and upgrade packages |
| `ap` | `sudo $apt_pref purge` | Removes packages along with configuration files |
| `au` | `sudo $apt_pref $apt_upgr` | Install package upgrades |
| `di` | `sudo dpkg -i` | Install all .deb files in the current directory |
| `dia` | `sudo dpkg -i ./*.deb` | Install all .deb files in the current directory |
| `kclean` | `sudo aptitude remove -P ?and(~i~nlinux-(ima\|hea) ?not(~n$(uname -r)))` | Remove ALL kernel images and headers EXCEPT the one in use |
## Aliases - Commands using `su`

View file

@ -51,11 +51,10 @@ if [[ $use_sudo -eq 1 ]]; then
alias au="sudo $apt_pref $apt_upgr"
alias ai="sudo $apt_pref install"
# Install all packages given on the command line while using only the first word of each line:
# acs ... | ail
# acse ... | ail
alias ail="sed -e 's/ */ /g' -e 's/ *//' | cut -s -d ' ' -f 1 | xargs sudo $apt_pref install"
alias ap="sudo $apt_pref purge"
alias ar="sudo $apt_pref remove"
alias aar="sudo $apt_pref autoremove"
# apt-get only
@ -98,11 +97,6 @@ else
print "$cmd"
eval "$cmd"
}
function ar() {
cmd="su -lc '$apt_pref remove $@' root"
print "$cmd"
eval "$cmd"
}
function aar() {
cmd="su -lc '$apt_pref autoremove $@' root"
print "$cmd"
@ -147,7 +141,6 @@ apt_pref_compdef au "$apt_upgr"
apt_pref_compdef ai "install"
apt_pref_compdef ail "install"
apt_pref_compdef ap "purge"
apt_pref_compdef ar "remove"
apt_pref_compdef aar "autoremove"
apt_pref_compdef ads "dselect-upgrade"

View file

@ -4,16 +4,17 @@ This plugin sets up completion and aliases for [Deno](https://deno.land).
## Aliases
| Alias | Full command |
| ----- | ---------------- |
| db | deno bundle |
| dc | deno compile |
| dca | deno cache |
| dfmt | deno fmt |
| dh | deno help |
| dli | deno lint |
| drn | deno run |
| drA | deno run -A |
| drw | deno run --watch |
| dts | deno test |
| dup | deno upgrade |
| Alias | Full command |
| ----- | ------------------- |
| db | deno bundle |
| dc | deno compile |
| dca | deno cache |
| dfmt | deno fmt |
| dh | deno help |
| dli | deno lint |
| drn | deno run |
| drA | deno run -A |
| drw | deno run --watch |
| dru | deno run --unstable |
| dts | deno test |
| dup | deno upgrade |

View file

@ -8,6 +8,7 @@ alias dli='deno lint'
alias drn='deno run'
alias drA='deno run -A'
alias drw='deno run --watch'
alias dru='deno run --unstable'
alias dts='deno test'
alias dup='deno upgrade'

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

@ -19,15 +19,17 @@ export DIRHISTORY_SIZE=30
# Returns the element if the array was not empty,
# otherwise returns empty string.
function pop_past() {
typeset -g $1="${dirhistory_past[$#dirhistory_past]}"
setopt localoptions no_ksh_arrays
if [[ $#dirhistory_past -gt 0 ]]; then
typeset -g $1="${dirhistory_past[$#dirhistory_past]}"
dirhistory_past[$#dirhistory_past]=()
fi
}
function pop_future() {
typeset -g $1="${dirhistory_future[$#dirhistory_future]}"
setopt localoptions no_ksh_arrays
if [[ $#dirhistory_future -gt 0 ]]; then
typeset -g $1="${dirhistory_future[$#dirhistory_future]}"
dirhistory_future[$#dirhistory_future]=()
fi
}
@ -35,6 +37,7 @@ function pop_future() {
# Push a new element onto the end of dirhistory_past. If the size of the array
# is >= DIRHISTORY_SIZE, the array is shifted
function push_past() {
setopt localoptions no_ksh_arrays
if [[ $#dirhistory_past -ge $DIRHISTORY_SIZE ]]; then
shift dirhistory_past
fi
@ -44,6 +47,7 @@ function push_past() {
}
function push_future() {
setopt localoptions no_ksh_arrays
if [[ $#dirhistory_future -ge $DIRHISTORY_SIZE ]]; then
shift dirhistory_future
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

@ -1,6 +1,6 @@
# Dnote Plugin
This plugin adds auto-completion for [Dnote](https://dnote.io) project.
This plugin adds auto-completion for [Dnote](https://www.getdnote.com/), a simple command line notebook.
To use it, add `dnote` to the plugins array in your zshrc file:

View file

@ -11,22 +11,24 @@ 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 |
| dcps | `docker-compose ps` | List containers |
| dcrestart | `docker-compose restart` | Restart container |
| dcrm | `docker-compose rm` | Remove container |
| dcr | `docker-compose run` | Run a command in container |
| dcstop | `docker-compose stop` | Stop a container |
| dcup | `docker-compose up` | Build, (re)create, start, and attach to containers for a service |
| dcupb | `docker-compose up --build` | Same as `dcup`, but build images before starting containers |
| dcupd | `docker-compose up -d` | Same as `dcup`, but starts as daemon |
| 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 |
| dcpull | `docker-compose pull` | Pull image of a service |
| dcstart | `docker-compose start` | Start a container |
| dck | `docker-compose kill` | Kills containers |
| 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 |
| dcps | `docker-compose ps` | List containers |
| dcrestart | `docker-compose restart` | Restart container |
| dcrm | `docker-compose rm` | Remove container |
| dcr | `docker-compose run` | Run a command in container |
| dcstop | `docker-compose stop` | Stop a container |
| dcup | `docker-compose up` | Build, (re)create, start, and attach to containers for a service |
| dcupb | `docker-compose up --build` | Same as `dcup`, but build images before starting containers |
| dcupd | `docker-compose up -d` | Same as `dcup`, but starts as daemon |
| dcupdb | `docker-compose up -d --build` | Same as `dcup`, but build images before starting containers and starts as daemon |
| 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

@ -12,9 +12,11 @@ alias dcstop="$dccmd stop"
alias dcup="$dccmd up"
alias dcupb="$dccmd up --build"
alias dcupd="$dccmd up -d"
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

@ -335,9 +335,9 @@ _docker-machine() {
'--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]' \
'--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]' \
'--bugsnag-api-token[Bugsnag API token for crash reporting]' \
'(- :)'{-v,--version}'[Print the version]' \
"(-): :->command" \
"(-)*:: :->option-or-argument" && ret=0

View file

@ -13,18 +13,15 @@ https://github.com/docker/cli/blob/master/contrib/completion/zsh/_docker
## Settings
By default, the completion doesn't allow option-stacking, meaning if you try to
complete `docker run -it <TAB>` it won't work, because you're _stacking_ the
`-i` and `-t` options.
By default, the completion doesn't allow option-stacking, meaning if you try to complete
`docker run -it <TAB>` it won't work, because you're _stacking_ the `-i` and `-t` options.
[You can enable it](https://github.com/docker/cli/commit/b10fb43048) by **adding
the lines below to your zshrc file**, but be aware of the side effects:
[You can enable it](https://github.com/docker/cli/commit/b10fb43048) by **adding the lines below to your zshrc
file**, but be aware of the side effects:
> This enables Zsh to understand commands like `docker run -it
> ubuntu`. However, by enabling this, this also makes Zsh complete
> `docker run -u<tab>` with `docker run -uapprox` which is not valid. The
> users have to put the space or the equal sign themselves before trying
> to complete.
> This enables Zsh to understand commands like `docker run -it ubuntu`. However, by enabling this, this also
> makes Zsh complete `docker run -u<tab>` with `docker run -uapprox` which is not valid. The users have to put
> the space or the equal sign themselves before trying to complete.
>
> Therefore, this behavior is disabled by default. To enable it:
>
@ -33,41 +30,49 @@ the lines below to your zshrc file**, but be aware of the side effects:
> zstyle ':completion:*:*:docker-*:*' option-stacking yes
> ```
### Use old-style completion
If the current completion does not work well for you, you can enable legacy completion instead with the
following setting. See https://github.com/ohmyzsh/ohmyzsh/issues/11789 for more information.
```zsh
zstyle ':omz:plugins:docker' legacy-completion yes
```
## Aliases
| Alias | Command | Description |
| :------ | :-------------------------- | :--------------------------------------------------------------------------------------- |
| dbl | `docker build` | Build an image from a Dockerfile |
| dcin | `docker container inspect` | Display detailed information on one or more containers |
| dlo | `docker container logs` | Fetch the logs of a docker container |
| dcls | `docker container ls` | List all the running docker containers |
| dclsa | `docker container ls -a` | List all running and stopped containers |
| dpo | `docker container port` | List port mappings or a specific mapping for the container |
| dpu | `docker pull` | Pull an image or a repository from a registry |
| dr | `docker container run` | Create a new container and start it using the specified command |
| drit | `docker container run -it` | Create a new container and start it in an interactive shell |
| drm | `docker container rm` | Remove the specified container(s) |
| drm! | `docker container rm -f` | Force the removal of a running container (uses SIGKILL) |
| dst | `docker container start` | Start one or more stopped containers |
| dstp | `docker container stop` | Stop one or more running containers |
| dtop | `docker top` | Display the running processes of a container |
| dxc | `docker container exec` | Run a new command in a running container |
| dxcit | `docker container exec -it` | Run a new command in a running container in an interactive shell |
| | | **Docker Images** |
| dib | `docker image build` | Build an image from a Dockerfile (same as docker build) |
| dii | `docker image inspect` | Display detailed information on one or more images |
| dils | `docker image ls` | List docker images |
| dipu | `docker image push` | Push an image or repository to a remote registry |
| dirm | `docker image rm` | Remove one or more images |
| dit | `docker image tag` | Add a name and tag to a particular image |
| | | **Docker Network** |
| dnc | `docker network create` | Create a new network |
| dncn | `docker network connect` | Connect a container to a network |
| dndcn | `docker network disconnect` | Disconnect a container from a network |
| dni | `docker network inspect` | Return information about one or more networks |
| dnls | `docker network ls` | List all networks the engine daemon knows about, including those spanning multiple hosts |
| dnrm | `docker network rm` | Remove one or more networks |
| | | **Docker Volume** |
| dvi | `docker volume inspect` | Display detailed information about one or more volumes |
| dvls | `docker volume ls` | List all the volumes known to docker |
| dvprune | `docker volume prune` | Cleanup dangling volumes |
| Alias | Command | Description |
| :------ | :---------------------------- | :--------------------------------------------------------------------------------------- |
| dbl | `docker build` | Build an image from a Dockerfile |
| dcin | `docker container inspect` | Display detailed information on one or more containers |
| dcls | `docker container ls` | List all the running docker containers |
| dclsa | `docker container ls -a` | List all running and stopped containers |
| dib | `docker image build` | Build an image from a Dockerfile (same as docker build) |
| dii | `docker image inspect` | Display detailed information on one or more images |
| dils | `docker image ls` | List docker images |
| dipu | `docker image push` | Push an image or repository to a remote registry |
| dirm | `docker image rm` | Remove one or more images |
| dit | `docker image tag` | Add a name and tag to a particular image |
| dlo | `docker container logs` | Fetch the logs of a docker container |
| dnc | `docker network create` | Create a new network |
| dncn | `docker network connect` | Connect a container to a network |
| dndcn | `docker network disconnect` | Disconnect a container from a network |
| dni | `docker network inspect` | Return information about one or more networks |
| dnls | `docker network ls` | List all networks the engine daemon knows about, including those spanning multiple hosts |
| dnrm | `docker network rm` | Remove one or more networks |
| dpo | `docker container port` | List port mappings or a specific mapping for the container |
| dpu | `docker pull` | Pull an image or a repository from a registry |
| dr | `docker container run` | Create a new container and start it using the specified command |
| drit | `docker container run -it` | Create a new container and start it in an interactive shell |
| drm | `docker container rm` | Remove the specified container(s) |
| drm! | `docker container rm -f` | Force the removal of a running container (uses SIGKILL) |
| dst | `docker container start` | Start one or more stopped containers |
| drs | `docker container restart` | Restart one or more containers |
| dsta | `docker stop $(docker ps -q)` | Stop all running containers |
| dstp | `docker container stop` | Stop one or more running containers |
| dtop | `docker top` | Display the running processes of a container |
| dvi | `docker volume inspect` | Display detailed information about one or more volumes |
| dvls | `docker volume ls` | List all the volumes known to docker |
| dvprune | `docker volume prune` | Cleanup dangling volumes |
| dxc | `docker container exec` | Run a new command in a running container |
| dxcit | `docker container exec -it` | Run a new command in a running container in an interactive shell |

View file

@ -567,7 +567,7 @@ __docker_container_commands() {
"cp:Copy files/folders between a container and the local filesystem"
"create:Create a new container"
"diff:Inspect changes on a container's filesystem"
"exec:Run a command in a running container"
"exec:Execute a command in a running container"
"export:Export a container's filesystem as a tar archive"
"inspect:Display detailed information on one or more containers"
"kill:Kill one or more running containers"
@ -579,7 +579,7 @@ __docker_container_commands() {
"rename:Rename a container"
"restart:Restart one or more containers"
"rm:Remove one or more containers"
"run:Run a command in a new container"
"run:Create and run a new container from an image"
"start:Start one or more stopped containers"
"stats:Display a live stream of container(s) resource usage statistics"
"stop:Stop one or more running containers"
@ -602,6 +602,7 @@ __docker_container_subcommand() {
opts_create_run=(
"($help -a --attach)"{-a=,--attach=}"[Attach to stdin, stdout or stderr]:device:(STDIN STDOUT STDERR)"
"($help)*--add-host=[Add a custom host-to-IP mapping]:host\:ip mapping: "
"($help)*--annotation=[Add an annotation to the container (passed through to the OCI runtime)]:annotations: "
"($help)*--blkio-weight-device=[Block IO (relative device weight)]:device:Block IO weight: "
"($help)*--cap-add=[Add Linux capabilities]:capability: "
"($help)*--cap-drop=[Drop Linux capabilities]:capability: "
@ -650,6 +651,7 @@ __docker_container_subcommand() {
"($help)*"{-p=,--publish=}"[Expose a container's port to the host]:port:_ports"
"($help)--pid=[PID namespace to use]:PID namespace:__docker_complete_pid"
"($help)--privileged[Give extended privileges to this container]"
"($help -q --quiet)"{-q,--quiet}"[Suppress the pull output]"
"($help)--read-only[Mount the container's root filesystem as read only]"
"($help)*--security-opt=[Security options]:security option: "
"($help)*--shm-size=[Size of '/dev/shm' (format is '<number><unit>')]:shm size: "
@ -661,7 +663,7 @@ __docker_container_subcommand() {
"($help)*--ulimit=[ulimit options]:ulimit: "
"($help)--userns=[Container user namespace]:user namespace:(host)"
"($help)--tmpfs[mount tmpfs]"
"($help)*-v[Bind mount a volume]:volume: "
"($help)*-v[Bind mount a volume]:volume:_directories -W / -P '/' -S '\:' -r '/ '"
"($help)--volume-driver=[Optional volume driver for the container]:volume driver:(local)"
"($help)*--volumes-from=[Mount volumes from the specified container]:volume: "
"($help -w --workdir)"{-w=,--workdir=}"[Working directory inside the container]:directory:_directories"
@ -802,7 +804,7 @@ __docker_container_subcommand() {
"($help -a --all)"{-a,--all}"[Show all containers]" \
"($help)--before=[Show only container created before...]:containers:__docker_complete_containers" \
"($help)*"{-f=,--filter=}"[Filter values]:filter:__docker_complete_ps_filters" \
"($help)--format=[Pretty-print containers using a Go template]:template: " \
"($help)--format=[Format the output using the given Go template]:template: " \
"($help -l --latest)"{-l,--latest}"[Show only the latest created container]" \
"($help -n --last)"{-n=,--last=}"[Show n last created containers (includes all states)]:n:(1 5 10 25 50)" \
"($help)--no-trunc[Do not truncate output]" \
@ -907,7 +909,7 @@ __docker_container_subcommand() {
_arguments $(__docker_arguments) \
$opts_help \
"($help -a --all)"{-a,--all}"[Show all containers (default shows just running)]" \
"($help)--format=[Pretty-print images using a Go template]:template: " \
"($help)--format=[Format the output using the given Go template]:template: " \
"($help)--no-stream[Disable streaming stats and only pull the first result]" \
"($help)--no-trunc[Do not truncate output]" \
"($help -)*:containers:__docker_complete_running_containers" && ret=0
@ -973,8 +975,8 @@ __docker_image_commands() {
"load:Load an image from a tar archive or STDIN"
"ls:List images"
"prune:Remove unused images"
"pull:Pull an image or a repository from a registry"
"push:Push an image or a repository to a registry"
"pull:Download an image from a registry"
"push:Upload an image to a registry"
"rm:Remove one or more images"
"save:Save one or more images to a tar archive (streamed to STDOUT by default)"
"tag:Tag an image into a repository"
@ -1060,7 +1062,7 @@ __docker_image_subcommand() {
"($help -a --all)"{-a,--all}"[Show all images]" \
"($help)--digests[Show digests]" \
"($help)*"{-f=,--filter=}"[Filter values]:filter:__docker_complete_images_filters" \
"($help)--format=[Pretty-print images using a Go template]:template: " \
"($help)--format=[Format the output using the given Go template]:template: " \
"($help)--no-trunc[Do not truncate output]" \
"($help -q --quiet)"{-q,--quiet}"[Only show image IDs]" \
"($help -): :__docker_complete_repositories" && ret=0
@ -1082,7 +1084,7 @@ __docker_image_subcommand() {
(push)
_arguments $(__docker_arguments) \
$opts_help \
"($help -a --all-tags)"{-a,--all-tags}"[Push all tagged images in the repository]" \
"($help -a --all-tags)"{-a,--all-tags}"[Push all tags of an image to the repository]" \
"($help)--disable-content-trust[Skip image signing]" \
"($help -): :__docker_complete_images" && ret=0
;;
@ -1292,7 +1294,7 @@ __docker_network_subcommand() {
$opts_help \
"($help)--no-trunc[Do not truncate the output]" \
"($help)*"{-f=,--filter=}"[Provide filter values]:filter:__docker_network_complete_ls_filters" \
"($help)--format=[Pretty-print networks using a Go template]:template: " \
"($help)--format=[Format the output using the given Go template]:template: " \
"($help -q --quiet)"{-q,--quiet}"[Only display network IDs]" && ret=0
;;
(prune)
@ -2050,7 +2052,7 @@ __docker_service_subcommand() {
_arguments $(__docker_arguments) \
$opts_help \
"($help)*"{-f=,--filter=}"[Filter output based on conditions provided]:filter:__docker_service_complete_ls_filters" \
"($help)--format=[Pretty-print services using a Go template]:template: " \
"($help)--format=[Format the output using the given Go template]:template: " \
"($help -q --quiet)"{-q,--quiet}"[Only display IDs]" && ret=0
;;
(rm|remove)
@ -2253,7 +2255,7 @@ __docker_stack_subcommand() {
_arguments $(__docker_arguments) \
$opts_help \
"($help)*"{-f=,--filter=}"[Filter output based on conditions provided]:filter:__docker_stack_complete_services_filters" \
"($help)--format=[Pretty-print services using a Go template]:template: " \
"($help)--format=[Format the output using the given Go template]:template: " \
"($help -q --quiet)"{-q,--quiet}"[Only display IDs]" \
"($help -):stack:__docker_complete_stacks" && ret=0
;;
@ -2520,12 +2522,14 @@ __docker_volume_subcommand() {
_arguments $(__docker_arguments) \
$opts_help \
"($help)*"{-f=,--filter=}"[Provide filter values]:filter:__docker_volume_complete_ls_filters" \
"($help)--format=[Pretty-print volumes using a Go template]:template: " \
"($help)--format=[Format the output using the given Go template]:template: " \
"($help -q --quiet)"{-q,--quiet}"[Only display volume names]" && ret=0
;;
(prune)
_arguments $(__docker_arguments) \
$opts_help \
"($help -a --all)"{-a,--all}"[Remove all unused local volumes, not just anonymous ones]" \
"($help)*--filter=[Filter values]:filter:__docker_complete_prune_filters" \
"($help -f --force)"{-f,--force}"[Do not prompt for confirmation]" && ret=0
;;
(rm)
@ -2582,10 +2586,8 @@ __docker_context_subcommand() {
(create)
_arguments $(__docker_arguments) \
$opts_help \
"($help)--default-stack-orchestrator=[Default orchestrator for stack operations to use with this context]:default-stack-orchestrator:(swarm kubernetes all)" \
"($help)--description=[Description of the context]:description:" \
"($help)--docker=[Set the docker endpoint]:docker:" \
"($help)--kubernetes=[Set the kubernetes endpoint]:kubernetes:" \
"($help)--from=[Create context from a named context]:from:__docker_complete_contexts" \
"($help -):name: " && ret=0
;;
@ -2607,10 +2609,8 @@ __docker_context_subcommand() {
(update)
_arguments $(__docker_arguments) \
$opts_help \
"($help)--default-stack-orchestrator=[Default orchestrator for stack operations to use with this context]:default-stack-orchestrator:(swarm kubernetes all)" \
"($help)--description=[Description of the context]:description:" \
"($help)--docker=[Set the docker endpoint]:docker:" \
"($help)--kubernetes=[Set the kubernetes endpoint]:kubernetes:" \
"($help -):name:" && ret=0
;;
esac
@ -2734,9 +2734,6 @@ __docker_subcommand() {
"($help -b --bridge)"{-b=,--bridge=}"[Attach containers to a network bridge]:bridge:_net_interfaces" \
"($help)--bip=[Network bridge IP]:IP address: " \
"($help)--cgroup-parent=[Parent cgroup for all containers]:cgroup: " \
"($help)--cluster-advertise=[Address or interface name to advertise]:Instance to advertise (host\:port): " \
"($help)--cluster-store=[URL of the distributed storage backend]:Cluster Store:->cluster-store" \
"($help)*--cluster-store-opt=[Cluster store options]:Cluster options:->cluster-store-options" \
"($help)--config-file=[Path to daemon configuration file]:Config File:_files" \
"($help)--containerd=[Path to containerd socket]:socket:_files -g \"*.sock\"" \
"($help)--containerd-namespace=[Containerd namespace to use]:containerd namespace:" \
@ -2771,16 +2768,16 @@ __docker_subcommand() {
"($help)--live-restore[Enable live restore of docker when containers are still running]" \
"($help)--log-driver=[Default driver for container logs]:logging driver:__docker_complete_log_drivers" \
"($help)*--log-opt=[Default log driver options for containers]:log driver options:__docker_complete_log_options" \
"($help)--max-concurrent-downloads[Set the max concurrent downloads for each pull]" \
"($help)--max-concurrent-uploads[Set the max concurrent uploads for each push]" \
"($help)--max-concurrent-downloads[Set the max concurrent downloads]" \
"($help)--max-concurrent-uploads[Set the max concurrent uploads]" \
"($help)--max-download-attempts[Set the max download attempts for each pull]" \
"($help)--mtu=[Network MTU]:mtu:(0 576 1420 1500 9000)" \
"($help)--oom-score-adjust=[Set the oom_score_adj for the daemon]:oom-score:(-500)" \
"($help -p --pidfile)"{-p=,--pidfile=}"[Path to use for daemon PID file]:PID file:_files" \
"($help)--raw-logs[Full timestamps without ANSI coloring]" \
"($help)*--registry-mirror=[Preferred Docker registry mirror]:registry mirror: " \
"($help)*--registry-mirror=[Preferred registry mirror]:registry mirror: " \
"($help)--seccomp-profile=[Path to seccomp profile]:path:_files -g \"*.json\"" \
"($help -s --storage-driver)"{-s=,--storage-driver=}"[Storage driver to use]:driver:(aufs btrfs devicemapper overlay overlay2 vfs zfs)" \
"($help -s --storage-driver)"{-s=,--storage-driver=}"[Storage driver to use]:driver:(btrfs devicemapper overlay2 vfs zfs)" \
"($help)--selinux-enabled[Enable selinux support]" \
"($help)--shutdown-timeout=[Set the shutdown timeout value in seconds]:time: " \
"($help)*--storage-opt=[Storage driver options]:storage driver options: " \
@ -2795,22 +2792,6 @@ __docker_subcommand() {
"($help)--validate[Validate daemon configuration and exit]" && ret=0
case $state in
(cluster-store)
if compset -P '*://'; then
_message 'host:port' && ret=0
else
store=('consul' 'etcd' 'zk')
_describe -t cluster-store "Cluster Store" store -qS "://" && ret=0
fi
;;
(cluster-store-options)
if compset -P '*='; then
_files && ret=0
else
opts=('discovery.heartbeat' 'discovery.ttl' 'kv.cacertfile' 'kv.certfile' 'kv.keyfile' 'kv.path')
_describe -t cluster-store-opts "Cluster Store Options" opts -qS "=" && ret=0
fi
;;
(users-groups)
if compset -P '*:'; then
_groups && ret=0
@ -3095,6 +3076,7 @@ _docker() {
_arguments $(__docker_arguments) -C \
"(: -)"{-h,--help}"[Print usage]" \
"($help)--config[Location of client config files]:path:_directories" \
"($help -c --context)"{-c=,--context=}"[Execute the command in a docker context]:context:__docker_complete_contexts" \
"($help -D --debug)"{-D,--debug}"[Enable debug mode]" \
"($help -H --host)"{-H=,--host=}"[tcp://host:port to bind/connect to]:host: " \
"($help -l --log-level)"{-l=,--log-level=}"[Logging level]:level:(debug info warn error fatal)" \
@ -3110,7 +3092,8 @@ _docker() {
local host=${opt_args[-H]}${opt_args[--host]}
local config=${opt_args[--config]}
local docker_options="${host:+--host $host} ${config:+--config $config}"
local context=${opt_args[-c]}${opt_args[--context]}
local docker_options="${host:+--host $host} ${config:+--config $config} ${context:+--context $context} "
case $state in
(command)

View file

@ -1,39 +1,62 @@
alias dbl='docker build'
alias dpu='docker pull'
alias dtop='docker top'
# docker containers
alias dcin='docker container inspect'
alias dlo='docker container logs'
alias dcls='docker container ls'
alias dclsa='docker container ls -a'
alias dpo='docker container port'
alias dr='docker container run'
alias drit='docker container run -it'
alias drm='docker container rm'
alias 'drm!'='docker container rm -f'
alias dst='docker container start'
alias dstp='docker container stop'
alias dxc='docker container exec'
alias dxcit='docker container exec -it'
# docker images
alias dib='docker image build'
alias dii='docker image inspect'
alias dils='docker image ls'
alias dipu='docker image push'
alias dirm='docker image rm'
alias dit='docker image tag'
# docker network
alias dlo='docker container logs'
alias dnc='docker network create'
alias dncn='docker network connect'
alias dndcn='docker network disconnect'
alias dni='docker network inspect'
alias dnls='docker network ls'
alias dnrm='docker network rm'
# docker volume
alias dpo='docker container port'
alias dpu='docker pull'
alias dr='docker container run'
alias drit='docker container run -it'
alias drm='docker container rm'
alias 'drm!'='docker container rm -f'
alias dst='docker container start'
alias drs='docker container restart'
alias dsta='docker stop $(docker ps -q)'
alias dstp='docker container stop'
alias dtop='docker top'
alias dvi='docker volume inspect'
alias dvls='docker volume ls'
alias dvprune='docker volume prune'
alias dxc='docker container exec'
alias dxcit='docker container exec -it'
if (( ! $+commands[docker] )); then
return
fi
# Standarized $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}"
# If the completion file doesn't exist yet, we need to autoload it and
# bind it to `docker`. Otherwise, compinit will have already done that.
if [[ ! -f "$ZSH_CACHE_DIR/completions/_docker" ]]; then
typeset -g -A _comps
autoload -Uz _docker
_comps[docker]=_docker
fi
{
# `docker completion` is only available from 23.0.0 on
# docker version returns `Docker version 24.0.2, build cb74dfcd85`
# with `s:,:` remove the comma after the version, and select third word of it
if zstyle -t ':omz:plugins:docker' legacy-completion || \
! 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"
fi
} &|

View file

@ -4,6 +4,14 @@
#
# Author: https://github.com/HalisCz
if [ $commands[doctl] ]; then
source <(doctl completion zsh)
if (( ! $+commands[doctl] )); then
return
fi
if [[ ! -f "$ZSH_CACHE_DIR/completions/_doctl" ]]; then
typeset -g -A _comps
autoload -Uz _doctl
_comps[doctl]=_doctl
fi
doctl completion zsh >| "$ZSH_CACHE_DIR/completions/_doctl" &|

View file

@ -17,6 +17,7 @@ plugins=(... dotnet)
| dt | dotnet test | Run unit tests using the test runner specified in a .NET project. |
| dw | dotnet watch | Watch for source file changes and restart the dotnet command. |
| dwr | dotnet watch run | Watch for source file changes and restart the `run` command. |
| dwt | dotnet watch test| Watch for source file changes and restart the `test` command. |
| ds | dotnet sln | Modify Visual Studio solution files. |
| da | dotnet add | Add a package or reference to a .NET project. |
| dp | dotnet pack | Create a NuGet package. |

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)
@ -26,6 +18,7 @@ alias dr='dotnet run'
alias dt='dotnet test'
alias dw='dotnet watch'
alias dwr='dotnet watch run'
alias dwt='dotnet watch test'
alias ds='dotnet sln'
alias da='dotnet add'
alias dp='dotnet pack'

View file

@ -25,6 +25,6 @@ The plugin uses a custom launcher (which we'll call here `$EMACS_LAUNCHER`) that
| e | `emacs` | Same as emacs alias |
| te | `$EMACS_LAUNCHER -nw` | Open terminal emacsclient |
| eeval | `$EMACS_LAUNCHER --eval` | Same as `M-x eval` but from outside Emacs |
| eframe | `emacsclient --alternate-editor "" --create-frame` | Create new X frame |
| 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 |

View file

@ -32,7 +32,7 @@ alias te="$EMACS_PLUGIN_LAUNCHER -nw"
# same than M-x eval but from outside Emacs.
alias eeval="$EMACS_PLUGIN_LAUNCHER --eval"
# create a new X frame
alias eframe='emacsclient --alternate-editor "" --create-frame'
alias eframe='emacsclient --alternate-editor="" --create-frame'
# Emacs ANSI Term tracking
if [[ -n "$INSIDE_EMACS" ]]; then

View file

@ -15,11 +15,11 @@ emacsfun() {
# Only create another X frame if there isn't one present
if [ -z "$frames" -o "$frames" = nil ]; then
emacsclient --alternate-editor "" --create-frame "$@"
emacsclient --alternate-editor="" --create-frame "$@"
return $?
fi
emacsclient --alternate-editor "" "$@"
emacsclient --alternate-editor="" "$@"
}
# Adapted from https://github.com/davidshepherd7/emacs-read-stdin/blob/master/emacs-read-stdin.sh

View file

@ -56,7 +56,7 @@ typeset -gAH emoji_groups
# def country_iso(_all_names, _omz_name):
# """ Using the external library country_converter,
# this funciton can detect the ISO2 and ISO3 codes
# this function can detect the ISO2 and ISO3 codes
# of the country. It takes as argument the array
# with all the names of the emoji, and returns that array."""
# omz_no_underscore = re.sub(r'_', r' ', _omz_name)
@ -96,7 +96,7 @@ def name_to_omz(_name, _group, _subgroup, _status):
# Special treatment by status
# Enables us to have every emoji combination,
# even the one that are not officially sanctionned
# and are implemeted by, say, only one vendor
# and are implemented by, say, only one vendor
if _status == "unqualified":
shortname += "_unqualified"
elif _status == "minimally-qualified":

View file

@ -10,10 +10,11 @@ plugins=(... encode64)
## Functions and Aliases
| Function | Alias | Description |
| ---------- | ----- | ------------------------------ |
| `encode64` | `e64` | Encodes given data to base64 |
| `decode64` | `d64` | Decodes given data from base64 |
| Function | Alias | Description |
| -------------- | ------ | -------------------------------------- |
| `encode64` | `e64` | Encodes given data to base64 |
| `encodefile64` | `ef64` | Encodes given file's content to base64 |
| `decode64` | `d64` | Decodes given data from base64 |
## Usage and examples
@ -37,6 +38,20 @@ plugins=(... encode64)
b2gtbXktenNo==
```
### Encoding a file
Encode a file's contents to base64 and save output to text file.
**NOTE:** Takes provided file and saves encoded content as new file with `.txt` extension
- From parameter
```console
$ encodefile64 ohmyzsh.icn
ohmyzsh.icn's content encoded in base64 and saved as ohmyzsh.icn.txt
$ ef64 "oh-my-zsh"
ohmyzsh.icn's content encoded in base64 and saved as ohmyzsh.icn.txt
```
### Decoding
- From parameter

View file

@ -6,6 +6,15 @@ encode64() {
fi
}
encodefile64() {
if [[ $# -eq 0 ]]; then
echo "You must provide a filename"
else
base64 -i $1 -o $1.txt
echo "${1}'s content encoded in base64 and saved as ${1}.txt"
fi
}
decode64() {
if [[ $# -eq 0 ]]; then
cat | base64 --decode
@ -14,4 +23,5 @@ decode64() {
fi
}
alias e64=encode64
alias ef64=encodefile64
alias d64=decode64

View file

@ -1,10 +1,10 @@
# extract plugin
This plugin defines a function called `extract` that extracts the archive file
you pass it, and it supports a wide variety of archive filetypes.
This plugin defines a function called `extract` that extracts the archive file you pass it, and it supports a
wide variety of archive filetypes.
This way you don't have to know what specific command extracts a file, you just
do `extract <filename>` and the function takes care of the rest.
This way you don't have to know what specific command extracts a file, you just do `extract <filename>` and
the function takes care of the rest.
To use it, add `extract` to the plugins array in your zshrc file:
@ -15,7 +15,7 @@ plugins=(... extract)
## Supported file extensions
| Extension | Description |
|:------------------|:-------------------------------------|
| :---------------- | :----------------------------------- |
| `7z` | 7zip file |
| `Z` | Z archive (LZW) |
| `apk` | Android app file |
@ -25,6 +25,7 @@ plugins=(... extract)
| `cpio` | Cpio archive |
| `deb` | Debian package |
| `ear` | Enterprise Application aRchive |
| `exe` | Windows executable file |
| `gz` | Gzip file |
| `ipa` | iOS app package |
| `ipsw` | iOS firmware file |
@ -32,6 +33,7 @@ plugins=(... extract)
| `lrz` | LRZ archive |
| `lz4` | LZ4 archive |
| `lzma` | LZMA archive |
| `obscpio` | cpio archive used on OBS |
| `rar` | WinRAR archive |
| `rpm` | RPM package |
| `sublime-package` | Sublime Text package |
@ -51,10 +53,13 @@ plugins=(... extract)
| `txz` | Tarball with lzma2 compression |
| `tzst` | Tarball with zstd compression |
| `war` | Web Application archive (Java-based) |
| `whl` | Python wheel file |
| `xpi` | Mozilla XPI module file |
| `xz` | LZMA2 archive |
| `zip` | Zip archive |
| `zlib` | zlib archive |
| `zst` | Zstandard file (zstd) |
| `zpaq` | Zpaq file |
See [list of archive formats](https://en.wikipedia.org/wiki/List_of_archive_formats) for
more information regarding archive formats.
See [list of archive formats](https://en.wikipedia.org/wiki/List_of_archive_formats) for more information
regarding archive formats.

View file

@ -3,5 +3,5 @@
_arguments \
'(-r --remove)'{-r,--remove}'[Remove archive.]' \
"*::archive file:_files -g '(#i)*.(7z|Z|apk|aar|bz2|cab|cpio|deb|ear|gz|ipa|ipsw|jar|lrz|lz4|lzma|rar|rpm|sublime-package|tar|tar.bz2|tar.gz|tar.lrz|tar.lz|tar.lz4|tar.xz|tar.zma|tar.zst|tbz|tbz2|tgz|tlz|txz|tzst|war|whl|xpi|xz|zip|zst)(-.)'" \
"*::archive file:_files -g '(#i)*.(7z|Z|apk|aar|bz2|cab|cpio|deb|ear|gz|ipa|ipsw|jar|lrz|lz4|lzma|obscpio|rar|rpm|sublime-package|tar|tar.bz2|tar.gz|tar.lrz|tar.lz|tar.lz4|tar.xz|tar.zma|tar.zst|tbz|tbz2|tgz|tlz|txz|tzst|war|whl|xpi|xz|zip|zst|zpaq)(-.)'" \
&& return 0

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