0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python開発時にpush/commit時に作業用のコードを消した後に復元する

Posted at

✅ 目的

  • 開発中:debug.print(...) を自由に使いたい
  • 本番push前:debug.print(...) を一時的に削除し、push後に復元したい
  • 理想:安全に・自動化されたプロセスで行う

🗂️ 構成ファイル一覧

project-root/
├── main.py              # あなたのコード(debug.printあり)
├── debug_tools/
│   └── debug_printer.py # DebugPrinterクラス(.gitignore推奨)
├── remove_debug_prints.py   # debug.print を削除するスクリプト
├── push_clean.sh            # 一連の処理を行うシェルスクリプト
├── .gitignore

① debug.print(...) を削除するスクリプト(remove_debug_prints.py)

# remove_debug_prints.py
import re
from pathlib import Path

def remove_debug_prints():
    pattern = re.compile(r'^\s*debug\.print\(.*?\)\s*$', re.MULTILINE)

    for path in Path('.').rglob('*.py'):
        if path.name in {"remove_debug_prints.py", "debug_printer.py"}:
            continue
        text = path.read_text(encoding='utf-8')
        new_text = pattern.sub('', text)
        path.write_text(new_text, encoding='utf-8')

if __name__ == "__main__":
    remove_debug_prints()

🔸 行全体が debug.print(...) の場合のみ削除します。
🔸 条件を追加して debug.print("!important") を残すなども可能。

② 一連の操作を実行するスクリプト(push_clean.sh)

#!/bin/bash

set -e  # エラーが出たら止める

echo "🌱 stash current changes..."
git stash push -m "debugあり"

echo "🧹 removing debug.print(...)..."
python3 remove_debug_prints.py

echo "📦 add and commit cleaned code..."
git add .
git commit -m "本番用push:debug.print除去"

echo "🚀 pushing..."
git push

echo "♻️ restoring debug付き作業コード..."
git stash pop

echo "✅ 完了しました!"

🔸 実行権限を与える: chmod +x push_clean.sh

③ .gitignore に debug_printer.py を追加(任意)

.gitignore
# .gitignore
debug_tools/debug_printer.py

🔸 debug_printer.py は個人の開発用としてGitに含めないことを想定

✅ 使用方法(毎回のpush)

./push_clean.sh

🔸 これだけで「削除 → push → 元に戻す」一連の処理が完了します。

✨ 拡張アイデア(必要に応じて)

  • remove_debug_prints.py に --dry-run や --backup オプション追加
  • debug.print("!keep") だけ残すなどの指定
  • Makefile に統合: make push_clean
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?