diff --git a/.editorconfig b/.editorconfig index b5321de59..b349bcc42 100644 --- a/.editorconfig +++ b/.editorconfig @@ -6,3 +6,6 @@ insert_final_newline = true charset = utf-8 indent_size = 2 indent_style = space + +[*.py] +indent_size = 4 diff --git a/.github/dependencies.yml b/.github/dependencies.yml index f760ddcef..d3b269361 100644 --- a/.github/dependencies.yml +++ b/.github/dependencies.yml @@ -36,3 +36,11 @@ dependencies: precopy: | set -e find . ! -name _gradle ! -name LICENSE -delete + plugins/wd: + repo: mfaerevaag/wd + branch: master + version: tag:v0.7.0 + precopy: | + set -e + rm -r test + rm install.sh tty.gif wd.1 diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml index 2e2217e1c..6c7387089 100644 --- a/.github/workflows/dependencies.yml +++ b/.github/workflows/dependencies.yml @@ -1,8 +1,8 @@ name: Update dependencies on: workflow_dispatch: {} - # schedule: - # - cron: '34 3 * * */8' + schedule: + - cron: "0 6 * * 0" jobs: check: @@ -12,12 +12,19 @@ jobs: steps: - name: Checkout uses: actions/checkout@v4 + with: + fetch-depth: 0 - name: Authenticate as @ohmyzsh id: generate_token uses: ohmyzsh/github-app-token@v2 with: app_id: ${{ secrets.OHMYZSH_APP_ID }} private_key: ${{ secrets.OHMYZSH_APP_PRIVATE_KEY }} + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: "pip" - name: Process dependencies env: GH_TOKEN: ${{ steps.generate_token.outputs.token }} diff --git a/.github/workflows/dependencies/requirements.txt b/.github/workflows/dependencies/requirements.txt index 3c4c149ea..7e840a74c 100644 --- a/.github/workflows/dependencies/requirements.txt +++ b/.github/workflows/dependencies/requirements.txt @@ -1,2 +1,7 @@ -PyYAML~=6.0.1 -requests~=2.31.0 +certifi==2024.2.2 +charset-normalizer==3.3.2 +idna==3.7 +PyYAML==6.0.1 +requests==2.31.0 +semver==3.0.2 +urllib3==2.2.1 diff --git a/.github/workflows/dependencies/updater.py b/.github/workflows/dependencies/updater.py index f54d316f9..f85c9eda7 100644 --- a/.github/workflows/dependencies/updater.py +++ b/.github/workflows/dependencies/updater.py @@ -1,11 +1,16 @@ +import json import os +import re +import shutil import subprocess import sys -import requests -import shutil -import yaml +import timeit from copy import deepcopy -from typing import Optional, TypedDict +from typing import Literal, NotRequired, Optional, TypedDict + +import requests +import yaml +from semver import Version # Get TMP_DIR variable from environment TMP_DIR = os.path.join(os.environ.get("TMP_DIR", "/tmp"), "ohmyzsh") @@ -14,28 +19,58 @@ DEPS_YAML_FILE = ".github/dependencies.yml" # Dry run flag DRY_RUN = os.environ.get("DRY_RUN", "0") == "1" -import timeit +# utils for tag comparison +BASEVERSION = re.compile( + r"""[vV]? + (?P(0|[1-9])\d*) + (\. + (?P(0|[1-9])\d*) + (\. + (?P(0|[1-9])\d*) + )? + )? + """, + re.VERBOSE, +) + + +def coerce(version: str) -> Optional[Version]: + match = BASEVERSION.search(version) + if not match: + return None + + # BASEVERSION looks for `MAJOR.minor.patch` in the string given + # it fills with None if any of them is missing (for example `2.1`) + ver = { + key: 0 if value is None else value for key, value in match.groupdict().items() + } + # Version takes `major`, `minor`, `patch` arguments + ver = Version(**ver) # pyright: ignore[reportArgumentType] + return ver + + class CodeTimer: - def __init__(self, name=None): - self.name = " '" + name + "'" if name else '' + def __init__(self, name=None): + self.name = " '" + name + "'" if name else "" - def __enter__(self): - self.start = timeit.default_timer() + 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') + 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) + """ + 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) @@ -43,408 +78,521 @@ yaml.representer.SafeRepresenter.add_representer(str, str_presenter) # Types class DependencyDict(TypedDict): - repo: str - branch: str - version: str - precopy: Optional[str] - postcopy: Optional[str] + repo: str + branch: str + version: str + precopy: NotRequired[str] + postcopy: NotRequired[str] + class DependencyYAML(TypedDict): - dependencies: dict[str, DependencyDict] + 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 UpdateStatusFalse(TypedDict): + has_updates: Literal[False] + + +class UpdateStatusTrue(TypedDict): + has_updates: Literal[True] + version: str + compare_url: str + head_ref: str + head_url: str class CommandRunner: - class Exception(Exception): - def __init__(self, message, returncode, stage, stdout, stderr): - super().__init__(message) - self.returncode = returncode - self.stage = stage - self.stdout = stdout - self.stderr = stderr + 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") + @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) + 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") - ) + 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 + return result class DependencyStore: - store: DependencyYAML = { - "dependencies": {} - } + store: DependencyYAML = {"dependencies": {}} - @staticmethod - def set(data: DependencyYAML): - DependencyStore.store = data + @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) + @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 + dependency = store_copy["dependencies"].get(path) + if dependency is None: + raise ValueError(f"Dependency {path} {version} not found") + dependency["version"] = version + store_copy["dependencies"][path] = dependency - return store_copy + 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) + @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 + def __init__(self, path: str, values: DependencyDict): + self.path = path + self.values = values - self.name: str = "" - self.desc: str = "" - self.kind: str = "" + 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 + 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 + 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 + 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) + 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 + # Check for updates + repo = self.values["repo"] + remote_branch = self.values["branch"] + version = self.values["version"] + is_tag = version.startswith("tag:") try: - # Create new branch - branch = Git.create_branch(self.path, new_version) + 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) - # Update dependencies.yml file - self.__update_yaml(f"tag:{new_version}" if is_tag else status["version"]) + if status["has_updates"] is True: + short_sha = status["head_ref"][:8] + new_version = status["version"] if is_tag else short_sha - # Update dependency files - self.__apply_upstream_changes() + try: + branch_name = f"update/{self.path}/{new_version}" - # Add all changes and commit - Git.add_and_commit(self.name, short_sha) + # Create new branch + branch = Git.checkout_or_create_branch(branch_name) - # Push changes to remote - Git.push(branch) + # Update dependencies.yml file + self.__update_yaml( + f"tag:{new_version}" if is_tag else status["version"] + ) - # Create GitHub PR - GitHub.create_pr( - branch, - f"feat({self.name}): update to version {new_version}", - f"""## Description + # Update dependency files + self.__apply_upstream_changes() + + # Add all changes and commit + has_new_commit = Git.add_and_commit(self.name, short_sha) + + if has_new_commit: + # Push changes to remote + Git.push(branch) + + # Create GitHub PR + GitHub.create_pr( + branch, + f"feat({self.name}): update to version {new_version}", + f"""## Description Update for **{self.desc}**: update to version [{new_version}]({status['head_url']}). Check out the [list of changes]({status['compare_url']}). -""" - ) +""", + ) - # Clean up repository - Git.clean_repo() - except (CommandRunner.Exception, shutil.Error) as e: - # Handle exception on automatic update - match type(e): - case CommandRunner.Exception: - # Print error message - print(f"Error running {e.stage} command: {e.returncode}", file=sys.stderr) - print(e.stderr, file=sys.stderr) - case shutil.Error: - print(f"Error copying files: {e}", file=sys.stderr) + # Clean up repository + Git.clean_repo() + except (CommandRunner.Exception, shutil.Error) as e: + # Handle exception on automatic update + match type(e): + case CommandRunner.Exception: + # Print error message + print( + f"Error running {e.stage} command: {e.returncode}", # pyright: ignore[reportAttributeAccessIssue] + file=sys.stderr, + ) + print(e.stderr, file=sys.stderr) # pyright: ignore[reportAttributeAccessIssue] + case shutil.Error: + print(f"Error copying files: {e}", file=sys.stderr) - try: - Git.clean_repo() - except CommandRunner.Exception as e: - print(f"Error reverting repository to clean state: {e}", file=sys.stderr) - sys.exit(1) + 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 + # 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) + print("Creating GitHub issue", file=sys.stderr) + print(f"{title}\n\n{body}", file=sys.stderr) + GitHub.create_issue(title, body) + except Exception as e: + print(e, file=sys.stderr) - def __update_yaml(self, new_version: str) -> None: - dep_yaml = DependencyStore.update_dependency_version(self.path, new_version) - DependencyStore.write_store(DEPS_YAML_FILE, dep_yaml) + def __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" - ] + 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") + 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) + 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) + # 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") + # 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)) + # 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") + # 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" + 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) + @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") + # 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() + @staticmethod + def checkout_or_create_branch(branch_name: str): + # Get current branch name + result = CommandRunner.run_or_fail( + ["git", "rev-parse", "--abbrev-ref", "HEAD"], stage="GetDefaultBranch" + ) + Git.default_branch = result.stdout.decode("utf-8").strip() - # Create new branch and return created branch name - branch_name = f"update/{path}/{version}" - CommandRunner.run_or_fail(["git", "checkout", "-b", branch_name], stage="CreateBranch") - return branch_name + # Create new branch and return created branch name + try: + # try to checkout already existing branch + CommandRunner.run_or_fail( + ["git", "checkout", branch_name], stage="CreateBranch" + ) + except CommandRunner.Exception: + # otherwise create new branch + CommandRunner.run_or_fail( + ["git", "checkout", "-b", branch_name], stage="CreateBranch" + ) + return branch_name - @staticmethod - def add_and_commit(scope: str, version: str): - user_name = os.environ.get("GIT_APP_NAME") - user_email = os.environ.get("GIT_APP_EMAIL") + @staticmethod + def add_and_commit(scope: str, version: str) -> bool: + """ + Returns `True` if there were changes and were indeed commited. + Returns `False` if the repo was clean and no changes were commited. + """ + # check if repo is clean (clean => no error, no commit) + try: + CommandRunner.run_or_fail( + ["git", "diff", "--exit-code"], stage="CheckRepoClean" + ) + return False + except CommandRunner.Exception: + # if it's other kind of error just throw! + pass - # Add all files to git staging - CommandRunner.run_or_fail(["git", "add", "-A", "-v"], stage="AddFiles") + user_name = os.environ.get("GIT_APP_NAME") + user_email = os.environ.get("GIT_APP_EMAIL") - # 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" + # Add all files to git staging + CommandRunner.run_or_fail(["git", "add", "-A", "-v"], stage="AddFiles") - # 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) + # 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" - @staticmethod - def push(branch: str): - CommandRunner.run_or_fail(["git", "push", "-u", "origin", branch], stage="PushBranch") + # Commit with settings above + CommandRunner.run_or_fail( + [ + "git", + "-c", + f"user.name={user_name}", + "-c", + f"user.email={user_email}", + "commit", + "-m", + f"feat({scope}): update to {version}", + ], + stage="CreateCommit", + env=clean_env, + ) + return True - @staticmethod - def clean_repo(): - CommandRunner.run_or_fail(["git", "reset", "--hard", "HEAD"], stage="ResetRepository") - CommandRunner.run_or_fail(["git", "checkout", Git.default_branch], stage="CheckoutDefaultBranch") + @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" + @staticmethod + def check_newer_tag(repo, current_tag) -> UpdateStatusFalse | UpdateStatusTrue: + # GET /repos/:owner/:repo/git/refs/tags + url = f"https://api.github.com/repos/{repo}/git/refs/tags" - # Send a GET request to the GitHub API - response = requests.get(url) + # Send a GET request to the GitHub API + response = requests.get(url) + current_version = coerce(current_tag) + if current_version is None: + raise ValueError( + f"Stored {current_version} from {repo} does not follow semver" + ) - # If the request was successful - if response.status_code == 200: - # Parse the JSON response - data = response.json() + # If the request was successful + if response.status_code == 200: + # Parse the JSON response + data = response.json() - if len(data) == 0: - return { - "has_updates": False, - } + if len(data) == 0: + return { + "has_updates": False, + } - latest_ref = data[-1] - latest_tag = latest_ref["ref"].replace("refs/tags/", "") + latest_ref = None + latest_version: Optional[Version] = None + for ref in data: + # we find the tag since GitHub returns it as plain git ref + tag_version = coerce(ref["ref"].replace("refs/tags/", "")) + if tag_version is None: + # we skip every tag that is not semver-complaint + continue + if latest_version is None or tag_version.compare(latest_version) > 0: + # if we have a "greater" semver version, set it as latest + latest_version = tag_version + latest_ref = ref - if latest_tag == current_tag: - return { - "has_updates": False, - } + # raise if no valid semver tag is found + if latest_ref is None or latest_version is None: + raise ValueError(f"No tags following semver found in {repo}") - 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()}") + # we get the tag since GitHub returns it as plain git ref + latest_tag = latest_ref["ref"].replace("refs/tags/", "") - @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}" + if latest_version.compare(current_version) <= 0: + return { + "has_updates": False, + } - # Send a GET request to the GitHub API - response = requests.get(url) + 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()}" + ) - # If the request was successful - if response.status_code == 200: - # Parse the JSON response - data = response.json() + @staticmethod + def check_updates(repo, branch, version) -> UpdateStatusFalse | UpdateStatusTrue: + url = f"https://api.github.com/repos/{repo}/compare/{version}...{branch}" - # If the base is behind the head, there is a newer version - has_updates = data["status"] != "identical" + # Send a GET request to the GitHub API + response = requests.get(url) - if not has_updates: - return { - "has_updates": False, - } + # If the request was successful + if response.status_code == 200: + # Parse the JSON response + data = response.json() - 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()}") + # If the base is behind the head, there is a newer version + has_updates = data["status"] != "identical" - @staticmethod - def create_issue(title: str, body: str) -> None: - cmd = [ - "gh", - "issue", - "create", - "-t", title, - "-b", body - ] - CommandRunner.run_or_fail(cmd, stage="CreateIssue") + if not has_updates: + return { + "has_updates": False, + } - @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") + return { + "has_updates": data["status"] != "identical", + "version": data["commits"][-1]["sha"], + "compare_url": data["permalink_url"], + "head_ref": data["commits"][-1]["sha"], + "head_url": data["commits"][-1]["html_url"], + } + else: + # If the request was not successful, raise an exception + raise Exception( + f"GitHub API request failed with status code {response.status_code}: {response.json()}" + ) + + @staticmethod + def create_issue(title: str, body: str) -> None: + cmd = ["gh", "issue", "create", "-t", title, "-b", body] + CommandRunner.run_or_fail(cmd, stage="CreateIssue") + + @staticmethod + def create_pr(branch: str, title: str, body: str) -> None: + # first of all let's check if PR is already open + check_cmd = [ + "gh", + "pr", + "list", + "--state", + "open", + "--head", + branch, + "--json", + "title", + ] + # returncode is 0 also if no PRs are found + output = json.loads( + CommandRunner.run_or_fail(check_cmd, stage="CheckPullRequestOpen") + .stdout.decode("utf-8") + .strip() + ) + # we have PR in this case! + if len(output) > 0: + return + cmd = [ + "gh", + "pr", + "create", + "-B", + Git.default_branch, + "-H", + branch, + "-t", + title, + "-b", + body, + ] + CommandRunner.run_or_fail(cmd, stage="CreatePullRequest") def main(): - # Load the YAML file - with open(DEPS_YAML_FILE, "r") as yaml_file: - data: DependencyYAML = yaml.safe_load(yaml_file) + # 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") + if "dependencies" not in data: + raise Exception("dependencies.yml not properly formatted") - # Cache YAML version - DependencyStore.set(data) + # Cache YAML version + DependencyStore.set(data) + + dependencies = data["dependencies"] + for path in dependencies: + dependency = Dependency(path, dependencies[path]) + dependency.update_or_notify() - dependencies = data["dependencies"] - for path in dependencies: - dependency = Dependency(path, dependencies[path]) - dependency.update_or_notify() if __name__ == "__main__": - main() + main() diff --git a/README.md b/README.md index b3561a833..dea36fda7 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ To learn more, visit [ohmyz.sh](https://ohmyz.sh), follow [@ohmyzsh](https://twi - [Custom Plugins And Themes](#custom-plugins-and-themes) - [Enable GNU ls In macOS And freeBSD Systems](#enable-gnu-ls-in-macos-and-freebsd-systems) - [Skip Aliases](#skip-aliases) + - [Disable async git prompt](#disable-async-git-prompt) - [Getting Updates](#getting-updates) - [Updates Verbosity](#updates-verbosity) - [Manual Updates](#manual-updates) @@ -361,6 +362,17 @@ Instead, you can now use the following: zstyle ':omz:lib:directories' aliases no ``` +### Disable async git prompt + +Async prompt functions are an experimental feature (included on April 3, 2024) that allows Oh My Zsh to render prompt information +asyncronously. This can improve prompt rendering performance, but it might not work well with some setups. We hope that's not an +issue, but if you're seeing problems with this new feature, you can turn it off by setting the following in your .zshrc file, +before Oh My Zsh is sourced: + +```sh +zstyle ':omz:alpha:lib:git' async-prompt no +``` + #### Notice > This feature is currently in a testing phase and it may be subject to change in the future. diff --git a/custom/example.zsh b/custom/example.zsh index 21a8d8be7..c194f49d7 100644 --- a/custom/example.zsh +++ b/custom/example.zsh @@ -1,12 +1,12 @@ # 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 diff --git a/custom/themes/example.zsh-theme b/custom/themes/example.zsh-theme index 494d029e8..5551207f8 100644 --- a/custom/themes/example.zsh-theme +++ b/custom/themes/example.zsh-theme @@ -1,6 +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%}%% " diff --git a/lib/async_prompt.zsh b/lib/async_prompt.zsh index 384e49d33..db48446e7 100644 --- a/lib/async_prompt.zsh +++ b/lib/async_prompt.zsh @@ -3,6 +3,7 @@ # https://github.com/woefe/git-prompt.zsh/blob/master/git-prompt.zsh zmodload zsh/system +autoload -Uz is-at-least # For now, async prompt function handlers are set up like so: # First, define the async function handler and register the handler @@ -82,10 +83,8 @@ function _omz_async_request { exec {fd}< <( # Tell parent process our PID builtin echo ${sysparams[pid]} - # Store handler name for callback - builtin echo $handler # Set exit code for the handler if used - (exit $ret) + () { return $ret } # Run the async function handler $handler ) @@ -95,11 +94,11 @@ function _omz_async_request { # There's a weird bug here where ^C stops working unless we force a fork # See https://github.com/zsh-users/zsh-autosuggestions/issues/364 - command true + # and https://github.com/zsh-users/zsh-autosuggestions/pull/612 + is-at-least 5.8 || command true # Save the PID from the handler child process - read pid <&$fd - _OMZ_ASYNC_PIDS[$handler]=$pid + read -u $fd "_OMZ_ASYNC_PIDS[$handler]" # When the fd is readable, call the response handler zle -F "$fd" _omz_async_callback @@ -114,19 +113,18 @@ function _omz_async_callback() { local err=$2 # Second arg will be passed in case of error if [[ -z "$err" || "$err" == "hup" ]]; then - # Get handler name from first line - local handler - read handler <&$fd + # Get handler name from fd + local handler="${(k)_OMZ_ASYNC_FDS[(r)$fd]}" # Store old output which is supposed to be already printed local old_output="${_OMZ_ASYNC_OUTPUT[$handler]}" # Read output from fd - _OMZ_ASYNC_OUTPUT[$handler]="$(cat <&$fd)" + IFS= read -r -u $fd -d '' "_OMZ_ASYNC_OUTPUT[$handler]" # Repaint prompt if output has changed if [[ "$old_output" != "${_OMZ_ASYNC_OUTPUT[$handler]}" ]]; then - zle reset-prompt + zle .reset-prompt zle -R fi diff --git a/lib/cli.zsh b/lib/cli.zsh index aa36a6ab5..383b0cfb0 100644 --- a/lib/cli.zsh +++ b/lib/cli.zsh @@ -241,10 +241,18 @@ function _omz::plugin::disable { # Remove plugins substitution awk script local awk_subst_plugins="\ - gsub(/[ \t]+(${(j:|:)dis_plugins})/, \"\") # with spaces before - gsub(/(${(j:|:)dis_plugins})[ \t]+/, \"\") # with spaces after - gsub(/\((${(j:|:)dis_plugins})\)/, \"\") # without spaces (only plugin) + gsub(/[ \t]+(${(j:|:)dis_plugins})[ \t]+/, \" \") # with spaces before or after + gsub(/[ \t]+(${(j:|:)dis_plugins})$/, \"\") # with spaces before and EOL + gsub(/^(${(j:|:)dis_plugins})[ \t]+/, \"\") # with BOL and spaces after + + gsub(/\((${(j:|:)dis_plugins})[ \t]+/, \"(\") # with parenthesis before and spaces after + gsub(/[ \t]+(${(j:|:)dis_plugins})\)/, \")\") # with spaces before or parenthesis after + gsub(/\((${(j:|:)dis_plugins})\)/, \"()\") # with only parentheses + + gsub(/^(${(j:|:)dis_plugins})\)/, \")\") # with BOL and closing parenthesis + gsub(/\((${(j:|:)dis_plugins})$/, \"(\") # with opening parenthesis and EOL " + # Disable plugins awk script local awk_script=" # if plugins=() is in oneline form, substitute disabled plugins and go to next line @@ -773,7 +781,17 @@ function _omz::theme::use { } function _omz::update { - local last_commit=$(builtin cd -q "$ZSH"; git rev-parse HEAD) + # Check if git command is available + (( $+commands[git] )) || { + _omz::log error "git is not installed. Aborting..." + return 1 + } + + local last_commit=$(builtin cd -q "$ZSH"; git rev-parse HEAD 2>/dev/null) + [[ $? -eq 0 ]] || { + _omz::log error "\`$ZSH\` is not a git directory. Aborting..." + return 1 + } # Run update script zstyle -s ':omz:update' verbose verbose_mode || verbose_mode=default diff --git a/lib/compfix.zsh b/lib/compfix.zsh index b09b283f2..2fe9d9e64 100644 --- a/lib/compfix.zsh +++ b/lib/compfix.zsh @@ -13,7 +13,7 @@ function handle_completion_insecurities() { # /usr/share/zsh/5.0.6 # # Since the ignorable first line is printed to stderr and thus not captured, - # stderr is squelched to prevent this output from leaking to the user. + # stderr is squelched to prevent this output from leaking to the user. local -aU insecure_dirs insecure_dirs=( ${(f@):-"$(compaudit 2>/dev/null)"} ) diff --git a/lib/diagnostics.zsh b/lib/diagnostics.zsh index eaeba7d23..d67e6fab4 100644 --- a/lib/diagnostics.zsh +++ b/lib/diagnostics.zsh @@ -30,7 +30,7 @@ # # This is written in a defensive style so it still works (and can detect) cases when # basic functionality like echo and which have been redefined. In particular, almost -# everything is invoked with "builtin" or "command", to work in the face of user +# everything is invoked with "builtin" or "command", to work in the face of user # redefinitions. # # OPTIONS @@ -59,7 +59,7 @@ function omz_diagnostic_dump() { emulate -L zsh builtin echo "Generating diagnostic dump; please be patient..." - + local thisfcn=omz_diagnostic_dump local -A opts local opt_verbose opt_noverbose opt_outfile @@ -90,7 +90,7 @@ function omz_diagnostic_dump() { builtin echo builtin echo Diagnostic dump file created at: "$outfile" builtin echo - builtin echo To share this with OMZ developers, post it as a gist on GitHub + builtin echo To share this with OMZ developers, post it as a gist on GitHub builtin echo at "https://gist.github.com" and share the link to the gist. builtin echo builtin echo "WARNING: This dump file contains all your zsh and omz configuration files," @@ -105,8 +105,8 @@ function _omz_diag_dump_one_big_text() { builtin echo oh-my-zsh diagnostic dump builtin echo builtin echo $outfile - builtin echo - + builtin echo + # Basic system and zsh information command date command uname -a @@ -151,7 +151,7 @@ function _omz_diag_dump_one_big_text() { # Core command definitions _omz_diag_dump_check_core_commands || return 1 - builtin echo + builtin echo # ZSH Process state builtin echo Process state: @@ -167,7 +167,7 @@ function _omz_diag_dump_one_big_text() { #TODO: Should this include `env` instead of or in addition to `export`? builtin echo Exported: builtin echo $(builtin export | command sed 's/=.*//') - builtin echo + builtin echo builtin echo Locale: command locale builtin echo @@ -181,7 +181,7 @@ function _omz_diag_dump_one_big_text() { builtin echo builtin echo 'compaudit output:' compaudit - builtin echo + builtin echo builtin echo '$fpath directories:' command ls -lad $fpath builtin echo @@ -224,7 +224,7 @@ function _omz_diag_dump_one_big_text() { local cfgfile cfgfiles # Some files for bash that zsh does not use are intentionally included # to help with diagnosing behavior differences between bash and zsh - cfgfiles=( /etc/zshenv /etc/zprofile /etc/zshrc /etc/zlogin /etc/zlogout + cfgfiles=( /etc/zshenv /etc/zprofile /etc/zshrc /etc/zlogin /etc/zlogout $zdotdir/.zshenv $zdotdir/.zprofile $zdotdir/.zshrc $zdotdir/.zlogin $zdotdir/.zlogout ~/.zsh.pre-oh-my-zsh /etc/bashrc /etc/profile ~/.bashrc ~/.profile ~/.bash_profile ~/.bash_logout ) @@ -258,8 +258,8 @@ function _omz_diag_dump_check_core_commands() { # (For back-compatibility, if any of these are newish, they should be removed, # or at least made conditional on the version of the current running zsh.) # "history" is also excluded because OMZ is known to redefine that - reserved_words=( do done esac then elif else fi for case if while function - repeat time until select coproc nocorrect foreach end '!' '[[' '{' '}' + reserved_words=( do done esac then elif else fi for case if while function + repeat time until select coproc nocorrect foreach end '!' '[[' '{' '}' ) builtins=( alias autoload bg bindkey break builtin bye cd chdir command comparguments compcall compctl compdescribe compfiles compgroups compquote comptags @@ -331,7 +331,7 @@ function _omz_diag_dump_os_specific_version() { case "$OSTYPE" in darwin*) osname=$(command sw_vers -productName) - osver=$(command sw_vers -productVersion) + osver=$(command sw_vers -productVersion) builtin echo "OS Version: $osname $osver build $(sw_vers -buildVersion)" ;; cygwin) diff --git a/lib/git.zsh b/lib/git.zsh index 96df5589d..b257d01a4 100644 --- a/lib/git.zsh +++ b/lib/git.zsh @@ -1,3 +1,5 @@ +autoload -Uz is-at-least + # The git prompt's git commands are read-only and should not interfere with # other processes. This environment variable is equivalent to running with `git # --no-optional-locks`, but falls back gracefully for older versions of git. @@ -9,7 +11,7 @@ function __git_prompt_git() { GIT_OPTIONAL_LOCKS=0 command git "$@" } -function _omz_git_prompt_status() { +function _omz_git_prompt_info() { # If we are on a folder not tracked by git, get out. # Otherwise, check for hide-info at global and local repository level if ! __git_prompt_git rev-parse --git-dir &> /dev/null \ @@ -37,11 +39,17 @@ function _omz_git_prompt_status() { echo "${ZSH_THEME_GIT_PROMPT_PREFIX}${ref:gs/%/%%}${upstream:gs/%/%%}$(parse_git_dirty)${ZSH_THEME_GIT_PROMPT_SUFFIX}" } -# Enable async prompt by default unless the setting is at false / no -if zstyle -t ':omz:alpha:lib:git' async-prompt; then +# Use async version if setting is enabled or undefined +if zstyle -T ':omz:alpha:lib:git' async-prompt; then function git_prompt_info() { - if [[ -n "$_OMZ_ASYNC_OUTPUT[_omz_git_prompt_status]" ]]; then - echo -n "$_OMZ_ASYNC_OUTPUT[_omz_git_prompt_status]" + if [[ -n "${_OMZ_ASYNC_OUTPUT[_omz_git_prompt_info]}" ]]; then + echo -n "${_OMZ_ASYNC_OUTPUT[_omz_git_prompt_info]}" + fi + } + + function git_prompt_status() { + if [[ -n "${_OMZ_ASYNC_OUTPUT[_omz_git_prompt_status]}" ]]; then + echo -n "${_OMZ_ASYNC_OUTPUT[_omz_git_prompt_status]}" fi } @@ -49,10 +57,15 @@ if zstyle -t ':omz:alpha:lib:git' async-prompt; then # or any of the other prompt variables function _defer_async_git_register() { # Check if git_prompt_info is used in a prompt variable - case "${PS1}:${PS2}:${PS3}:${PS4}:${RPS1}:${RPS2}:${RPS3}:${RPS4}" in + case "${PS1}:${PS2}:${PS3}:${PS4}:${RPROMPT}:${RPS1}:${RPS2}:${RPS3}:${RPS4}" in *(\$\(git_prompt_info\)|\`git_prompt_info\`)*) + _omz_register_handler _omz_git_prompt_info + ;; + esac + + case "${PS1}:${PS2}:${PS3}:${PS4}:${RPROMPT}:${RPS1}:${RPS2}:${RPS3}:${RPS4}" in + *(\$\(git_prompt_status\)|\`git_prompt_status\`)*) _omz_register_handler _omz_git_prompt_status - return ;; esac @@ -65,6 +78,9 @@ if zstyle -t ':omz:alpha:lib:git' async-prompt; then precmd_functions=(_defer_async_git_register $precmd_functions) else function git_prompt_info() { + _omz_git_prompt_info + } + function git_prompt_status() { _omz_git_prompt_status } fi @@ -197,7 +213,7 @@ function git_prompt_long_sha() { SHA=$(__git_prompt_git rev-parse HEAD 2> /dev/null) && echo "$ZSH_THEME_GIT_PROMPT_SHA_BEFORE$SHA$ZSH_THEME_GIT_PROMPT_SHA_AFTER" } -function git_prompt_status() { +function _omz_git_prompt_status() { [[ "$(__git_prompt_git config --get oh-my-zsh.hide-status 2>/dev/null)" = 1 ]] && return # Maps a git status prefix to an internal constant diff --git a/lib/history.zsh b/lib/history.zsh index 794076904..a8431fd5a 100644 --- a/lib/history.zsh +++ b/lib/history.zsh @@ -1,19 +1,20 @@ ## History wrapper function omz_history { - local clear list - zparseopts -E c=clear l=list + # parse arguments and remove from $@ + local clear list stamp + zparseopts -E -D c=clear l=list f=stamp E=stamp i=stamp t:=stamp if [[ -n "$clear" ]]; then # if -c provided, clobber the history file echo -n >| "$HISTFILE" fc -p "$HISTFILE" echo >&2 History file deleted. - elif [[ -n "$list" ]]; then - # if -l provided, run as if calling `fc' directly - builtin fc "$@" + elif [[ $# -eq 0 ]]; then + # if no arguments provided, show full history starting from 1 + builtin fc $stamp -l 1 else - # unless a number is provided, show all history events (starting from 1) - [[ ${@[-1]-} = *[0-9]* ]] && builtin fc -l "$@" || builtin fc -l "$@" 1 + # otherwise, run `fc -l` with a custom format + builtin fc $stamp -l "$@" fi } diff --git a/lib/termsupport.zsh b/lib/termsupport.zsh index d170ffcbf..087bae9bb 100644 --- a/lib/termsupport.zsh +++ b/lib/termsupport.zsh @@ -17,7 +17,7 @@ function title { : ${2=$1} case "$TERM" in - cygwin|xterm*|putty*|rxvt*|konsole*|ansi|mlterm*|alacritty|st*|foot*|contour*) + cygwin|xterm*|putty*|rxvt*|konsole*|ansi|mlterm*|alacritty*|st*|foot*|contour*) print -Pn "\e]2;${2:q}\a" # set window name print -Pn "\e]1;${1:q}\a" # set tab name ;; @@ -129,7 +129,7 @@ fi # Don't define the function if we're in an unsupported terminal case "$TERM" in # all of these either process OSC 7 correctly or ignore entirely - xterm*|putty*|rxvt*|konsole*|mlterm*|alacritty|screen*|tmux*) ;; + xterm*|putty*|rxvt*|konsole*|mlterm*|alacritty*|screen*|tmux*) ;; contour*|foot*) ;; *) # Terminal.app and iTerm2 process OSC 7 correctly diff --git a/lib/tests/cli.test.zsh b/lib/tests/cli.test.zsh new file mode 100644 index 000000000..9ee5cd219 --- /dev/null +++ b/lib/tests/cli.test.zsh @@ -0,0 +1,169 @@ +#!/usr/bin/zsh -df + +run_awk() { + local -a dis_plugins=(${=1}) + local input_text="$2" + + (( ! DEBUG )) || set -xv + + local awk_subst_plugins="\ + gsub(/[ \t]+(${(j:|:)dis_plugins})[ \t]+/, \" \") # with spaces before or after + gsub(/[ \t]+(${(j:|:)dis_plugins})$/, \"\") # with spaces before and EOL + gsub(/^(${(j:|:)dis_plugins})[ \t]+/, \"\") # with BOL and spaces after + + gsub(/\((${(j:|:)dis_plugins})[ \t]+/, \"(\") # with parenthesis before and spaces after + gsub(/[ \t]+(${(j:|:)dis_plugins})\)/, \")\") # with spaces before or parenthesis after + gsub(/\((${(j:|:)dis_plugins})\)/, \"()\") # with only parentheses + + gsub(/^(${(j:|:)dis_plugins})\)/, \")\") # with BOL and closing parenthesis + gsub(/\((${(j:|:)dis_plugins})$/, \"(\") # with opening parenthesis and EOL + " + # Disable plugins awk script + local awk_script=" + # if plugins=() is in oneline form, substitute disabled plugins and go to next line + /^[ \t]*plugins=\([^#]+\).*\$/ { + $awk_subst_plugins + print \$0 + next + } + + # if plugins=() is in multiline form, enable multi flag and disable plugins if they're there + /^[ \t]*plugins=\(/ { + multi=1 + $awk_subst_plugins + print \$0 + next + } + + # if multi flag is enabled and we find a valid closing parenthesis, remove plugins and disable multi flag + multi == 1 && /^[^#]*\)/ { + multi=0 + $awk_subst_plugins + print \$0 + next + } + + multi == 1 && length(\$0) > 0 { + $awk_subst_plugins + if (length(\$0) > 0) print \$0 + next + } + + { print \$0 } + " + + command awk "$awk_script" <<< "$input_text" + + (( ! DEBUG )) || set +xv +} + +# runs awk against stdin, checks if the resulting file is not empty and then checks if the file has valid zsh syntax +run_awk_and_test() { + local description="$1" + local plugins_to_disable="$2" + local input_text="$3" + local expected_output="$4" + + local tmpfile==(:) + + { + print -u2 "Test: $description" + DEBUG=0 run_awk "$plugins_to_disable" "$input_text" >| $tmpfile + + if [[ ! -s "$tmpfile" ]]; then + print -u2 "\e[31mError\e[0m: output file empty" + return 1 + fi + + if ! zsh -n $tmpfile; then + print -u2 "\e[31mError\e[0m: zsh syntax error" + diff -u $tmpfile <(echo "$expected_output") + return 1 + fi + + if ! diff -u --color=always $tmpfile <(echo "$expected_output"); then + if (( DEBUG )); then + print -u2 "" + DEBUG=1 run_awk "$plugins_to_disable" "$input_text" + print -u2 "" + fi + print -u2 "\e[31mError\e[0m: output file does not match expected output" + return 1 + fi + + print -u2 "\e[32mSuccess\e[0m" + } always { + print -u2 "" + command rm -f "$tmpfile" + } +} + +# These tests are for the `omz plugin disable` command +run_awk_and_test \ + "it should delete a single plugin in oneline format" \ + "git" \ + "plugins=(git)" \ + "plugins=()" + +run_awk_and_test \ + "it should delete a single plugin in multiline format" \ + "github" \ +"plugins=( + github +)" \ +"plugins=( +)" + +run_awk_and_test \ + "it should delete multiple plugins in oneline format" \ + "github git z" \ + "plugins=(github git z)" \ + "plugins=()" + +run_awk_and_test \ + "it should delete multiple plugins in multiline format" \ + "github git z" \ +"plugins=( + github + git + z +)" \ +"plugins=( +)" + +run_awk_and_test \ + "it should delete a single plugin among multiple in oneline format" \ + "git" \ + "plugins=(github git z)" \ + "plugins=(github z)" + +run_awk_and_test \ + "it should delete a single plugin among multiple in multiline format" \ + "git" \ +"plugins=( + github + git + z +)" \ +"plugins=( + github + z +)" + +run_awk_and_test \ + "it should delete multiple plugins in mixed format" \ + "git z" \ +"plugins=(github +git z)" \ +"plugins=(github +)" + +run_awk_and_test \ + "it should delete multiple plugins in mixed format 2" \ + "github z" \ +"plugins=(github + git +z)" \ +"plugins=( + git +)" diff --git a/oh-my-zsh.sh b/oh-my-zsh.sh index 137ca3b6f..2fb20298a 100644 --- a/oh-my-zsh.sh +++ b/oh-my-zsh.sh @@ -152,7 +152,7 @@ unset zcompdump_revision zcompdump_fpath zcompdump_refresh # 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" + command rm -rf "$ZSH_COMPDUMP.zwc.old" "${ZSH_COMPDUMP}.lock" fi _omz_source() { diff --git a/plugins/ansible/README.md b/plugins/ansible/README.md index ce21e7075..dd0e1ce03 100644 --- a/plugins/ansible/README.md +++ b/plugins/ansible/README.md @@ -28,6 +28,6 @@ plugins=(... ansible) ## Maintainer -### [Deepankumar](https://github.com/deepan10) +### [Deepankumar](https://github.com/deepan10) [https://github.com/deepan10/oh-my-zsh/tree/features/ansible-plugin](https://github.com/deepan10/oh-my-zsh/tree/features/ansible-plugin) diff --git a/plugins/archlinux/archlinux.plugin.zsh b/plugins/archlinux/archlinux.plugin.zsh index fca6548c0..e20a31156 100644 --- a/plugins/archlinux/archlinux.plugin.zsh +++ b/plugins/archlinux/archlinux.plugin.zsh @@ -179,8 +179,8 @@ fi # Check Arch Linux PGP Keyring before System Upgrade to prevent failure. function upgrade() { echo ":: Checking Arch Linux PGP Keyring..." - local installedver="$(sudo pacman -Qi archlinux-keyring | grep -Po '(?<=Version : ).*')" - local currentver="$(sudo pacman -Si archlinux-keyring | grep -Po '(?<=Version : ).*')" + local installedver="$(LANG= sudo pacman -Qi archlinux-keyring | grep -Po '(?<=Version : ).*')" + local currentver="$(LANG= sudo pacman -Si archlinux-keyring | grep -Po '(?<=Version : ).*')" if [ $installedver != $currentver ]; then echo " Arch Linux PGP Keyring is out of date." echo " Updating before full system upgrade." diff --git a/plugins/autojump/autojump.plugin.zsh b/plugins/autojump/autojump.plugin.zsh index 84333a89f..e385a2de8 100644 --- a/plugins/autojump/autojump.plugin.zsh +++ b/plugins/autojump/autojump.plugin.zsh @@ -13,7 +13,9 @@ autojump_paths=( /opt/local/etc/profile.d/autojump.sh # macOS with MacPorts /usr/local/etc/profile.d/autojump.sh # macOS with Homebrew (default) /opt/homebrew/etc/profile.d/autojump.sh # macOS with Homebrew (default on M1 macs) + /opt/pkg/share/autojump/autojump.zsh # macOS with pkgsrc /etc/profiles/per-user/$USER/etc/profile.d/autojump.sh # macOS Nix, Home Manager and flakes + /nix/var/nix/gcroots/current-system/sw/share/zsh/site-functions/autojump.zsh # macOS Nix, nix-darwin ) for file in $autojump_paths; do diff --git a/plugins/aws/aws.plugin.zsh b/plugins/aws/aws.plugin.zsh index 071dd1f0b..0c43031df 100644 --- a/plugins/aws/aws.plugin.zsh +++ b/plugins/aws/aws.plugin.zsh @@ -280,7 +280,7 @@ if [[ "$AWS_PROFILE_STATE_ENABLED" == true ]]; then test -s "${AWS_STATE_FILE}" || return aws_state=($(cat $AWS_STATE_FILE)) - + export AWS_DEFAULT_PROFILE="${aws_state[1]}" export AWS_PROFILE="$AWS_DEFAULT_PROFILE" export AWS_EB_PROFILE="$AWS_DEFAULT_PROFILE" diff --git a/plugins/branch/README.md b/plugins/branch/README.md index a15dd22df..2b6d12d29 100644 --- a/plugins/branch/README.md +++ b/plugins/branch/README.md @@ -39,7 +39,7 @@ index 2fd5f2cd..9d89a464 100644 PROMPT="%(?:%{$fg_bold[green]%}➜ :%{$fg_bold[red]%}➜ )" -PROMPT+=' %{$fg[cyan]%}%c%{$reset_color%} $(git_prompt_info)' +PROMPT+=' %{$fg[cyan]%}%c%{$reset_color%} $(branch_prompt_info)' - + ZSH_THEME_GIT_PROMPT_PREFIX="%{$fg_bold[blue]%}git:(%{$fg[red]%}" ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%} " ``` diff --git a/plugins/chruby/chruby.plugin.zsh b/plugins/chruby/chruby.plugin.zsh index d7a28d4e2..1210897c4 100644 --- a/plugins/chruby/chruby.plugin.zsh +++ b/plugins/chruby/chruby.plugin.zsh @@ -2,7 +2,7 @@ _source-from-omz-settings() { local _chruby_path _chruby_auto - + zstyle -s :omz:plugins:chruby path _chruby_path || return 1 zstyle -s :omz:plugins:chruby auto _chruby_auto || return 1 @@ -23,7 +23,7 @@ _source-from-homebrew() { if [[ -h /usr/local/opt/chruby ]];then _brew_prefix="/usr/local/opt/chruby" else - # ok , it is not default prefix + # ok , it is not default prefix # this call to brew is expensive ( about 400 ms ), so at least let's make it only once _brew_prefix=$(brew --prefix chruby) fi diff --git a/plugins/cloudfoundry/README.md b/plugins/cloudfoundry/README.md index 89dd9d1ce..567a9056b 100644 --- a/plugins/cloudfoundry/README.md +++ b/plugins/cloudfoundry/README.md @@ -50,7 +50,7 @@ Alternatively, seek out the [online documentation][3]. And don't forget, there a ## Contributors -Contributed to `oh_my_zsh` by [benwilcock][2]. +Contributed to `oh_my_zsh` by [benwilcock][2]. [1]: https://docs.cloudfoundry.org/cf-cli/install-go-cli.html [2]: https://github.com/benwilcock diff --git a/plugins/coffee/README.md b/plugins/coffee/README.md index 2baade844..c2ab192b6 100644 --- a/plugins/coffee/README.md +++ b/plugins/coffee/README.md @@ -24,7 +24,7 @@ Also provides the following aliases: * **cfc:** Copies the compiled JS to your clipboard. Very useful when you want to run the code in a JS console. -* **cfp:** Compiles from your currently copied clipboard. Useful when you want +* **cfp:** Compiles from your currently copied clipboard. Useful when you want to compile large/multi-line snippets * **cfpc:** Paste coffeescript from clipboard, compile to JS, then copy the diff --git a/plugins/compleat/compleat.plugin.zsh b/plugins/compleat/compleat.plugin.zsh index 38f1b396a..7fbd2b953 100644 --- a/plugins/compleat/compleat.plugin.zsh +++ b/plugins/compleat/compleat.plugin.zsh @@ -7,7 +7,7 @@ if (( ${+commands[compleat]} )); then local prefix="${commands[compleat]:h:h}" - local setup="${prefix}/share/compleat-1.0/compleat_setup" + local setup="${prefix}/share/compleat-1.0/compleat_setup" if [[ -f "$setup" ]]; then if ! bashcompinit >/dev/null 2>&1; then @@ -15,6 +15,6 @@ if (( ${+commands[compleat]} )); then bashcompinit -i fi - source "$setup" + source "$setup" fi fi diff --git a/plugins/copybuffer/copybuffer.plugin.zsh b/plugins/copybuffer/copybuffer.plugin.zsh index e67f920f0..e636d9730 100644 --- a/plugins/copybuffer/copybuffer.plugin.zsh +++ b/plugins/copybuffer/copybuffer.plugin.zsh @@ -1,8 +1,8 @@ -# copy the active line from the command line buffer +# copy the active line from the command line buffer # onto the system clipboard copybuffer () { - if which clipcopy &>/dev/null; then + if builtin which clipcopy &>/dev/null; then printf "%s" "$BUFFER" | clipcopy else zle -M "clipcopy not found. Please make sure you have Oh My Zsh installed correctly." diff --git a/plugins/dash/README.md b/plugins/dash/README.md index 0ca3e4e44..970c6541f 100644 --- a/plugins/dash/README.md +++ b/plugins/dash/README.md @@ -19,7 +19,7 @@ dash - Query for something in dash app: `dash query` ``` -dash golang +dash golang ``` - You can optionally provide a keyword: `dash [keyword:]query` diff --git a/plugins/dotnet/dotnet.plugin.zsh b/plugins/dotnet/dotnet.plugin.zsh index 40ee7efae..ed7c55024 100644 --- a/plugins/dotnet/dotnet.plugin.zsh +++ b/plugins/dotnet/dotnet.plugin.zsh @@ -11,7 +11,7 @@ _dotnet_completion() { compdef _dotnet_completion dotnet # Aliases bellow are here for backwards compatibility -# added by Shaun Tabone (https://github.com/xontab) +# added by Shaun Tabone (https://github.com/xontab) alias dn='dotnet new' alias dr='dotnet run' diff --git a/plugins/emoji/emoji.plugin.zsh b/plugins/emoji/emoji.plugin.zsh index f9e476ebf..f7be56cf7 100644 --- a/plugins/emoji/emoji.plugin.zsh +++ b/plugins/emoji/emoji.plugin.zsh @@ -24,7 +24,7 @@ unset _omz_emoji_plugin_dir # This is a combining character that can be placed after any other character to surround # it in a "keycap" symbol. -# The digits 0-9 are already in the emoji table as keycap_digit_, keycap_ten, etc. +# The digits 0-9 are already in the emoji table as keycap_digit_, keycap_ten, etc. # It's unclear whether this should be in the $emoji array, because those characters are all ones # which can be displayed on their own. @@ -63,9 +63,9 @@ function random_emoji() { [[ $list_size -eq 0 ]] && return 1 local random_index=$(( ( RANDOM % $list_size ) + 1 )) local name=${names[$random_index]} - if [[ "$group" == "flags" ]]; then + if [[ "$group" == "flags" ]]; then echo ${emoji_flags[$name]} - else + else echo ${emoji[$name]} fi } @@ -86,22 +86,22 @@ function display_emoji() { # terminals treat these emoji chars as single-width. local counter=1 for i in $names; do - if [[ "$group" == "flags" ]]; then + if [[ "$group" == "flags" ]]; then printf '%s ' "$emoji_flags[$i]" - else - printf '%s ' "$emoji[$i]" + else + printf '%s ' "$emoji[$i]" fi # New line every 20 emoji, to avoid weirdnesses if (($counter % 20 == 0)); then - printf "\n" + printf "\n" fi let counter=$counter+1 done print for i in $names; do - if [[ "$group" == "flags" ]]; then + if [[ "$group" == "flags" ]]; then echo "${emoji_flags[$i]} = $i" - else + else echo "${emoji[$i]} = $i" fi done diff --git a/plugins/emotty/emotty.plugin.zsh b/plugins/emotty/emotty.plugin.zsh index 661169a8b..b48d121dc 100644 --- a/plugins/emotty/emotty.plugin.zsh +++ b/plugins/emotty/emotty.plugin.zsh @@ -4,7 +4,7 @@ # AUTHOR: Alexis Hildebrandt (afh[at]surryhill.net) # VERSION: 1.0.0 # DEPENDS: emoji plugin -# +# # There are different sets of emoji characters available, to choose a different # set export emotty_set to the name of the set you would like to use, e.g.: # % export emotty_set=nature diff --git a/plugins/encode64/README.md b/plugins/encode64/README.md index 7cdf8c3f3..e3e25a742 100644 --- a/plugins/encode64/README.md +++ b/plugins/encode64/README.md @@ -40,7 +40,7 @@ plugins=(... encode64) ### Encoding a file -Encode a file's contents to base64 and save output to text 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 diff --git a/plugins/extract/extract.plugin.zsh b/plugins/extract/extract.plugin.zsh index 80ca50c50..1c7599195 100644 --- a/plugins/extract/extract.plugin.zsh +++ b/plugins/extract/extract.plugin.zsh @@ -87,7 +87,7 @@ EOF builtin cd -q control; extract ../control.tar.* builtin cd -q ../data; extract ../data.tar.* builtin cd -q ..; command rm *.tar.* debian-binary ;; - (*.zst) unzstd "$full_path" ;; + (*.zst) unzstd --stdout "$full_path" > "${file:t:r}" ;; (*.cab|*.exe) cabextract "$full_path" ;; (*.cpio|*.obscpio) cpio -idmvF "$full_path" ;; (*.zpaq) zpaq x "$full_path" ;; diff --git a/plugins/fancy-ctrl-z/README.md b/plugins/fancy-ctrl-z/README.md index f1b1dfa5c..82a4fd75e 100644 --- a/plugins/fancy-ctrl-z/README.md +++ b/plugins/fancy-ctrl-z/README.md @@ -1,14 +1,14 @@ # Use Ctrl-Z to switch back to Vim -I frequently need to execute random commands in my shell. To achieve it I pause +I frequently need to execute random commands in my shell. To achieve it I pause Vim by pressing Ctrl-z, type command and press fg to switch back to Vim. -The fg part really hurts me. I just wanted to hit Ctrl-z once again to get back -to Vim. I could not find a solution, so I developed one on my own that +The fg part really hurts me. I just wanted to hit Ctrl-z once again to get back +to Vim. I could not find a solution, so I developed one on my own that works wonderfully with ZSH. Source: http://sheerun.net/2014/03/21/how-to-boost-your-vim-productivity/ -Credits: +Credits: - original idea by @sheerun - added to OMZ by @mbologna diff --git a/plugins/fastfile/README.md b/plugins/fastfile/README.md index 32f619ffd..7291fde38 100644 --- a/plugins/fastfile/README.md +++ b/plugins/fastfile/README.md @@ -71,13 +71,13 @@ them, add `=` to your zshrc file, before Oh My Zsh is sourced. For example: `fastfile_var_prefix='@'`. - `fastfile_var_prefix`: prefix for the global aliases created. Controls the prefix of the - created global aliases. + created global aliases. **Default:** `§` (section sign), easy to type in a german keyboard via the combination [`⇧ Shift`+`3`](https://en.wikipedia.org/wiki/German_keyboard_layout#/media/File:KB_Germany.svg), or using `⌥ Option`+`6` in macOS. - `fastfile_dir`: directory where the fastfile shortcuts are stored. Needs to end - with a trailing slash. + with a trailing slash. **Default:** `$HOME/.fastfile/`. ## Author diff --git a/plugins/forklift/forklift.plugin.zsh b/plugins/forklift/forklift.plugin.zsh index 85889481b..848aedabf 100644 --- a/plugins/forklift/forklift.plugin.zsh +++ b/plugins/forklift/forklift.plugin.zsh @@ -58,7 +58,7 @@ function fl { tell application forkLiftSetapp activate set forkLiftVersion to version - end tell + end tell else if forkLift3 is not null and application forkLift3 is running then tell application forkLift3 activate @@ -84,7 +84,7 @@ function fl { else if forkLift is not null then set appName to forkLift end if - + tell application appName activate set forkLiftVersion to version diff --git a/plugins/fzf/fzf.plugin.zsh b/plugins/fzf/fzf.plugin.zsh index 7312e3d26..e244b4cfb 100644 --- a/plugins/fzf/fzf.plugin.zsh +++ b/plugins/fzf/fzf.plugin.zsh @@ -1,3 +1,16 @@ +function fzf_setup_using_fzf() { + (( ${+commands[fzf]} )) || return 1 + + # we remove "fzf " prefix, this fixes really old fzf versions behaviour + # see https://github.com/ohmyzsh/ohmyzsh/issues/12387 + local fzf_ver=${"$(fzf --version)"#fzf } + + autoload -Uz is-at-least + is-at-least 0.48.0 ${${(s: :)fzf_ver}[1]} || return 1 + + eval "$(fzf --zsh)" +} + function fzf_setup_using_base_dir() { local fzf_base fzf_shell fzfdirs dir @@ -62,7 +75,7 @@ function fzf_setup_using_base_dir() { function fzf_setup_using_debian() { if (( ! $+commands[apt] && ! $+commands[apt-get] )); then - # Not a debian based distro + # Not a debian based distro return 1 fi @@ -135,6 +148,27 @@ function fzf_setup_using_opensuse() { return 0 } +function fzf_setup_using_fedora() { + (( $+commands[fzf] )) || return 1 + + local completions="/usr/share/zsh/site-functions/fzf" + local key_bindings="/usr/share/fzf/shell/key-bindings.zsh" + + if [[ ! -f "$completions" || ! -f "$key_bindings" ]]; then + return 1 + fi + + if [[ -o interactive && "$DISABLE_FZF_AUTO_COMPLETION" != "true" ]]; then + source "$completions" 2>/dev/null + fi + + if [[ "$DISABLE_FZF_KEY_BINDINGS" != "true" ]]; then + source "$key_bindings" 2>/dev/null + fi + + return 0 +} + function fzf_setup_using_openbsd() { # openBSD installs fzf in /usr/local/bin/fzf if [[ "$OSTYPE" != openbsd* ]] || (( ! $+commands[fzf] )); then @@ -217,9 +251,11 @@ Please add `export FZF_BASE=/path/to/fzf/install/dir` to your .zshrc EOF } -fzf_setup_using_openbsd \ +fzf_setup_using_fzf \ + || fzf_setup_using_openbsd \ || fzf_setup_using_debian \ || fzf_setup_using_opensuse \ + || fzf_setup_using_fedora \ || fzf_setup_using_cygwin \ || fzf_setup_using_macports \ || fzf_setup_using_base_dir \ diff --git a/plugins/gcloud/gcloud.plugin.zsh b/plugins/gcloud/gcloud.plugin.zsh index cf3d650ea..fa8f884a4 100644 --- a/plugins/gcloud/gcloud.plugin.zsh +++ b/plugins/gcloud/gcloud.plugin.zsh @@ -9,6 +9,7 @@ if [[ -z "${CLOUDSDK_HOME}" ]]; then "/usr/local/share/google-cloud-sdk" "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk" "/opt/homebrew/Caskroom/google-cloud-sdk/latest/google-cloud-sdk" + "/opt/homebrew/share/google-cloud-sdk" "/usr/share/google-cloud-sdk" "/snap/google-cloud-sdk/current" "/snap/google-cloud-cli/current" diff --git a/plugins/git-prompt/README.md b/plugins/git-prompt/README.md index 05208d72f..8f42c6842 100644 --- a/plugins/git-prompt/README.md +++ b/plugins/git-prompt/README.md @@ -9,6 +9,10 @@ To use it, add `git-prompt` to the plugins array in your zshrc file: plugins=(... git-prompt) ``` +You may also need to [customize your theme](https://github.com/ohmyzsh/ohmyzsh/issues/9395#issuecomment-1027130429) +to change the way the prompt is built. See the +[OMZ wiki on customizing themes](https://github.com/ohmyzsh/ohmyzsh/wiki/Customization#overriding-and-adding-themes). + See the [original repository](https://github.com/olivierverdier/zsh-git-prompt). ## Requirements diff --git a/plugins/git/README.md b/plugins/git/README.md index 4acb0c858..4022f8c62 100644 --- a/plugins/git/README.md +++ b/plugins/git/README.md @@ -41,8 +41,8 @@ plugins=(... git) | `gba` | `git branch --all` | | `gbd` | `git branch --delete` | | `gbD` | `git branch --delete --force` | -| `gbgd` | `LANG=C git branch --no-color -vv \| grep ": gone\]" \| awk '"'"'{print $1}'"'"' \| xargs git branch -d` | -| `gbgD` | `LANG=C git branch --no-color -vv \| grep ": gone\]" \| awk '"'"'{print $1}'"'"' \| xargs git branch -D` | +| `gbgd` | `LANG=C git branch --no-color -vv \| grep ": gone\]" \| cut -c 3- \| awk '"'"'{print $1}'"'"' \| xargs git branch -d` | +| `gbgD` | `LANG=C git branch --no-color -vv \| grep ": gone\]" \| cut -c 3- \| awk '"'"'{print $1}'"'"' \| xargs git branch -D` | | `gbm` | `git branch --move` | | `gbnm` | `git branch --no-merged` | | `gbr` | `git branch --remote` | @@ -111,6 +111,7 @@ plugins=(... git) | `gfg` | `git ls-files \| grep` | | `gm` | `git merge` | | `gma` | `git merge --abort` | +| `gmc` | `git merge --continue` | | `gms` | `git merge --squash` | | `gmom` | `git merge origin/$(git_main_branch)` | | `gmum` | `git merge upstream/$(git_main_branch)` | @@ -166,6 +167,7 @@ plugins=(... git) | `grhk` | `git reset --keep` | | `grhs` | `git reset --soft` | | `gpristine` | `git reset --hard && git clean --force -dfx` | +| `gwipe` | `git reset --hard && git clean --force -df` | | `groh` | `git reset origin/$(git_current_branch) --hard` | | `grs` | `git restore` | | `grss` | `git restore --source` | diff --git a/plugins/git/git.plugin.zsh b/plugins/git/git.plugin.zsh index 692a36a73..c48e365b5 100644 --- a/plugins/git/git.plugin.zsh +++ b/plugins/git/git.plugin.zsh @@ -147,8 +147,8 @@ function gbds() { done } -alias gbgd='LANG=C git branch --no-color -vv | grep ": gone\]" | awk '"'"'{print $1}'"'"' | xargs git branch -d' -alias gbgD='LANG=C git branch --no-color -vv | grep ": gone\]" | awk '"'"'{print $1}'"'"' | xargs git branch -D' +alias gbgd='LANG=C git branch --no-color -vv | grep ": gone\]" | cut -c 3- | awk '"'"'{print $1}'"'"' | xargs git branch -d' +alias gbgD='LANG=C git branch --no-color -vv | grep ": gone\]" | cut -c 3- | awk '"'"'{print $1}'"'"' | xargs git branch -D' alias gbm='git branch --move' alias gbnm='git branch --no-merged' alias gbr='git branch --remote' @@ -252,6 +252,7 @@ alias gignored='git ls-files -v | grep "^[[:lower:]]"' alias gfg='git ls-files | grep' alias gm='git merge' alias gma='git merge --abort' +alias gmc='git merge --continue' alias gms="git merge --squash" alias gmom='git merge origin/$(git_main_branch)' alias gmum='git merge upstream/$(git_main_branch)' @@ -349,6 +350,7 @@ alias grhh='git reset --hard' alias grhk='git reset --keep' alias grhs='git reset --soft' alias gpristine='git reset --hard && git clean --force -dfx' +alias gwipe='git reset --hard && git clean --force -df' alias groh='git reset origin/$(git_current_branch) --hard' alias grs='git restore' alias grss='git restore --source' diff --git a/plugins/gnu-utils/gnu-utils.plugin.zsh b/plugins/gnu-utils/gnu-utils.plugin.zsh index 6023bf2b4..adc2bd3bb 100644 --- a/plugins/gnu-utils/gnu-utils.plugin.zsh +++ b/plugins/gnu-utils/gnu-utils.plugin.zsh @@ -14,7 +14,7 @@ __gnu_utils() { local -a gcmds local gcmd - # coreutils + # coreutils gcmds=('g[' 'gbase64' 'gbasename' 'gcat' 'gchcon' 'gchgrp' 'gchmod' 'gchown' 'gchroot' 'gcksum' 'gcomm' 'gcp' 'gcsplit' 'gcut' 'gdate' 'gdd' 'gdf' 'gdir' 'gdircolors' 'gdirname' 'gdu' 'gecho' 'genv' 'gexpand' @@ -41,7 +41,7 @@ __gnu_utils() { for gcmd in "${gcmds[@]}"; do # Do nothing if the command isn't found (( ${+commands[$gcmd]} )) || continue - + # This method allows for builtin commands to be primary but it's # lost if hash -r or rehash is executed, or if $PATH is updated. # Thus, a preexec hook is needed, which will only run if whoami diff --git a/plugins/grails/grails.plugin.zsh b/plugins/grails/grails.plugin.zsh index ddc257428..e5dceb530 100644 --- a/plugins/grails/grails.plugin.zsh +++ b/plugins/grails/grails.plugin.zsh @@ -7,7 +7,7 @@ _enumerateGrailsScripts() { then directories+=(plugins/*/scripts) fi - + # Enumerate all of the Groovy files files=() for dir in $directories; @@ -17,13 +17,13 @@ _enumerateGrailsScripts() { files+=($dir/[^_]*.groovy) fi done - + # Don't try to basename () if [ ${#files} -eq 0 ]; then return fi - + scripts=() for file in $files do @@ -42,19 +42,19 @@ _enumerateGrailsScripts() { done echo $scripts } - + _grails() { if (( CURRENT == 2 )); then scripts=( $(_enumerateGrailsScripts) ) - + if [ ${#scripts} -ne 0 ]; then _multi_parts / scripts return fi fi - + _files } - + compdef _grails grails diff --git a/plugins/history-substring-search/README.md b/plugins/history-substring-search/README.md index 71a389535..4be744c4c 100644 --- a/plugins/history-substring-search/README.md +++ b/plugins/history-substring-search/README.md @@ -57,13 +57,13 @@ Using [antigen](https://github.com/zsh-users/antigen): 1. Add the `antigen bundle` command just before `antigen apply`, like this: -``` +``` antigen bundle zsh-users/zsh-history-substring-search antigen apply ``` - + 2. Then, **after** `antigen apply`, add the key binding configurations, like this: - + ``` # zsh-history-substring-search configuration bindkey '^[[A' history-substring-search-up # or '\eOA' @@ -120,7 +120,7 @@ Usage bindkey "$terminfo[kcuu1]" history-substring-search-up bindkey "$terminfo[kcud1]" history-substring-search-down - Users have also observed that `[OA` and `[OB` are correct values, + Users have also observed that `[OA` and `[OB` are correct values, _even if_ these were not the observed values. If you are having trouble with the observed values, give these a try. diff --git a/plugins/httpie/_httpie b/plugins/httpie/_httpie index 11bc8e1f8..2c0db229f 100644 --- a/plugins/httpie/_httpie +++ b/plugins/httpie/_httpie @@ -1,4 +1,4 @@ -#compdef http +#compdef http https # ------------------------------------------------------------------------------ # Copyright (c) 2015 GitHub zsh-users - http://github.com/zsh-users # All rights reserved. diff --git a/plugins/ionic/ionic.plugin.zsh b/plugins/ionic/ionic.plugin.zsh index cf388af1b..e3913b549 100644 --- a/plugins/ionic/ionic.plugin.zsh +++ b/plugins/ionic/ionic.plugin.zsh @@ -3,13 +3,13 @@ alias ih="ionic --help" alias ist="ionic start" alias ii="ionic info" alias is="ionic serve" -alias icba="ionic cordova build android" -alias icbi="ionic cordova build ios" -alias icra="ionic cordova run android" -alias icri="ionic cordova run ios" -alias icrsa="ionic cordova resources android" +alias icba="ionic cordova build android" +alias icbi="ionic cordova build ios" +alias icra="ionic cordova run android" +alias icri="ionic cordova run ios" +alias icrsa="ionic cordova resources android" alias icrsi="ionic cordova resources ios" -alias icpaa="ionic cordova platform add android" +alias icpaa="ionic cordova platform add android" alias icpai="ionic cordova platform add ios" alias icpra="ionic cordova platform rm android" alias icpri="ionic cordova platform rm ios" diff --git a/plugins/iterm2/README.md b/plugins/iterm2/README.md index 3d11622df..86bd77f1d 100644 --- a/plugins/iterm2/README.md +++ b/plugins/iterm2/README.md @@ -9,7 +9,7 @@ plugins=(... iterm2) ``` Optionally, the plugin also applies the [Shell Integration Script for iTerm2](https://iterm2.com/documentation-shell-integration.html). -You can enable the integration with zstyle. It's important to add this line +You can enable the integration with zstyle. It's important to add this line before the line sourcing oh-my-zsh: ``` diff --git a/plugins/iterm2/iterm2.plugin.zsh b/plugins/iterm2/iterm2.plugin.zsh index d00232a30..03a63a70c 100644 --- a/plugins/iterm2/iterm2.plugin.zsh +++ b/plugins/iterm2/iterm2.plugin.zsh @@ -8,7 +8,7 @@ if [[ "$OSTYPE" == darwin* ]] && [[ -n "$ITERM_SESSION_ID" ]] ; then # maybe make it the default in the future and allow opting out? - if zstyle -t ':omz:plugins:iterm2' shell-integration; then + if zstyle -t ':omz:plugins:iterm2' shell-integration; then # Handle $0 according to the standard: # https://zdharma-continuum.github.io/Zsh-100-Commits-Club/Zsh-Plugin-Standard.html 0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}" diff --git a/plugins/iterm2/iterm2_shell_integration.zsh b/plugins/iterm2/iterm2_shell_integration.zsh index 7871ddded..281332e0d 100644 --- a/plugins/iterm2/iterm2_shell_integration.zsh +++ b/plugins/iterm2/iterm2_shell_integration.zsh @@ -2,12 +2,12 @@ # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. -# +# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -# +# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. diff --git a/plugins/jira/README.md b/plugins/jira/README.md index d78ea15a4..1c6930298 100644 --- a/plugins/jira/README.md +++ b/plugins/jira/README.md @@ -16,23 +16,26 @@ This plugin supplies one command, `jira`, through which all its features are exp ## Commands +`jira help` or `jira usage` will print the below usage instructions + | Command | Description | | :------------ | :-------------------------------------------------------- | | `jira` | Performs the default action | | `jira new` | Opens a new Jira issue dialogue | | `jira ABC-123` | Opens an existing issue | | `jira ABC-123 m` | Opens an existing issue for adding a comment | -| `jira dashboard [rapid_view]` | # opens your JIRA dashboard | +| `jira dashboard [rapid_view]` | Opens your JIRA dashboard | | `jira mine` | Queries for your own issues | | `jira tempo` | Opens your JIRA Tempo | | `jira reported [username]` | Queries for issues reported by a user | | `jira assigned [username]` | Queries for issues assigned to a user | | `jira branch` | Opens an existing issue matching the current branch name | +| `jira help` | Prints usage instructions | ### Jira Branch usage notes -The branch name may have prefixes ending in "/": "feature/MP-1234", and also suffixes +The branch name may have prefixes ending in "/": "feature/MP-1234", and also suffixes starting with "_": "MP-1234_fix_dashboard". In both these cases, the issue opened will be "MP-1234" This is also checks if the prefix is in the name, and adds it if not, so: "MP-1234" opens the issue "MP-1234", diff --git a/plugins/jira/_jira b/plugins/jira/_jira index 0e37b7e9d..5f7dcd09d 100644 --- a/plugins/jira/_jira +++ b/plugins/jira/_jira @@ -11,6 +11,7 @@ _1st_arguments=( 'assigned:search for issues assigned to a user' 'branch:open the issue named after the git branch of the current directory' 'dumpconfig:display effective jira configuration' + 'help:print usage help to stdout' ) _arguments -C \ diff --git a/plugins/jira/jira.plugin.zsh b/plugins/jira/jira.plugin.zsh index b6ee9f100..9bcf4cc7b 100644 --- a/plugins/jira/jira.plugin.zsh +++ b/plugins/jira/jira.plugin.zsh @@ -2,6 +2,21 @@ # # See README.md for details +function _jira_usage() { +cat <