55 Commits

Author SHA1 Message Date
aee45ba2ee Added zsh functions for managing zrep packages. Fixed bugs in zrep functions. Updated zrep version to 0.0.7. 2024-04-05 21:43:51 +02:00
ae6becb2cc Updated zrep script to version 0.0.7 with new features and improvements.
- Updated version to 0.0.7
- Added URL-encoding function for search queries
- Implemented search function to query and process JSON response
- Refactored package removal function
- Added check for 'jq' installation
- Improved package installation process
- Enhanced update package functionality
- Added search command to search for authors, packages, or descriptions
2024-04-05 00:36:24 +02:00
8ea89b837b Added search function link to zrep website.
Added note about future search function in zrep script.
2024-04-04 13:12:53 +02:00
e37233009c Update README with information about zrep tool and its usage. Added a section explaining what zrep is and how to share scripts. 2024-04-04 13:07:14 +02:00
6399a20ed1 Updated zrep version to 0.0.6
- Updated version to 0.0.6
- Changed repo_url to https://zrep.kekepower.com
- Added reminder to copy 'zrep' to a directory in 'PATH'
- Added reminder to source ${zshrc_file} after installation.
2024-04-03 13:57:43 +02:00
2e0d42c040 Updated zrep version to 0.0.5
- Updated version to 0.0.5
- Added validation for package name format
- Display error message if package name format is incorrect
2024-04-02 21:57:39 +02:00
8f34150a78 Update zrep script to version 0.0.4
- Updated version number to 0.0.4
- Added timestamp to remoteFile URL
- Improved update_package function logic
- Added prompt for user confirmation before updating
- Updated downloader commands for curl, wget, and wget2
- Improved error handling in download_package function
- Improved installation process in install_package function
2024-03-31 15:14:43 +02:00
c4c384c799 Use PNG instead of SVG for logo 2024-03-17 09:05:41 +01:00
d0fed1720e Update zrep to version 0.0.3. New zrep-logo.svg. Bug fixes and enhancements. 2024-03-17 09:04:23 +01:00
c3962c72a0 Title: Fix debug message in zrep script
- Updated debug message in zrep script to include a newline character.
- Improved error handling for when package is not found.
2024-03-16 00:29:32 +01:00
255649a53e Title: Update zrep function to exit instead of return
- Changed `return 1` to `exit 1` in zrep_parse_remote function.
2024-03-16 00:29:07 +01:00
a64e876b7d Added return statement when package is not found in zrep_parse_remote function.
- Added return 1 when package is not found.
2024-03-16 00:27:27 +01:00
a50a99183b Added touch command to create installed.json if not found.
Included error message for clarity.
2024-03-16 00:18:25 +01:00
fcf519dd68 Added conditional check to load config and theme only if argument is not "init". 2024-03-16 00:14:36 +01:00
dd518d733b Refactor zrep_load_config function in zrep script:
- Indent zrep_init call properly.
- Add else block to handle setup abort.
- Provide feedback message for setup abortion.
2024-03-16 00:11:00 +01:00
7243ae4235 Added user interaction for setting up zrep for the first time.
- Display welcome message when running zrep for the first time.
- Prompt user to set up zrep if config file is not found.
- Added user confirmation before running 'zrep init'.
2024-03-16 00:10:00 +01:00
3345f78b7a Update zrep script:
- Comment out unused variable assignment.
- Add installation path to theme installation message.
- Prompt user to initialize config if not found.
- Provide welcome message for first-time users.
2024-03-16 00:06:08 +01:00
ba1829953c Added directory creation for install_dir
Added autoload for zini
Added creation of .addons file
Added installation of Classic theme
Updated zrep initialization process
2024-03-15 23:58:20 +01:00
03adceec67 Title: Update unzip command in zrep script
- Changed unzip command to use quiet mode
- Ensured overwrite of existing files during extraction
- Improved error handling for unzip operation
2024-03-15 23:23:20 +01:00
7da1c425f4 Title: Fix unzip command order in zrep script
Changes:
- Reordered unzip command options in zrep script for correct execution.
2024-03-15 23:21:29 +01:00
3830e58ebb Update unzip command in zrep script to use -aa flag for better compatibility.
- Use `-aa` flag in unzip command for better compatibility with various zip formats.
2024-03-15 23:19:05 +01:00
4337b13a28 Update zrep script with autoload fix and debug message in zrep_install_package function.
- Fix autoload command in zrep script.
- Add debug message in zrep_install_package function.
2024-03-15 23:14:47 +01:00
e314131622 Update zrep script to display a newline before "No packages installed" message.
Add newline character before the message to improve readability.
2024-03-15 22:56:38 +01:00
b160120893 Update zrep script to handle cases where installed.json is empty or contains no packages. Add checks to handle empty JSON objects or arrays. 2024-03-15 22:55:52 +01:00
d4e355cf32 Update zrep script with improvements in file existence check and script entry handling. Fix JSON file creation and ensure it's not empty. Refactor script entry update/addition logic for better clarity. Rearrange curl command options for zrep_download_package function. 2024-03-15 22:45:37 +01:00
c297c2a551 Update curl command in zrep script for downloading packages. Fix duplicate output redirection. 2024-03-15 22:39:24 +01:00
c92eb49c05 Added conditional check for zrep initialization.
Created files .addons and installed.json during zrep initialization.
2024-03-15 22:35:41 +01:00
17355e5779 Title: Fix downloader selection logic in zrep script
- Fixed logical OR conditions to logical AND in downloader selection.
- Improved user input validation for downloader selection.
- Added error messages for invalid downloader choices.
- Updated zrep script for correct downloader selection logic.
2024-03-15 22:19:23 +01:00
53bd010da6 Title: Update zrep script with downloader choice validation
- Fixed downloader choice validation in zrep_init function
- Moved zrep_fpath and autoload commands to else block for existing config handling
2024-03-15 22:16:33 +01:00
de3bb15662 Title: Update zrep script with enhanced downloader function
- Added user prompt to choose downloader command
- Enhanced zrep_download_package function with retry logic
- Updated zrep_help function for better readability
- Added zrep_package_info function to display package details
2024-03-15 22:10:39 +01:00
17c9058be5 Added 'curl' to the list of required programs in zrep script. 2024-03-15 11:53:45 +01:00
d0210580b1 Refactor zrep_list_installed_packages function
- Added zmodload zsh/regex for regex support
- Changed grep to regex match for package activation check
- Updated zrep_msg output format
2024-03-14 16:24:48 +01:00
40adc05b9b Update zrep script:
- Changed comment to define default path for .zreprc
- Updated comment to define list of colors available for themes
- Removed clearing of previous theme settings
- Added function to check if a string exists in ~/.zshrc
- Added function to check for required dependencies
- Updated zrep_init function to include checking for dependencies
- Updated zrep_init function to create default file and directory structure
- Updated zrep_init function to check for existing zini path in .zshrc
- Updated zrep_init function to check for existing source command for .zrep_addons in .zshrc
- Updated zrep_init function to create or update .zrep_addons file
- Updated zrep_check_for_updates function to display message if no updates found
- Removed redundant message in zrep_update_package function
- Updated zrep_download_package function to display download attempt message
- Updated zrep_download_package function to display download successful message
- Updated zrep_install_package function to include fetching package information
- Removed commented out line in zrep_install_package function
- Removed commented out line in zrep_parse_package_name function
2024-03-13 22:52:47 +01:00
a492260ec9 Update zrep version to 0.0.2
- Updated zrep version to 0.0.2
- Improved error messages for package not found
- Enhanced output messages for installed packages
- Improved error handling for package installation
- Enhanced error messages for package not installed
- Added 'del' alias for 'remove' command
- Improved usage message for 'remove' command
2024-03-13 07:25:59 +01:00
de29949486 Update zrep script with new color scheme and theme loading functionality.
- Added new base_colors associative array for color definitions.
- Implemented zrep_load_theme function to load themes.
- Modified zrep_msg function to use colors from the current theme.
- Updated zrep_version function to use theme colors for help and info.
- Adjusted zrep_list_installed_packages to use base_colors for color definitions.
- Enhanced zrep_update_package with informative messages.
- Added zrep_download_package function for downloading packages.
- Improved zrep_install_package to use zrep_download_package for downloads.
- Updated main function to load the global theme.
2024-03-12 23:52:10 +01:00
7ddcd309c5 Added export statement to fix variable assignment issue in zrep script.
- Fixed variable assignment in zrep script.
2024-03-12 18:07:33 +01:00
548012d7cc Update zrep script with zrep_installed_json function
- Added zrep_installed_json function to handle installed.json existence
- Updated zrep_update_installed_json to use zrep_installed_json
- Updated zrep_list_installed_packages to use zrep_installed_json
- Updated zrep_list_package to use zrep_installed_json
- Updated zrep_remove_package to use zrep_installed_json
- Updated zrep_check_if_installed to use zrep_installed_json
- Updated zrep_check_for_updates to use zrep_installed_json
- Updated zrep_install_package to remove temporary zip files
- Updated zrep_parse_installed_json to use zrep_installed_json
- Updated zrep_parse_package_name to use zrep_installed_json
- Updated zrep_enable and zrep_disable to remove unnecessary sourcing and function calls
- Updated zrep_read_usage to use zrep_installed_json
2024-03-12 18:06:06 +01:00
4d249d2bf1 Update zrep initialization to include global settings and reminder to source zshrc. Check for 'zini' path in fpath before adding. Enhance update logic to handle specific package updates. Improve update messaging and handle no updates found case. Refactor update package function for better readability. Add conditional help message for 'init' command if config file doesn't exist. 2024-03-12 14:58:13 +01:00
849d4e46a4 Updated zrep script to include functions for checking updates, updating specific packages, and installing packages. Added logic to handle package installation, removal, and updating. Improved error handling and messaging for better user experience. Enhanced functionality for managing zrep packages efficiently. 2024-03-11 22:15:43 +01:00
77eb36815b Minor changes and cleanups 2024-03-10 14:03:27 +01:00
02ae618bf1 Clean up comments. Embrace variables. 2024-03-10 13:31:19 +01:00
dbc9a8b6dd Fix zrep script to correctly load addons by moving the 'done' statement inside the 'if' block. 2024-03-10 10:02:08 +01:00
2ebb0fd3b7 Update zrep logo in README.md
Enhance version string color in zrep script
Add bold style to version number in zrep script
Fix autoload command in zrep script
Improve color styling for active/inactive packages in zrep script
2024-03-10 09:49:34 +01:00
cb15f80042 Update README.md 2024-03-09 09:12:02 +01:00
4b6eb5734c revert d7e0a5ec4c
revert Update README.md
2024-03-09 09:09:28 +01:00
d7e0a5ec4c Update README.md 2024-03-09 09:08:51 +01:00
5562ae7986 Update zrep initialization to use ZREP_CONFIG variable for configuration file path. Prompt user for zrep installation directory if ZREP_CONFIG doesn't exist. Add source command for .zrep_addons in .zshrc if not present. Create or update .zrep_addons file with addon handling logic. Modify zrep_enable and zrep_disable functions to use ZREP_CONFIG variable. Update main function to call zrep_load_config. Ensure proper sourcing of .zrep_addons after enabling/disabling packages. Include necessary error handling and informative messages. - Sat, 09 Mar 2024 00:36:09 +0100 2024-03-09 00:36:09 +01:00
5f7c437701 Update zrep script with color definitions using associative array and refactor color usage in functions. Add functionality to display package-specific help from USAGE file. - Wed, 06 Mar 2024 18:33:14 +0100 2024-03-06 18:33:14 +01:00
e3ee9e49a9 Update zrep script:
- Commented out unused variables and echo statements.
- Added check to create installed.json if not exists.
- Improved jq command to update installed.json.
- Refactored zrep_list_installed_packages function.
- Refactored zrep_list_package function to concatenate package names.
- Updated zrep_install_package to use a temporary directory.
- Refactored zrep_enable and zrep_disable functions.
- Added zrep_parse_package_name function for package name parsing. - Mon, 04 Mar 2024 23:40:02 +0100
2024-03-04 23:40:02 +01:00
d1f2b04d5b Update zrep script:
- Added `zrep_main_version_string` function to display version string.
- Modified `zrep_remove_package` function to safely remove directories and update `installed.json`.
- Updated `zrep_help` function to include `enable` and `disable` commands.
- Minor formatting improvements and code cleanup. - Mon, 04 Mar 2024 22:36:49 +0100
2024-03-04 22:36:49 +01:00
469ff49206 Add zrep_enable and zrep_disable functions
- Added zrep_enable function to enable packages in zsh
- Added zrep_disable function to disable packages in zsh
- Updated zrep_help function to include enable and disable commands
- Updated main function to handle enable and disable commands
- Minor formatting and comment improvements in zrep script - Mon, 04 Mar 2024 22:17:21 +0100
2024-03-04 22:17:21 +01:00
bc1c7f4e4f Fix directory removal logic in zrep_remove_package function
- Corrected the logic to check if the first letter directory is empty before deletion
- Updated the README with work-in-progress status and a call for help and feedback - Mon, 04 Mar 2024 20:34:23 +0100
2024-03-04 20:34:23 +01:00
ad7ef3d777 - Refactored zrep_list_installed_packages function to display package status (Active/Inactive).
- Updated zrep_remove_package function to remove package from installed.json after successful removal.
- Added zrep_install_package function to download and install packages from a remote server.
- Minor code cleanup and formatting improvements. - Mon, 04 Mar 2024 20:20:33 +0100
2024-03-04 20:20:33 +01:00
720fc65095 Create space - Fri, 01 Mar 2024 12:22:39 +0100 2024-03-01 12:22:39 +01:00
588848b644 Lots of changes to a few functions - Thu, 29 Feb 2024 16:53:22 +0100 2024-02-29 16:53:22 +01:00
5 changed files with 1036 additions and 357 deletions

