Created
August 29, 2025 16:22
-
-
Save dhamidi/79c69359d7594e8afefbc8e9ea1ab812 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # lessopen - LESSOPEN preprocessor for JSON files | |
| # Usage: Set LESSOPEN="|lessopen %s" in your shell | |
| set -euo pipefail | |
| # Check if jq is available | |
| if ! command -v jq >/dev/null 2>&1; then | |
| exit 1 | |
| fi | |
| # Get the input file | |
| input_file="${1:-}" | |
| # If no file provided, exit | |
| if [[ -z "$input_file" ]]; then | |
| exit 1 | |
| fi | |
| # Function to check if content is valid JSON | |
| is_json() { | |
| local file="$1" | |
| # Handle stdin case (when file is "-") | |
| if [[ "$file" == "-" ]]; then | |
| jq empty 2>/dev/null | |
| return $? | |
| fi | |
| # Check if file exists and is readable | |
| if [[ ! -f "$file" || ! -r "$file" ]]; then | |
| return 1 | |
| fi | |
| # Try to parse with jq | |
| jq empty "$file" 2>/dev/null | |
| return $? | |
| } | |
| # Function to format JSON with jq | |
| format_json() { | |
| local file="$1" | |
| if [[ "$file" == "-" ]]; then | |
| jq --color-output '.' | |
| else | |
| jq --color-output '.' "$file" | |
| fi | |
| } | |
| # Check if input looks like JSON by extension | |
| case "${input_file,,}" in | |
| *.json | *.jsonl | *.ndjson) | |
| # File has JSON extension, try to format it | |
| if is_json "$input_file"; then | |
| format_json "$input_file" | |
| exit 0 | |
| else | |
| # Invalid JSON, let less handle the original file | |
| exit 1 | |
| fi | |
| ;; | |
| *.md) | |
| glow "$input_file" | |
| ;; | |
| *) | |
| # Check if content is actually JSON even without extension | |
| if is_json "$input_file"; then | |
| format_json "$input_file" | |
| exit 0 | |
| else | |
| # Not JSON, let less handle the original file | |
| exit 1 | |
| fi | |
| ;; | |
| esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment