Skip to content

Commit

Permalink
fix code to run automatically on all __init__.py files
Browse files Browse the repository at this point in the history
  • Loading branch information
chainyo committed Apr 21, 2024
1 parent 120b09c commit 261e340
Show file tree
Hide file tree
Showing 6 changed files with 111 additions and 80 deletions.
2 changes: 0 additions & 2 deletions .pre-commit-hooks.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,3 @@
description: Pre-commit hook to clean up __init__.py files automatically.
entry: scripts/bootstrap.sh
language: script
types: [python]
files: __init__\.py$
51 changes: 51 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ license = "MIT"

[dependencies]
regex = "1.10.4"
walkdir = "2.5.0"
85 changes: 11 additions & 74 deletions scripts/bootstrap.sh
Original file line number Diff line number Diff line change
@@ -1,83 +1,20 @@
#!/bin/bash

#!/usr/bin/env bash
set -euo pipefail

# Wrap everything in a function so that a truncated script
# does not have the chance to cause issues.
# This wraps everything to avoid truncated script issues.
__wrap__() {

# allow overriding the version
VERSION=${PIC_VERSION:-latest}

REPO=chainyo/py-init-cleaner
PLATFORM=`uname -s`
ARCH=`uname -m`

if [[ $PLATFORM == "Darwin" ]]; then
PLATFORM="macos"
elif [[ $PLATFORM == "Linux" ]]; then
PLATFORM="linux"
fi

if [[ $ARCH == armv8* ]] || [[ $ARCH == arm64* ]] || [[ $ARCH == aarch64* ]]; then
ARCH="aarch64"
elif [[ $ARCH == i686* ]]; then
ARCH="x86"
fi

BINARY="py-init-cleaner-${ARCH}-${PLATFORM}"

# Oddly enough GitHub has different URLs for latest vs specific version
if [[ $VERSION == "latest" ]]; then
DOWNLOAD_URL=https://github.com/${REPO}/releases/latest/download/${BINARY}.gz
else
DOWNLOAD_URL=https://github.com/${REPO}/releases/download/${VERSION}/${BINARY}.gz
fi

echo "This script will automatically download and launch py-init-cleaner (${VERSION}) for you."
if [ "x$(id -u)" == "x0" ]; then
echo "warning: this script is running as root. This is dangerous and unnecessary!"
fi
# Download or use cached binary
BINARY_PATH=$(./download_binary.sh)

if ! hash curl 2> /dev/null; then
echo "error: you do not have 'curl' installed which is required for this script."
exit 1
fi
# Execute the binary with all passed arguments
if [ -x "$BINARY_PATH" ]; then
"$BINARY_PATH" "$@"
else
echo "Failed to execute the binary."
exit 1
fi

if ! hash gunzip 2> /dev/null; then
echo "error: you do not have 'gunzip' installed which is required for this script."
exit 1
fi

TEMP_FILE=`mktemp "${TMPDIR:-/tmp}/.picinstall.XXXXXXXX"`
TEMP_FILE_GZ="${TEMP_FILE}.gz"

cleanup() {
rm -f "$TEMP_FILE"
rm -f "$TEMP_FILE_GZ"
}

trap cleanup EXIT
HTTP_CODE=$(curl -SL --progress-bar "$DOWNLOAD_URL" --output "$TEMP_FILE_GZ" --write-out "%{http_code}")
if [[ ${HTTP_CODE} -lt 200 || ${HTTP_CODE} -gt 299 ]]; then
echo "error: platform ${PLATFORM} (${ARCH}) is unsupported."
exit 1
fi

rm -f "$TEMP_FILE"
gunzip "$TEMP_FILE_GZ"
chmod +x "$TEMP_FILE"

# Detect when the file cannot be executed due to NOEXEC /tmp. Taken from rustup
# https://github.com/rust-lang/rustup/blob/87fa15d13e3778733d5d66058e5de4309c27317b/rustup-init.sh#L158-L159
if [ ! -x "$TEMP_FILE" ]; then
printf '%s\n' "Cannot execute $TEMP_FILE (likely because of mounting /tmp as noexec)." 1>&2
printf '%s\n' "Please copy the file to a location where you can execute binaries and run it manually." 1>&2
exit 1
fi

# Execute the binary
"$TEMP_FILE" "$@"

}; __wrap__
__wrap__
34 changes: 34 additions & 0 deletions scripts/download.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/bin/bash
set -euo pipefail

VERSION=${PIC_VERSION:-latest}
REPO="chainyo/py-init-cleaner"
PLATFORM=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)

case $PLATFORM in
Darwin) PLATFORM="macos" ;;
Linux) PLATFORM="linux" ;;
esac

case $ARCH in
armv8*|arm64*|aarch64*) ARCH="aarch64" ;;
i686*) ARCH="x86" ;;
*) ARCH="x86_64" ;;
esac

BINARY="py-init-cleaner-${ARCH}-${PLATFORM}"
BINARY_PATH="$HOME/.cache/pre-commit/$BINARY"

# Check if binary is already downloaded
if [[ ! -f "$BINARY_PATH" ]]; then
echo "Downloading $BINARY..."
DOWNLOAD_URL="https://github.com/${REPO}/releases/download/${VERSION}/${BINARY}.gz"
curl -SL --progress-bar "$DOWNLOAD_URL" -o "${BINARY_PATH}.gz"
gunzip "${BINARY_PATH}.gz"
chmod +x "$BINARY_PATH"
else
echo "Using cached binary."
fi

echo "$BINARY_PATH"
18 changes: 14 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use regex::Regex;
use std::fs;
use std::io::{self, Write};
use walkdir::WalkDir;

fn clean_file(path: &str) -> io::Result<()> {
let data = fs::read_to_string(path)?;
Expand All @@ -12,12 +13,21 @@ fn clean_file(path: &str) -> io::Result<()> {
Ok(())
}

fn main() {
fn main() -> io::Result<()> {
let args: Vec<String> = std::env::args().collect();
for file in &args[1..] {
if let Err(e) = clean_file(file) {
writeln!(io::stderr(), "Error processing {}: {}", file, e).unwrap();
let target_directory = if args.len() > 1 { &args[1] } else { "." };

for entry in WalkDir::new(target_directory)
.into_iter()
.filter_map(Result::ok)
.filter(|e| e.file_name().to_string_lossy() == "__init__.py")
{
let path = entry.path().to_str().unwrap();
if let Err(e) = clean_file(path) {
writeln!(io::stderr(), "Error processing {}: {}", path, e)?;
std::process::exit(1);
}
}

Ok(())
}

0 comments on commit 261e340

Please sign in to comment.