View File

@ -1,3 +1,39 @@
# zrep
<img src="zrep-logo.png" width="150" align="left">
The Zsh Repository tool, akin to PyPi and pip
# Zsh Repository Tool (zrep)
zrep is a powerful and user-friendly package manager for the Zsh shell. It allows you to easily install, manage, and share Zsh packages, such as plugins, themes, and scripts, directly from a central repository.
## What is it?
`zrep` in and of itself is the command line tool that you use to install and manage scripts that are placed in `$fpath` used by Zsh. The packages are available on [the zrep website](https://zrep.kekepower.com) where you can, if you want to share your own scripts, register for an account. By sharing your scripts with the community, you are probably making somebody's day easier.
You can read more in the Wiki.
## Key Features
- **Easy Installation**: zrep simplifies the process of installing Zsh packages. With a single command, you can install packages from the zrep repository.
- **Package Management**: zrep provides a set of commands to manage your installed packages. You can list, enable, disable, update, and remove packages effortlessly.
- **Centralized Repository**: All packages are stored in a central repository, making it convenient to discover and share Zsh packages with the community.
- **Automatic Setup**: zrep automatically sets up the necessary configuration files and directories, ensuring a smooth integration with your Zsh environment.
- **Customizable**: zrep allows you to customize the installation directory and other settings through a configuration file.
## Getting Started
To start using zrep, simply run the `zrep init` command to initialize the tool. zrep will guide you through the setup process and create the required configuration files.
Use the search function on **[the zrep website](https://zrep.kekepower.com)** to find useful scripts until a search function is added to the `zrep` script some time in the future.
Once initialized, you can explore and install packages using commands like `zrep install <author/package>`, `zrep list`, and `zrep enable <author/package>`.
## Contributing
zrep is an open-source project, and contributions are welcome! If you have any ideas, bug reports, or feature requests, please open an issue on the GitHub repository.
## License
zrep is released under the MIT License.

10
themes/classic Normal file
View File

@ -0,0 +1,10 @@
# Classic zrep theme
declare -A theme_colors=(
[std]="green"
[info]="yellow"
[debug]="red"
[other]="bold_yellow"
[sub]="magenta"
[main]="white green_bg" # Combining colors for 'main'
[help]="bold_green"
)

988
zpi Executable file
View File

@ -0,0 +1,988 @@
#!/usr/bin/zsh
setopt extendedglob
VERSION="0.0.8" # Fri-2024-04-05
ZREP="Zsh Repository Tool"
# Define the default path to .zreprc
ZREP_CONFIG="${HOME}/.zreprc"
function zrep_fpath() {
local base_dir="${1}"
local mode="${2:-generic}" # Default mode is 'generic'
# Ensure globbing finds dotfiles and nullglob avoids empty directory issues
setopt local_options dotglob nullglob
# Check if the base directory exists
if [[ ! -d "${base_dir}" ]]; then
echo "Error: Base directory '${base_dir}' does not exist."
return 1
fi
if [[ "${mode}" == "zrep_load" ]]; then
# Specific mode for first_letter/author/script structure
for one_char_dir in ${base_dir}/?; do
[[ -d "${one_char_dir}" ]] || continue
for script_dir in ${one_char_dir}/*/*(/); do
local script_name=$(basename "${script_dir}")
local matching_files=("${script_dir}/${script_name}".*)
if (( ${#matching_files} )); then
fpath+=("${script_dir}")
fi
done
done
else
# Generic mode for any directory containing at least one file
for dir in ${base_dir}/**/*(/N); do
if [[ -n $(ls -A "${dir}/") ]]; then
fpath+=("${dir}")
fi
done
fi
}
if [[ ${1} != "init" ]]; then
zrep_fpath ${HOME}/.zrep/functions
autoload -Uz zini
fi
# Define a list of colors available to use in themes
typeset -A base_colors=(
[green]="\033[0;32m"
[yellow]="\033[1;33m"
[red]="\033[0;31m"
[bold_yellow]="\033[1;33m"
[magenta]="\033[0;35m"
[white]="\033[1;37m"
[green_bg]="\033[42m"
[white_on_green]="\033[1;37m\033[42m" # Combined color
[end]="\033[0m"
[black]="\033[0;30m"
[blue]="\033[0;34m"
[cyan]="\033[0;36m"
[bold_black]="\033[1;30m"
[bold_red]="\033[1;31m"
[bold_green]="\033[1;32m"
[bold_blue]="\033[1;34m"
[bold_magenta]="\033[1;35m"
[bold_cyan]="\033[1;36m"
[bold_white]="\033[1;37m"
[black_bg]="\033[40m"
[red_bg]="\033[41m"
[yellow_bg]="\033[43m"
[blue_bg]="\033[44m"
[magenta_bg]="\033[45m"
[cyan_bg]="\033[46m"
[white_bg]="\033[47m"
[underline]="\033[4m"
[italic]="\033[3m"
)
# Define the global associative array to hold the current theme
declare -A current_theme
zrep_load_theme() {
local theme_name="$1"
local theme_file="${config[main_zrep_install_dir]}/themes/${theme_name}"
if [[ ! -f "$theme_file" ]]; then
echo "Error: Theme file for '${theme_name}' not found. Falling back to the 'classic' theme."
theme_file="${config[main_zrep_install_dir]}/themes/classic"
fi
# Source the theme file, which should define 'theme_colors'
source "$theme_file"
# Copy 'theme_colors' to 'current_theme'
for key value in ${(kv)theme_colors}; do
current_theme[$key]="$value"
done
}
function zrep_main_version_string() {
echo "${base_colors[bold_black]}${base_colors[white_bg]} ${ZREP} ${base_colors[end]}${base_colors[bold_white]}${base_colors[black_bg]} ${VERSION} ${base_colors[end]}"
}
function zrep_version() {
zrep_msg info "\nCreated by kekePower - 2024"
zrep_msg info "License: MIT"
zrep_msg info "https://git.kekepower.com/kekePower/zrep/"
zrep_msg info "Please see '${base_colors[${current_theme[help]}]}${ZSH_SCRIPT:t} help${base_colors[end]}${base_colors[${current_theme[info]}]}' for more info${base_colors[end]}"
exit
}
# This function is used to display messages and use colors
# from the loaded theme.
function zrep_msg() {
local msg_type="$1"
local message="$2"
local color="${base_colors[end]}" # Default color is NONE
# Retrieve the color key from the current theme
local theme_color_key="${current_theme[$msg_type]}"
# Check if a valid color was found based on the key
if [[ -n "${base_colors[$theme_color_key]}" ]]; then
color="${base_colors[$theme_color_key]}"
else
# Handle invalid theme color key if needed
echo "Warning: Theme color key '$theme_color_key' not found. Using default." >&2
fi
printf "%b\n" "${color}${message}${base_colors[end]}"
}
#################################################################################################
# Function to URL-encode strings in Zsh
zrep_search_url_encode() {
local string="${1}"
local strlen=${#string}
local encoded=""
for (( pos=0 ; pos<strlen ; pos++ )); do
c=${string:$pos:1}
case "$c" in
[-_.~a-zA-Z0-9] ) o="${c}" ;;
* ) printf -v o '%%%02x' "'$c"
esac
encoded+="${o}"
done
echo "${encoded}"
# This will output the URL-encoded string
}
# Function to perform a search query and process JSON response
zrep_search() {
local searchTerm="${@}"
local encodedSearch=$(zrep_search_url_encode "${searchTerm}")
# Use the global_repo_url from the config associative array
local response=$(curl -s -A "zrep ${VERSION} (curl)" "${config[global_repo_url]}/find.php?s=${encodedSearch}")
# Determine if the JSON response is an object indicating "No scripts found"
local jsonType=$(echo "$response" | jq -r 'type')
zrep_msg std "\nSearch results:"
if [[ "$jsonType" == "object" ]]; then
# Assuming an object type indicates a message field exists
local message=$(echo "$response" | jq -r '.message')
echo "$message"
return 0
elif [[ "$jsonType" == "array" ]]; then
# It's an array, process each item
echo "$response" | jq -c '.[]' | while IFS= read -r line; do
local script=$(echo "$line" | jq -r '.script')
local description=$(echo "$line" | jq -r '.description')
local url=$(echo "$line" | jq -r '.url')
# You can process these variables further as needed
zrep_msg other " * $script"
zrep_msg sub " - Description: $description"
zrep_msg sub " - $url"
# echo "-------------------------------------"
done
else
echo "Unexpected JSON format."
return 1
fi
}
############################################################################################
# Function to check if a given string exists in ~/.zshrc
function zrep_find_string() {
local searchString="$1"
local found=0
while IFS= read -r line || [[ -n $line ]]; do
if [[ "$line" == *"$searchString"* ]]; then
found=1
break
fi
done < "${HOME}/.zshrc"
echo $found
}
function zrep_check_for_deps() {
# Array of required external programs
local required_programs=('jq' "${config[global_downloader]}")
# Iterate over the array
for program in "${required_programs[@]}"; do
# Check if the program is available in the system's PATH
if ! command -v "$program" &> /dev/null; then
# Program not found, display a message
echo "Required program not found: $program"
fi
done
}
# The first step after downloading zrep.
# Here we create the default file and directory structure
function zrep_init() {
local zshrc_file="${HOME}/.zshrc"
local zrep_addons="${HOME}/.zrep_addons"
local install_dir
# Check if .zreprc exists
if [[ ! -f ${ZREP_CONFIG} ]]; then
echo "${ZREP_CONFIG} not found. Creating it..."
# Prompt user for install directory
read "install_dir?Enter zrep installation directory [${HOME}/.zrep]: "
install_dir=${install_dir:-"${HOME}/.zrep"}
mkdir -p ${install_dir}
read "downloader?Choose command to download packages [curl, wget, wget2]: "
if [[ ${downloader} != curl && ${downloader} != wget && ${downloader} != wget2 ]]; then
echo "Invalid choice: '$downloader'. Try again."
read "downloader?Choose command to download packages [curl, wget, wget2] "
if [[ ${downloader} != curl && ${downloader} != wget && ${downloader} != wget2 ]]; then
echo "Invalid choice: '$downloader'. Exiting."
exit
fi
fi
# Write to .zreprc
cat > "${ZREP_CONFIG}" <<EOF
[main]
zrep_install_dir = ${install_dir}
[global]
repo_url = https://zrep.kekepower.com
theme = classic
downloader = ${downloader}
EOF
echo "The file '${ZREP_CONFIG}' has been created."
else
zrep_fpath ${HOME}/.zrep/functions
autoload -Uz zini
echo "Loading configuration from ${ZREP_CONFIG}"
zini ${ZREP_CONFIG}
# install_dir=${config[main_zrep_install_dir]}
fi
if [[ $(zrep_find_string zini) -eq 0 ]]; then
mkdir -p "${install_dir}/functions/zini"
zrep_global_downloader https://raw.githubusercontent.com/kekePower/zini/main/zini -o "${install_dir}/functions/zini/zini"
echo "Adding 'zini' path to fpath in ${zshrc_file}"
echo "fpath=(${install_dir}/functions/zini \$fpath)" >> ${zshrc_file}
autoload -Uz zini
fi
# Check if .zshrc already sources .zrep_addons, if not, add it
if [[ $(zrep_find_string "source ${zrep_addons}") -eq 0 ]]; then
echo "Adding source command for .zrep_addons to .zshrc..."
echo "source ${zrep_addons}" >> "${zshrc_file}"
fi
# Create or update the .zrep_addons file
if [[ ! -f ${zrep_addons} ]]; then
echo "Creating file ${zrep_addons}..."
touch ${install_dir}/.addons
cat > "${zrep_addons}" <<EOF
# Source the .addons file from the zrep installation directory
source "${install_dir}/.addons"
# If addons array is defined and not empty, add its elements to fpath
if [[ -n \${addons[@]} ]]; then
for addon in "\${addons[@]}"; do
if [[ -d \${addon} ]] && [[ ! " \${fpath[*]} " =~ " \${addon} " ]]; then
fpath=(\${addon} "\${fpath[@]}") # Prepend the new addon to fpath
fi
autoload -Uz \$(basename \${addon})
done
else
echo "zrep: No addons enabled."
fi
EOF
echo "File .zrep_addons created and configured."
else
echo "File .zrep_addons already exists. Review manually if update is needed."
fi
if [[ ! -d ${install_dir}/themes ]]; then
echo "Installing the Classic theme to ${install_dir}/themes"
mkdir -p ${install_dir}/themes
zrep_global_downloader https://git.kekepower.com/kekePower/zrep/raw/branch/main/themes/classic -o ${install_dir}/themes/classic
fi
echo "zrep initialization complete."
echo "You should copy 'zrep' to a path in you 'PATH' so that it's accessible."
echo "For example '${HOME}/bin'"
echo "Remember to 'source ${zshrc_file}' to load the 'zrep' settings."
}
function zrep_installed_json() {
# Check if installed.json exists
if [[ ! -f "${config[main_zrep_install_dir]}/installed.json" ]]; then
touch ${config[main_zrep_install_dir]}/installed.json
zrep_msg debug "\nError: installed.json not found."
return 1
else
installed_json="${config[main_zrep_install_dir]}/installed.json"
export installed_json=${installed_json}
fi
}
# Function to parse remote JSON data and extract author, script, and version
# and return the correct download url
function zrep_parse_remote() {
local url="${1}"
local package="${2}"
local author_name="${package%%/*}"
local script_name="${package#*/}"
local json_data
# Fetch JSON data from the URL
json_data=$(zrep_global_downloader "${url}")
# Directly extract the details based on author_name and script_name
version=$(echo "${json_data}" | jq -r --arg author_name "$author_name" --arg script_name "$script_name" '.authors[] | select(.name==$author_name) | .scripts[] | select(.name==$script_name) | .version')
# Check if the dlurl and version are found
if [[ -n "$version" ]]; then
# Set the details as global
#export author="$author_name"
#export script="$script_name"
export version
#export dlurl
else
zrep_msg debug "\nPackage ${package} not found.\n"
exit 1
fi
}
# Function to write to installed.json after successful install
function zrep_update_installed_json() {
local author="${1}"
local script="${2}"
local version="${3}"
zrep_installed_json
# Ensure the JSON file exists and is not empty, creating an empty object if necessary
if [[ ! -f "${installed_json}" ]] || [[ ! -s "${installed_json}" ]]; then
echo "{}" > "${installed_json}"
fi
# Update or add the script entry
jq --arg author "$author" --arg script "$script" --arg version "$version" \
'if has($author) then
.[$author] |= map(if .script == $script then .version = $version else . end) |
if .[$author] | all(.script != $script) then .[$author] += [{"script": $script, "version": $version}] else . end
else
.[$author] = [{"script": $script, "version": $version}]
end' "$installed_json" > "$installed_json.tmp" && mv "$installed_json.tmp" "$installed_json"
zrep_msg info " - Package '$script' by '$author' version $version installed/updated successfully."
}
# Function to list installed packages from installed.json
function zrep_list_installed_packages() {
zrep_installed_json
# Check if installed.json exists and is not empty
if [[ ! -s "${installed_json}" ]]; then
zrep_msg info "\nNo packages installed."
return
fi
# Parse installed.json and list packages
zrep_msg sub "\nInstalled packages:"
# Check if the JSON file is effectively empty ({} or [])
if jq -e 'if type == "object" then . == {} elif type == "array" then . == [] else false end' "${installed_json}" >/dev/null; then
zrep_msg info "\nNo packages installed."
return
fi
# Iterate through each author and their packages
jq -r 'to_entries | .[] | .key as $author | .value[] | "\($author)/\(.script) (\(.version))"' "${installed_json}" | while IFS= read -r package_info; do
local package_name=$(echo "${package_info}" | cut -d ' ' -f1) # Extract package name before the version
local is_active="${base_colors[white]}(${base_colors[end]}${base_colors[bold_red]}Inactive${base_colors[end]}${base_colors[white]})${base_colors[end]}" # Set default to Inactive
zmodload zsh/regex
# Check if the package is active (only modify if active)
if [[ $(<${config[main_zrep_install_dir]}/.addons) =~ "\b${package_name}\b" ]]; then
is_active="${base_colors[white]}(${base_colors[end]}${base_colors[bold_green]}Active${base_colors[end]}${base_colors[white]})${base_colors[end]}"
fi
zrep_msg info " |> ${package_info} ${is_active}"
done
}
function zrep_list_package() {
zrep_installed_json
local package_names=""
# Parse installed.json and concatenate package names
jq -r 'to_entries[] | .key as $author | .value[] | "\($author)/\(.script) (\(.version))"' "${installed_json}" | while IFS= read -r package_info; do
package_names+="${package_info} "
done
# Assuming you want to print out the concatenated package names
if [[ -n "${package_names}" ]]; then
zrep_msg info "\nInstalled packages: ${package_names}"
else
zrep_msg debug "\nNo packages found."
fi
}
function zrep_load_config() {
if [[ ! -x $(which jq) ]]; then
echo "Error: 'jq' is not installed. Please install jq to continue."
exit 1
fi
if [[ -f "${ZREP_CONFIG}" ]]; then
zini "${ZREP_CONFIG}"
zrep_fpath ${config[main_zrep_install_dir]} zrep_load
else
echo "${ZREP_CONFIG} not found. Run 'zrep init' to set up."
exit 1
fi
}
function zrep_remove_package() {
local package_name="${1}"
zrep_installed_json
local author="${package_name%%/*}"
local script="${package_name#*/}"
# Verify if the package is installed and get its version (if any)
local installed_version=$(jq -r --arg author "$author" --arg script "$script" \
'.[$author][] | select(.script == $script) | .version' "$installed_json")
if [[ -z "$installed_version" || "$installed_version" == "null" ]]; then
zrep_msg debug "\nError: Package '${package_name}' is not installed."
zrep_msg info "Please see 'zrep list' for installed packages."
return 1
fi
local first_letter="${author:0:1:l}"
local package_dir="${config[main_zrep_install_dir]}/${first_letter}/${author}/${script}"
zrep_msg std "\nFound installed package: $package_name, version: $installed_version"
# Ask user for confirmation with default response "Y"
zrep_msg info "Are you sure you want to remove this package? (y/n) [Y]: \c"
read REPLY
REPLY=${REPLY:-Y}
echo
if [[ "${REPLY}" =~ ^[Yy]$ ]]; then
# Remove the package directory from disk
if [[ -d "${package_dir}" ]]; then
rm -rf "${package_dir}"
else
zrep_msg debug "Warning: Package directory '${package_dir}' not found."
fi
# Remove the package from installed.json
jq --arg author "$author" --arg script "$script" \
'(.[$author] |= map(select(.script != $script))) |
if .[$author] == [] then del(.[$author]) else . end' \
"$installed_json" > "$installed_json.tmp" && mv "$installed_json.tmp" "$installed_json"
zrep_msg sub "Package '${package_name}' successfully removed."
else
zrep_msg info "Removal canceled."
fi
}
function zrep_check_if_installed() {
local package="${1}"
zrep_installed_json
local author_name="${package%%/*}"
local script_name="${package#*/}"
# Initialize version to an empty string
typeset -g installed_version=""
# Check if the package is already installed and retrieve its version
installed_version=$(jq -r --arg author "$author_name" --arg script "$script_name" \
'.[$author][] | select(.script == $script) | .version' "$installed_json")
if [[ -n "${installed_version}" && "${installed_version}" != "null" ]]; then
# Package is installed, and version is stored in installed_version
return 0 # Package is installed
else
return 1 # Package is not installed
fi
}
function zrep_global_downloader() {
case ${config[global_downloader]} in
curl)
dloader="curl -s -A \"zrep ${VERSION} (curl)\""
;;
wget)
dloader="wget -q -U \"zrep ${VERSION} (wget)\""
;;
wget2)
dloader="wget2 -q -U \"zrep ${VERSION} (wget2)\""
;;
*)
echo "Invalid Downloader."
exit
;;
esac
eval ${dloader} "${1}"
}
function zrep_process_updates() {
for package in ${(k)updatesAvailable}; do
local updateDetails=(${(s/|/)updatesAvailable[${package}]})
local author=${updateDetails[1]}
local script=${updateDetails[2]}
local version=${updateDetails[3]}
echo "Updating ${author}/${script} to version ${version}..."
zrep_install_package u "${author}/${script}" "${version}"
done
}
typeset -A updatesAvailable
function zrep_check_for_updates() {
# Now using a zrep API to fetch the JSON for checking for updates. This _may_ change in the
# future if the load on the DB gets too high.
local remoteFile="${config[global_repo_url]}/getver.php"
# local localFile="${config[main_zrep_install_dir]}/installed.json"
zrep_installed_json
local remotePackages=$(zrep_global_downloader "${remoteFile}")
# Reset global variables
updatesAvailable=()
typeset -g updates=false # Global declaration, initializes to false
# Process updates
local authorsScripts=$(jq -r '. | to_entries[] | .key as $author | .value[] | "\($author)/\(.script):\(.version)"' "$installed_json")
for entry in ${(f)authorsScripts}; do
local author="${entry%%/*}"
local rest="${entry#*/}"
local script="${rest%%:*}"
local installed_version="${rest##*:}"
local remote_version=$(jq -r --arg author "$author" --arg script "$script" \
'.authors[] | select(.name==$author) | .scripts[] | select(.name==$script) | .version' <<<"$remotePackages")
if [[ "${remote_version}" > "${installed_version}" ]]; then
# updatesAvailable[${author}/${script}]="${remote_version}"
# Store author, script, and version in a single string, separated by "|"
updatesAvailable[${author}/${script}]="${author}|${script}|${remote_version}"
zrep_msg info "\n${author}/${script} can be updated from ${installed_version} to ${remote_version}"
updates=true # Mark that updates are available
fi
done
if [[ ${updates} == "false" ]]; then
zrep_msg info "\nNo updates found."
fi
}
function zrep_update_package() {
local specificPackage=${1}
zrep_check_for_updates
if [[ -n "${specificPackage}" ]]; then
# Logic for updating a specific package
# Assuming specificPackage format is "author/script"
local version=${updatesAvailable[${specificPackage}]}
if [[ -n "$version" ]]; then
local author="${specificPackage%%/*}"
local script="${specificPackage#*/}"
local install_pkg="${author}/${script}"
zrep_install_package u ${install_pkg}
else
zrep_msg info "\nNo update available for ${specificPackage}."
fi
else
if [[ ${updates} == "true" ]]; then
# Prompt the user only if updates are available
zrep_msg sub "New updates are available. Do you want to proceed with updating? (Y/n): \c"
read "response"
echo # Move to a new line
# Set the default response to 'Y' if no input is entered
response=${response:-Y}
# Proceed with update if the response is 'Y' or 'y'
if [[ $response =~ ^[Yy]$ ]]; then
# Call zrep_process_updates to handle all updates.
zrep_process_updates
else
zrep_msg info "Update canceled."
fi
fi
fi
}
# Enhanced zrep_downloader function with error handling and retry logic.
# It attempts to download a file from a given URL to a specified zip file using curl, wget, or wget2 based on the global configuration.
# This function supports retries and delays between attempts for robust error handling.
#
# Usage: zrep_download_package ZipFile DownloadURL
#
# Parameters:
# DownloadURL: The URL from which to download the file.
# ZipFile: The name of the file to save the downloaded content to.
function zrep_download_package() {
local ZipFile="${1}"
local DownloadURL="${2}"
local retries=5
local delay=5
local attempt=1
local downloader=""
local http_status
local cmd
local exit_status
case "${config[global_downloader]}" in
curl)
downloader="curl"
cmd="curl -L -A \"zrep ${VERSION} (curl)\" -s -o \"$ZipFile\" \"$DownloadURL\" -w \"%{http_code}\""
;;
wget)
downloader="wget"
cmd="wget -L -U \"zrep ${VERSION} (wget)\" -q -O \"$ZipFile\" \"$DownloadURL\""
;;
wget2)
downloader="wget2"
cmd="wget2 -L -U \"zrep ${VERSION} (wget2)\" -q -O \"$ZipFile\" \"$DownloadURL\""
;;
*)
zrep_msg debug "Unsupported or unspecified downloader: '${config[global_downloader]}'."
return 1
;;
esac
while (( attempt <= retries )); do
# zrep_msg sub "Attempt $attempt of $retries: Downloading using $downloader..."
if [[ $downloader == "curl" ]]; then
http_status=$(eval $cmd)
exit_status=$?
# For curl, check HTTP status is 200 and exit status is 0
if [[ $exit_status -eq 0 && $http_status -eq 200 ]]; then
# zrep_msg sub "a.Download successful."
return 0
fi
else # wget or wget2
eval $cmd
exit_status=$?
# For wget/wget2, just check exit status is 0
if [[ $exit_status -eq 0 ]]; then
# zrep_msg sub "b.Download successful."
return 0
fi
fi
sleep $delay
((attempt++))
done
zrep_msg debug "Error: The download failed after $retries attempts."
return 1
}
# Function to install a package by unzipping it to ${config[main_zrep_install_dir]}
function zrep_install_package() {
if [[ ${1} == "u" ]]; then
updates=true
local package=${2}
#echo "zrep_install_package: package=$package"
else
updates=false
local package="${1}"
# Ensure package name is in 'author/package' format
if [[ ! "${package}" =~ ^.+/[^/]+$ ]]; then
zrep_msg debug "\nError: Package name must be in 'author/package' format."
return 1
fi
# Call zrep_check_if_installed to check if the package is already installed
if zrep_check_if_installed "${package}"; then
zrep_msg debug "\nPackage ${package} is already installed."
zrep_msg info "Use 'zrep list' to see installed packages."
return 0
fi
fi
# If not installed, proceed with fetching the package information
# Using the new zrep API to get the package version
# zrep_parse_remote "${config[global_repo_url]}/getver.php\?p\=${package}" ${package}
local tmpDir="${config[main_zrep_install_dir]}/tmp"
mkdir -p "${tmpDir}"
local zipFile="${tmpDir}/${author}-${script}-${version}.zip"
dlurl="${config[global_repo_url]}/download/${package}/${version}"
zrep_download_package "${zipFile}" "${dlurl}"
unzip -q -o "${zipFile}" -d "${config[main_zrep_install_dir]}"
if [[ $? -ne 0 ]]; then
zrep_msg debug "\nError: Failed to unzip the package."
return 1
else
zrep_update_installed_json "${author}" "${script}" "${version}"
fi
rm "${zipFile}"
}
# Function to parse installed.json
function zrep_parse_installed_json() {
zrep_installed_json
jq -c '.' "${installed_json}"
}
function zrep_parse_package_name() {
package_name="${1}"
zrep_installed_json
author="${package_name%/*}"
script="${package_name#*/}"
local first_letter="${author:0:1:l}"
addon_path="${config[main_zrep_install_dir]}/${first_letter}/${author}/${script}"
# Check if the package is installed
if ! jq -e --arg author "$author" --arg script "$script" '.[$author] | any(.script == $script)' "${installed_json}" &>/dev/null; then
zrep_msg debug "\nError: Package '${package_name}' is not installed."
return 1
fi
}
function zrep_enable() {
local package_name="${1}"
zrep_parse_package_name "${package_name}"
# Initialize addons array if .zrep_addons does not exist
if [ ! -f "${config[main_zrep_install_dir]}/.addons" ]; then
addons=()
else
# Load existing addons from ${config[main_zrep_install_dir]}/.addons
source "${config[main_zrep_install_dir]}/.addons"
fi
# Check if the addon is already enabled
local addon_exists=0
for addon in "${addons[@]}"; do
if [[ "${addon}" == "${addon_path}" ]]; then
addon_exists=1
break
fi
done
if ((addon_exists)); then
echo "Package '${package_name}' is already enabled."
return 0
fi
# Add addon path to the array
addons+=("${addon_path}")
# Reconstruct .zrep_addons file with the updated addons array
{
echo "addons=("
for addon in "${addons[@]}"; do
echo " '${addon}'"
done
echo ")"
} > "${config[main_zrep_install_dir]}/.addons"
zrep_msg info "\nPackage '${package_name}' has been enabled and added to fpath."
zrep_msg info "You may have to run 'source ~/.zrep_addons' to get access to it."
}
function zrep_disable() {
local package_name="${1}"
zrep_parse_package_name "${package_name}"
# Initialize addons array if .zrep_addons does not exist
if [ ! -f "${config[main_zrep_install_dir]}/.addons" ]; then
addons=()
else
# Load existing addons from ${config[main_zrep_install_dir]}/.addons
source "${config[main_zrep_install_dir]}/.addons"
fi
# Initialize a new array for addons
local new_addons=()
# Flag to check if addon was found and removed
local found=0
# Iterate through existing addons
for addon in "${addons[@]}"; do
if [[ "${addon}" == "${addon_path}" ]]; then
found=1
else
new_addons+=("${addon}")
fi
done
if ((found == 0)); then
zrep_msg debug "\nPackage '${package_name}' is not currently enabled."
return 0
fi
# Reconstruct .zrep_addons file with the new addons array
{
echo "addons=("
for addon in "${new_addons[@]}"; do
echo " '${addon}'"
done
echo ")"
} > ${config[main_zrep_install_dir]}/.addons
zrep_msg info "\nPackage '${package_name} (${script})' has been disabled and removed from fpath."
zrep_msg info "You may have to run 'source ~/.zrep_addons' to remove it from your shell."
}
# Help function to display available options
function zrep_help() {
zrep_msg sub "\nUsage: zrep <command> [arguments]"
zrep_msg info "Available commands:"
if [[ ! -f ${ZREP_CONFIG} ]]; then
zrep_msg info " init: Initialize zrep"
fi
zrep_msg info " install (i) <author/package>:\t\t\tInstall a package"
zrep_msg info " remove (rm, delete, del) <author/package>:\tRemove a package"
zrep_msg info " update (u) <author/package>:\t\t\tUpdate zrep package"
zrep_msg info " enable <author/package>:\t\t\tEnable zrep package"
zrep_msg info " disable <author/package>:\t\t\tDisable zrep package"
zrep_msg info " search 'search term':\t\t\t\tSearch for authors, packages or description"
zrep_msg info " version:\t\t\t\t\tDisplay zrep version"
zrep_msg info " list:\t\t\t\t\t\tList installed packages"
zrep_msg info " <author/package> help:\t\t\tDisplay help for package (if available)"
}
function zrep_package_info() {
local package_name="${1}"
zrep_installed_json # Ensure installed.json is loaded and available
# Parse the package name to extract author and script
local author="${package_name%/*}"
local script="${package_name#*/}"
local first_letter="${author:0:1:l}" # Get the first letter of the author's name to construct the URL
# Check if the package is installed and get its version
if zrep_check_if_installed "${package_name}"; then
local installed_version="${installed_version}" # This variable is set by zrep_check_if_installed
local package_dir="${config[main_zrep_install_dir]}/${first_letter}/${author}/${script}"
local zrep_url="${config[global_repo_url]}/${first_letter}/${author}/${script}"
# Display package information
zrep_msg info "\nAuthor/Package:\t\t${author}/${script}"
zrep_msg info "Version installed:\t${installed_version}"
zrep_msg info "Location on disk:\t${package_dir}"
zrep_msg info "zrep URL:\t\t${zrep_url}"
else
zrep_msg debug "\nPackage '${package_name}' is not installed."
fi
}
function zrep_read_usage() {
local package_name="${1}"
# Parse the package name to extract author and script
local author="${package_name%/*}"
local script="${package_name#*/}"
local first_letter="${author:0:1:l}"
# Construct the path to the USAGE file
local usage_file="${config[main_zrep_install_dir]}/${first_letter}/${author}/${script}/USAGE"
# Check if the USAGE file exists
if [[ -f "${usage_file}" ]]; then
# Display the content of the USAGE file
zrep_msg sub "\n${package_name}:"
local usage_buffer=$(<${usage_file})
zrep_msg info "${usage_buffer}"
else
zrep_msg debug "No USAGE file found for package '${package_name}'."
fi
}
function main() {
zrep_main_version_string
if [[ ${1} != "init" ]]; then
zrep_load_config ${1}
zrep_load_theme ${config[global_theme]}
fi
# Check if the second argument is "help" and the first argument is not empty
if [[ "${2}" == "help" && -n "${1}" ]]; then
zrep_read_usage "${1}"
exit
fi
# Example command handling structure
case "${1}" in
init)
zrep_init
zrep_check_for_deps
exit
;;
search | s | find)
zrep_search "${@:2}"
;;
install | i)
zrep_install_package ${2}
;;
remove | delete | rm | del)
# Parse the command argument to extract the package name
zrep_remove_package_name="${2:-}"
if [[ -z "${zrep_remove_package_name}" ]]; then
zrep_msg info "\nUsage: zrep ${1} author/package"
else
zrep_remove_package "${zrep_remove_package_name}"
fi
;;
update | u)
zrep_update_package ${2}
;;
version | -v | --version)
zrep_version
;;
list)
zrep_list_installed_packages
;;
help | -h | --help)
zrep_help
;;
enable)
zrep_enable ${2}
;;
disable)
zrep_disable ${2}
;;
info)
zrep_package_info ${2}
;;
*)
zrep_help
;;
esac
}
# Call main with all passed arguments
main "$@"

355
zrep
View File

@ -1,355 +0,0 @@
#!/usr/bin/zsh
VERSION="0.0.1" # Sat-2024-02-24
ZREP="Zsh Repository Tool"
# Define the path to .zreprc
ZREP_CONFIG="$HOME/.zreprc"
# echo "START: $fpath"
function zrep_fpath() {
local base_dir="$1"
# Check if the base directory exists
if [[ ! -d "$base_dir" ]]; then
echo "Error: Base directory '$base_dir' does not exist."
return 1
fi
# Add directories containing at least one file to fpath
for dir in $base_dir/**/*(/N); do
if [[ -n $(ls -A "$dir/") ]]; then
fpath=($dir $fpath)
fi
done
}
zrep_fpath ${HOME}/.zrep/functions
autoload -Uz zini
# List of colors available
black="\033[0;30m"
red="\033[0;31m"
green="\033[0;32m"
yellow="\033[0;33m"
blue="\033[0;34m"
magenta="\033[0;35m"
cyan="\033[0;36m"
white="\033[0;37m"
bold_black="\033[1;30m"
bold_red="\033[1;31m"
bold_green="\033[1;32m"
bold_yellow="\033[1;33m"
bold_blue="\033[1;34m"
bold_magenta="\033[1;35m"
bold_cyan="\033[1;36m"
bold_white="\033[1;37m"
black_bg="\033[40m"
red_bg="\033[41m"
green_bg="\033[42m"
yellow_bg="\033[43m"
blue_bg="\033[44m"
magenta_bg="\033[45m"
cyan_bg="\033[46m"
white_bg="\033[47m"
end="\033[0m"
function zrep_version() {
zrep_msg info "Created by kekePower - 2024"
zrep_msg info "- https://git.kekepower.com/kekePower/zrep/${end}"
zrep_msg info "Please see '${ZSH_SCRIPT:t} help' for more info"
exit
}
function zrep_msg() {
# Determine the color based on the type
# local color="${end}" # Default to no color if type is unrecognized
case ${1} in
std) color="${green}" ;;
info) color="${yellow}" ;;
debug) color="${red}" ;;
other) color="${bold_yellow}" ;;
sub) color="${magenta}" ;;
main) color="${white} ${green_bg}" ;;
esac
# echo "1=$1\n2=$2\ncolor=$color"
printf "${color}%b${end}\n" "${2}"
}
function zrep_init() {
local config_file="$HOME/.zreprc"
local zshrc_file="$HOME/.zshrc"
local install_dir
# Check if .zreprc exists
if [[ ! -f $config_file ]]; then
echo "$config_file not found. Creating it..."
# Prompt user for install directory
read "?Enter zrep installation directory [$HOME/.zrep]: " install_dir
install_dir=${install_dir:-$HOME/.zrep}
# Write to .zreprc
echo "[main]" > $config_file
echo "zrep_install_dir = $install_dir" >> $config_file
else
echo "Running zini $config_file"
zini $config_file
echo "Setting install_dir"
install_dir=${config[zrep_install_dir]}
echo "install_dir=${install_dir}"
fi
# Ensure zrep_install_dir exists
mkdir -p "$install_dir"
# Update or add fpath in .zshrc, ensuring no duplicate or empty entries
if ! grep -q "fpath=(.*$install_dir)" "$zshrc_file"; then
echo "Adding zrep installation directory to fpath in .zshrc..."
echo "fpath=('$install_dir' \$fpath)" >> "$zshrc_file"
if ! grep -q "^export fpath" "$zshrc_file"; then
echo "export fpath" >> "$zshrc_file"
fi
else
echo "zrep installation directory ($install_dir) is already included in fpath."
fi
source ${zshrc_file}
echo "zrep initialization complete."
}
# Function to parse remote JSON data and extract author, script, and version
function zrep_parse_remote() {
local url="$1"
local json_data
# Fetch JSON data from the URL
json_data=$(curl -s "$url")
# Extract author, script, and version using jq
author=$(echo "$json_data" | jq -r '.authors[0].name')
script=$(echo "$json_data" | jq -r '.authors[0].scripts[0].name')
version=$(echo "$json_data" | jq -r '.authors[0].scripts[0].version')
# Set the variables as global
export author
export script
export version
# local dlurl="https://kekepower.com/zrep/download.php?a=${author}&s=${script}&v=${version}"
# echo "zrep_parse_remote: ${dlurl}"
}
# Function to write to installed.json after successful install
function zrep_update_installed_json() {
local author="$1"
local script="$2"
local version="$3"
local json_file="${config[main_zrep_install_dir]}/installed.json"
# Check if installed.json exists, create it if not
if [[ ! -f "$json_file" ]]; then
echo '[]' >| "$json_file"
fi
# Create JSON object
local json_object='{"author":"'$author'", "script":"'$script'", "version":"'$version'"}'
# Check if the entry already exists in installed.json
if grep -q "$json_object" "$json_file"; then
echo "Package '$script' by '$author' version $version is already installed."
return 0
fi
# Add the entry to installed.json
echo "$json_object" >> "$json_file"
echo "Package '$script' by '$author' version $version installed successfully."
}
# Function to install a package by unzipping it to ${config[main_zrep_install_dir]}
function zrep_install_package() {
zrep_parse_remote "https://kekepower.com/zrep/packages.json"
# Construct the download URL
local dlurl="https://kekepower.com/zrep/download.php?a=${author}&s=${script}&v=${version}"
echo "${dlurl}"
# exit
# Get the base directory where the package will be installed
local baseDir="${config[main_zrep_install_dir]}/"
# Create the directory if it doesn't exist
mkdir -p "$baseDir"
# Download the package zip file
local zipFile="/tmp/${author}_${package}_${version}.zip"
curl -s -o "$zipFile" "$dlurl"
# Check if the download was successful
if [[ $? -ne 0 ]]; then
echo "Error: Failed to download the package."
return 1
fi
# Unzip the package to the installation directory
unzip -q "$zipFile" -d "$baseDir"
# Check if the unzip operation was successful
if [[ $? -ne 0 ]]; then
echo "Error: Failed to unzip the package."
return 1
else
zrep_update_installed_json "$author" "$script" "$version"
fi
# Clean up: Remove the downloaded zip file
rm "$zipFile"
}
# Function to list installed packages from installed.json
function zrep_list_installed_packages() {
local installed_json="${config[main_zrep_install_dir]}/installed.json"
# Check if installed.json exists
if [[ ! -f "$installed_json" ]]; then
echo "No installed packages found."
return 0
fi
# Parse installed.json and list packages
zrep_msg main "\nInstalled packages:"
zrep_msg other " - $(jq -r '.[] | "\(.author)/\(.script) (\(.version))"' "$installed_json")"
}
# Function to load configuration
function load_config() {
if [[ -f "$ZREP_CONFIG" ]]; then
zini "$ZREP_CONFIG"
zrep_fpath ${config[main_zrep_install_dir]}
else
if [[ "$1" == "init" ]]; then
echo "$ZREP_CONFIG not found. Proceeding with 'zrep init'..."
zrep_init
else
echo "$ZREP_CONFIG not found."
# Ask the user if they want to run 'zrep init'
read "response?Would you like to run 'zrep init' to set up? (y/n): "
if [[ "$response" =~ ^[Yy]$ ]]; then
zrep_init
else
echo "Initialization canceled. Please run 'zrep init' manually to set up."
exit 1
fi
fi
fi
}
# Function to remove a package from installed.json
function zrep_remove_package() {
local package_name="$1"
local installed_json="${config[main_zrep_install_dir]}/installed.json"
# Check if installed.json exists
if [[ ! -f "$installed_json" ]]; then
echo "Error: installed.json not found."
return 1
fi
# Get package information from installed.json
local package_info
package_info=$(zrep_parse_installed_json | jq ".[] | select(.author + \"/\" + .script == \"$package_name\")")
# Check if the package is installed
if [[ -z "$package_info" ]]; then
echo "Error: Package '$package_name' is not installed."
return 1
fi
# Display package information
echo "Package information:"
echo "$package_info" | jq .
# Ask user for confirmation
read -q "REPLY?Are you sure you want to remove this package? (y/n) "
echo
if [[ "$REPLY" =~ ^[Yy]$ ]]; then
# Remove the package from installed.json
jq "map(select(.author + \"/\" + .script != \"$package_name\"))" "$installed_json" > "$installed_json.tmp"
mv "$installed_json.tmp" "$installed_json"
echo "Package '$package_name' removed successfully."
else
echo "Removal canceled."
fi
}
# Function to parse installed.json
function zrep_parse_installed_json() {
local installed_json="${config[main_zrep_install_dir]}/installed.json"
jq -c '.' "$installed_json"
}
# Help function to display available options
function zrep_help() {
zrep_msg sub "Usage: zrep <command> [arguments]"
zrep_msg other "Available commands:"
zrep_msg other " init: Initialize zrep"
zrep_msg other " install <package>: Install a package"
zrep_msg other " remove <package>: Remove a package"
zrep_msg other " update: Update zrep"
zrep_msg other " version: Display zrep version"
zrep_msg other " list: List installed packages"
}
function main() {
load_config
# Example command handling structure
case "$1" in
init)
zrep_init
zrep_fpath ${config[main_zrep_install_dir]}
exit
;;
install)
zrep_msg info "Install function here"
zrep_install_package ${1}
;;
remove)
# Parse the command argument to extract the package name
zrep_remove_package_name="${1:-}"
if [[ -z "$zrep_remove_package_name" ]]; then
echo "Usage: zrep remove package_name"
else
zrep_remove_package "$zrep_remove_package_name"
fi
;;
update)
zrep_msg info "Update function here"
;;
version)
zrep_version
;;
list)
zrep_list_installed_packages
;;
help)
zrep_help
;;
*)
zrep_help
;;
esac
}
echo "${magenta}${blue_bg} ${ZREP} ${end}${bold_white}${blue_bg}${VERSION} ${end}"
# Call main with all passed arguments
main "$@"

BIN
zrep-logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 231 KiB