oops-cli 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6e1003df0d3be3f85135c9f36b34aaed5d5ce02002a22d1c75baafd235180b15
4
- data.tar.gz: b67d4984e973482dc9c4f4938d14e65dfc4e99c7c149a2deea7a6aee0e2c2297
3
+ metadata.gz: 57dbf3ca3cbb5597d03ce5f568d6ccad80ea5fa0f1f31b129ba61914e3a32a58
4
+ data.tar.gz: 03aa37cc2ba8ffc20f2f2834d1d3d746237f0652456f11a081f44eab971b9ecf
5
5
  SHA512:
6
- metadata.gz: e6754adb99ca3b4ae7f0294eb84547f630fd6fcb9bbe9191cf9112e77d9590b6dd5561aa94300e2c19e683d1a9e50072358d5814485de8c355ece40e349ca360
7
- data.tar.gz: ede05535447c896dca5e443e883c9c90d7b225a7ccea09ee0628601d8650f9b1642aa2098c7c0ebedb6d0c8433645134402352140d45cb2dffc25eac07425fba
6
+ metadata.gz: 126f86861ea152c1f9e989531041a0f8aab4f2d30595abed578f6a529449df5540d24f4b4562f73f769a41fa4e59da57d0fcb623352d39a52b96d0777c4d105c
7
+ data.tar.gz: 1d83b125fe47d95fb7940c798b1f17e8520cafda19b9eeb9341619ff07b30a5b789d187d1424555aad5d3b77c904b29ce5a19bf008bfd07da4ab07aa24fed59f
data/CHANGELOG.ja.md CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  [English](CHANGELOG.md) | 日本語
4
4
 
5
+ ## 0.4.1 - 2026-11-04
6
+
7
+ - 修正: 閉じたタブのプロセス番号が別のプロセスに使い回されると、そのログがいつまでも消えなかった問題を直しました。ログに最後に書き込まれた後に起動したプロセスは、そのログを書いたタブではないと判断します([#58](https://github.com/ysb3996-blip/oops/issues/58))。
8
+ - 変更: 開いたままのタブも、`retention_days` より古いコマンドを自分のログから落とすようにしました。確かめるのはコマンドが終わったとき(1 時間に 1 回まで)です([#59](https://github.com/ysb3996-blip/oops/issues/59))。
9
+ - Ghostty 上の bash: Ghostty が外側のシェルにシェル統合を入れていた場合、記録される側のシェルでもう一度読み込むようにしました。zsh と fish はすでにそうしていました。README で bash の人に頼んでいた 1 行は、この場合は要りません([#50](https://github.com/ysb3996-blip/oops/issues/50))。
10
+ - 変更: 全画面アプリの出力の代わりに入る 1 行に、コマンド名を入れるようにしました。1 行に 1 コマンドのときだけで、たとえばページャーを通した `git log` なら `[git: full-screen output omitted]` です([#45](https://github.com/ysb3996-blip/oops/issues/45))。
11
+
12
+ ## 0.4.0 - 2026-11-03
13
+
14
+ - `--print` / `-p` を追加。クリップボードの代わりに整形したテキストを標準出力へ書き出し、SSH 先・コンテナ・スクリプトからパイプできるようにします([#40](https://github.com/ysb3996-blip/oops/issues/40))。[@ShahadatTest](https://github.com/ShahadatTest) さんによる貢献([#52](https://github.com/ysb3996-blip/oops/pull/52))。
15
+
5
16
  ## 0.3.0 - 2026-11-02
6
17
 
7
18
  - `oops clear` で閉じたタブのログを削除できます。`oops clear --all` は今のタブのログも空にします([#42](https://github.com/ysb3996-blip/oops/issues/42))。
data/CHANGELOG.md CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  English | [日本語](CHANGELOG.ja.md)
4
4
 
5
+ ## 0.4.1 - 2026-11-04
6
+
7
+ - Fixed: a closed tab's log is no longer kept forever when its process id is reused by another process. A process that started after the log was last written is not the tab that wrote it ([#58](https://github.com/ysb3996-blip/oops/issues/58)).
8
+ - Changed: a tab that stays open now drops commands older than `retention_days` from its own log when a command finishes, at most once an hour ([#59](https://github.com/ysb3996-blip/oops/issues/59)).
9
+ - bash in Ghostty: when Ghostty injected its shell integration into the outer shell, the recorded shell now loads it again, as zsh and fish already did. The line the README asked bash users to add is no longer needed there ([#50](https://github.com/ysb3996-blip/oops/issues/50)).
10
+ - Changed: the line that stands in for a full-screen app's output names the command when the line holds one command, e.g. `[git: full-screen output omitted]` for `git log` through a pager ([#45](https://github.com/ysb3996-blip/oops/issues/45)).
11
+
12
+ ## 0.4.0 - 2026-11-03
13
+
14
+ - `--print` / `-p`: write the formatted text to stdout instead of the clipboard, so SSH sessions, containers and scripts can pipe it ([#40](https://github.com/ysb3996-blip/oops/issues/40)). Contributed by [@ShahadatTest](https://github.com/ShahadatTest) in [#52](https://github.com/ysb3996-blip/oops/pull/52).
15
+
5
16
  ## 0.3.0 - 2026-11-02
6
17
 
7
18
  - `oops clear` deletes the logs of closed tabs, and `oops clear --all` also empties the current tab's log ([#42](https://github.com/ysb3996-blip/oops/issues/42)).
data/README.ja.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [English](README.md) | 日本語
4
4
 
5
- [![Gem Version](https://img.shields.io/gem/v/oops-cli)](https://rubygems.org/gems/oops-cli) [![CI](https://github.com/ysb3996-blip/oops/actions/workflows/ci.yml/badge.svg)](https://github.com/ysb3996-blip/oops/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
5
+ [![Gem Version](https://img.shields.io/gem/v/oops-cli)](https://rubygems.org/gems/oops-cli) [![CI](https://github.com/ysb3996-blip/oops/actions/workflows/ci.yml/badge.svg)](https://github.com/ysb3996-blip/oops/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![codecov](https://codecov.io/gh/ysb3996-blip/oops/graph/badge.svg)](https://codecov.io/gh/ysb3996-blip/oops) [![All Contributors](https://img.shields.io/github/all-contributors/ysb3996-blip/oops?color=ee8449)](#貢献してくれた人たち)
6
6
 
7
7
  直前のシェルコマンドとその出力を、貼り付けられる形でクリップボードにコピーします。
8
8
 
@@ -31,6 +31,8 @@ Homebrew 版は Homebrew の Ruby で oops を動かすので、`PATH` の先に
31
31
 
32
32
  macOS または Linux(WSL は Linux 扱い)、Ruby 3.3 以降、zsh・bash・fish のどれかが必要です。実行時に依存する gem はありません。
33
33
 
34
+ macOS の Terminal.app・iTerm2・Ghostty・VS Code の統合ターミナルで、手で動作を確かめています。ほかの端末でおかしな動きがあれば、issue で教えてください。
35
+
34
36
  `gem install` は、そのとき有効な Ruby にだけ oops を入れます。gem は Ruby のバージョンごとに別々です。rbenv・asdf・mise などで別の Ruby を使うタブでは、`oops` が `command not found` のエラーになります(シェルの起動時にも出ます)。いつでも使える直し方は、有効な Ruby で `gem install oops-cli` をもう一度実行することです(rbenv なら続けて `rbenv rehash`)。`.ruby-version`・`.tool-versions`・`mise.toml` で Ruby を指定しているディレクトリの外では、代わりにインストールした Ruby を標準(グローバル)の Ruby に設定することもできます(例: `rbenv global 3.3.5`)。
35
37
 
36
38
  ### zsh のプラグインマネージャーで入れる
@@ -112,13 +114,14 @@ oops init fish | source
112
114
  | `--head N` | 出力の最初の N 行だけ残す(`--tail` と併用すると両端を残す) |
113
115
  | `--time` | 各コマンドの開始時刻を `# 2026-10-31 19:30:09 +09:00` の行として付ける |
114
116
  | `--output-only` | `$ コマンド` の行を省き、出力だけをコピーする |
117
+ | `-p`, `--print` | クリップボードの代わりに標準出力へ書き出す(`copied:` 行は出さない) |
115
118
  | `--show-secrets` | 秘密情報をマスクせず、置換テーブルも適用しない |
116
119
 
117
120
  `N` は正の整数で指定します。件数は位置引数の `N` または `-n N` のどちらかで 1 回だけ指定でき、併用や `-n` の繰り返しは使い方の誤りになります。対象のコマンドが指定件数より少なければ、見つかった分をコピーします。`-n` は上記の書式オプションと併用できます。
118
121
 
119
122
  `oops` 自身はコピー対象になりません。直前のコマンドが `oops` だった場合は、その前のコマンドがコピーされます。
120
123
 
121
- 終了コード: `0` コピーした、`1` コピーしなかった(記録していない、まだコマンドがない、失敗したコマンドがない、一時停止中、クリップボードのコマンドが失敗)、`2` 使い方の誤り。
124
+ 終了コード: `0` コピーした(または `--print` で出力した)、`1` コピーしなかった(記録していない、まだコマンドがない、失敗したコマンドがない、一時停止中、クリップボードのコマンドが失敗)、`2` 使い方の誤り。
122
125
 
123
126
  ### 標準の出力
124
127
 
@@ -196,14 +199,14 @@ replace: # コピー時に適用する単純な文字列置換
196
199
  secrets: # マスクする追加の正規表現
197
200
  - "sk_live_[A-Za-z0-9]+"
198
201
  clipboard: auto # auto | pbcopy | wl-copy | xclip | xsel | clip.exe | osc52 | 任意のコマンド(標準入力から読む)
199
- retention_days: 7 # 閉じたタブのログをこの日数で削除する。false なら残す
202
+ retention_days: 7 # この日数より古いコマンドを削除する。false なら残す
200
203
  ```
201
204
 
202
205
  - 置換とマスクはコピーする瞬間に適用されます。記録済みのログは変更されないため、設定を変えると以前のコマンドにも反映されます。
203
206
  - `replace` のキーは長いものから順に、大文字小文字を区別して適用されます。
204
207
  - 未知のキーは警告されて無視されます。YAML が壊れている場合も警告が出て、設定なしで続行します。
205
208
  - `clipboard: auto` のとき、oops は macOS では `pbcopy`、WSL では `clip.exe`、Wayland では `wl-copy`、X11 では `xclip` か `xsel` を試し、だめなら OSC 52 端末エスケープシーケンスにフォールバックします(SSH 越しでもこれが使われます)。どれを選んだかは `oops doctor` で確認できます。
206
- - `retention_days`(標準は 7)は、閉じたタブがログに最後に書き込んだ時点から数えます。古いログは、タブが記録を始めるときに削除されます。`false` にすると、閉じたタブのログは 50 MB の上限で削除されるまで残ります。
209
+ - `retention_days`(標準は 7)は、閉じたタブがログに最後に書き込んだ時点から数えます。古いログは、タブが記録を始めるときに削除されます。開いたままのタブも、コマンドが終わったときに、自分のログからこの日数より古いコマンドを落とします(1 時間に 1 回まで)。何も実行していないタブでは、次のコマンドまで残ります。`false` にすると、ログは 50 MB の上限で削除されるまで残ります。
207
210
  - 自分で指定した `clipboard:` のコマンドは、独自のプロセスグループで 5 秒のタイムアウト付きで実行されます。そのため端末の読み取りや設定(パスワード入力、`stty` など)はできません。コピー中の Ctrl-C もそのコマンドには届きません。
208
211
 
209
212
  組み込みのマスク対象: AWS アクセスキー、GitHub / GitLab / Slack / npm / OpenAI・Anthropic(`sk-...`)/ Stripe / Google の API トークン、Slack の webhook URL、JWT、`Authorization` ヘッダーの値、秘密鍵ブロック(END 行がなくても)、`key`・`token`・`secret`・`password`・`passwd`・`pwd` を含む名前に代入された値、`--password <値>`・`curl -u user:pass`・`mysql -p<値>`・`docker login -p <値>` で渡されたパスワード、メールアドレス、URL 中の認証情報、公開 IPv4 アドレス(ループバックとプライベート範囲は対象外)。出力だけでなくコマンドラインにも適用されます。
@@ -217,12 +220,12 @@ retention_days: 7 # 閉じたタブのログをこの日数で削除する。f
217
220
  1. `oops init` は、rc ファイルから `eval` する(fish では `| source` する)スニペットを出力します。まだ記録されていない端末の対話シェルでは、シェルを `oops record` の下で再起動します。
218
221
  2. `oops record` は、Ruby 製の小さな pty 中継です。キー入力とシェルの出力をそのまま通し、ウィンドウのリサイズをシェルに伝えます。
219
222
  3. シェルのフック(zsh は `preexec`/`precmd`、bash は `DEBUG` トラップと `PROMPT_COMMAND`、fish は `fish_preexec`/`fish_postexec` イベント)が、各コマンドの前後に目に見えない APC マーカーを出力します。中継がそれを取り除くので、端末には見えません。
220
- 4. コマンドが終わるたびに、中継は 1 行の JSON(コマンド、ディレクトリ、時刻、終了コード、生の出力)をタブごとのログに追記します。置き場所は `${XDG_STATE_HOME:-~/.local/state}/oops/sessions/` です。出力は 1 コマンドあたり 1 MB まで(末尾を残す)。各タブのログは 50 MB までで、超えると新しいコマンドだけを残して書き直されます(約 37 MiB まで縮む)。タブが記録を始めるとき、閉じたタブのログのうち `retention_days`(標準は 7 日)を過ぎたものが削除され、続いて残りが古い順に、全ログの合計が 50 MB 以下になるまで削除されます。開いているタブのログは削除されないので、忙しいタブが複数あると合計がそれを超えることがあります。
223
+ 4. コマンドが終わるたびに、中継は 1 行の JSON(コマンド、ディレクトリ、時刻、終了コード、生の出力)をタブごとのログに追記します。置き場所は `${XDG_STATE_HOME:-~/.local/state}/oops/sessions/` です。出力は 1 コマンドあたり 1 MB まで(末尾を残す)。各タブのログは 50 MB までで、超えると新しいコマンドだけを残して書き直されます(約 37 MiB まで縮む)。タブが記録を始めるとき、閉じたタブのログのうち `retention_days`(標準は 7 日)を過ぎたものが削除され、続いて残りが古い順に、全ログの合計が 50 MB 以下になるまで削除されます。開いているタブのログは削除されないので、忙しいタブが複数あると合計がそれを超えることがあります。ログ名のプロセスが動いていて、しかもログに最後に書き込まれる前に起動していれば、そのタブは開いているとみなします。開いているタブも、コマンドが終わったときに、`retention_days` より古いコマンドを自分のログから落とします(1 時間に 1 回まで)。
221
224
  5. `oops` は現在のタブのログの末尾を読み、テキストを整えてマスクし、コードブロックを組み立ててクリップボードに渡します。コマンドを再実行することはありません。
222
225
 
223
226
  ## プライバシーとセキュリティ
224
227
 
225
- - セッションログには、記録されたすべてのコマンドの生の出力が**マスクされないまま**入っています。マスクと置換テーブルはコピーするときにだけ適用されます。ログは `${XDG_STATE_HOME:-~/.local/state}/oops/sessions/` にあり、あなただけが読めます(ファイルは 0600、ディレクトリは 0700)。閉じたタブのログは 7 日後に削除されます(`retention_days`)。`oops clear` ですぐに削除でき、`oops clear --all` なら今のタブのログも空にします。開いている他のタブのログも含めてすべて削除するには `rm -rf "${XDG_STATE_HOME:-$HOME/.local/state}/oops"` を実行します(標準では `rm -rf ~/.local/state/oops`)。ディスクに残したくない秘密情報を表示する前には `oops pause` を使ってください。
228
+ - セッションログには、記録されたすべてのコマンドの生の出力が**マスクされないまま**入っています。マスクと置換テーブルはコピーするときにだけ適用されます。ログは `${XDG_STATE_HOME:-~/.local/state}/oops/sessions/` にあり、あなただけが読めます(ファイルは 0600、ディレクトリは 0700)。`retention_days` が標準の 7 なら、閉じたタブのログは最後のコマンドから 7 日たつと(別のタブが記録を始めるときに)削除され、開いているタブはコマンドが終わったときに 7 日より古いコマンドを落とします。閉じたタブのログは `oops clear` ですぐに削除でき、`oops clear --all` なら今のタブのログも空にします。開いている他のタブのログも含めてすべて削除するには `rm -rf "${XDG_STATE_HOME:-$HOME/.local/state}/oops"` を実行します(標準では `rm -rf ~/.local/state/oops`)。ディスクに残したくない秘密情報を表示する前には `oops pause` を使ってください。
226
229
  - セキュリティ上の問題を非公開で報告する方法は [SECURITY.ja.md](SECURITY.ja.md) を見てください。公開の issue には書かないでください。
227
230
  - 記録される出力は信頼できません。実行したプログラムは、oops のマーカーに見せかけたテキストを出力できます。そのため oops は、`oops pause` / `oops resume` が作るフラグファイルと一致する一時停止・再開マーカーにだけ従います。出力によって黙って記録を止められることはありません。ただし、プログラムがログ上でコマンドの開始と終了の位置を偽装することはできるので、貼り付ける内容は確認してください。
228
231
 
@@ -233,10 +236,10 @@ retention_days: 7 # 閉じたタブのログをこの日数で削除する。f
233
236
  - 使えるのは現在のタブだけです。閉じたタブや以前のタブのものは取り出せません。
234
237
  - OSC 52 経由(SSH やクリップボードツールがない場合)では、端末が一度に送れる量を制限します。oops は約 100 KB に切り詰めて警告します。OSC 52 は一方通行のエスケープシーケンスなので、端末がコピーを受け付けたかどうかは分かりません。無視する端末や確認を求める端末もあり、tmux では `set -g set-clipboard on` が必要です。
235
238
  - 8192 文字を超えるコマンドは、記録されるコマンドラインが切り詰められます。
236
- - vim・less・tmux などの全画面アプリの出力は保存されず、`[full-screen app output omitted]` に置き換わります。
239
+ - vim・less・tmux などの全画面アプリの出力は保存されず、1 行に置き換わります。コマンドラインが 1 つのコマンドだけで、その名前が英数字と `. _ + - /` だけなら、その行にコマンド名が入ります(ページャーを通した `git log` なら `[git: full-screen output omitted]`)。そうでなければ `[full-screen app output omitted]` です。全画面になる前と後に出た行は残ります。
237
240
  - スペースで始まるコマンドラインは、zsh では記録されますが bash では記録されません(bash はそれを履歴に保存せず、oops はコマンドを履歴から読むため)。
238
241
  - [bash-preexec](https://github.com/rcaloras/bash-preexec) を使う bash(atuin や Ghostty の bash 統合の背後にあるものも含む): oops は自前の `DEBUG` トラップを使わず、bash-preexec にフックを登録します。rc ファイルでどちらが先でも同じです。bash が履歴に保存しなかった行(`HISTCONTROL=ignorespace`、`HISTIGNORE`)は、この場合 `(not saved in history)` と記録されます。行のテキストを履歴から読むためです。bash-preexec がない場合、oops はそのような行の最初のコマンドを記録します。
239
- - Ghostty 上の bash: Ghostty のシェル統合(プロンプトマーク、同じディレクトリでの新しいタブ、タイトル)は外側のシェルにだけ入るため、記録される側のシェルには入りません。足し戻すには、`~/.bashrc` の oops の行の下に次の行を置きます(bash 3.2 で確認済み): `[ -n "$GHOSTTY_RESOURCES_DIR" ] && source "$GHOSTTY_RESOURCES_DIR/shell-integration/bash/ghostty.bash"`。zsh と fish は何もしなくて構いません。スニペットがやります。
242
+ - Ghostty のシェル統合(プロンプトマーク、同じディレクトリでの新しいタブ、タイトル)は、外側のシェルにだけ入ります。入っていた場合は、zsh・fish・bash のどれでも、スニペットが記録される側のシェルにもう一度読み込みます。bash 3.2(macOS の `/bin/bash`)には Ghostty が統合を入れられないので、読み込まれません。使いたい場合は、`~/.bashrc` の oops の行の下に次の行を置きます: `[ -n "$GHOSTTY_RESOURCES_DIR" ] && source "$GHOSTTY_RESOURCES_DIR/shell-integration/bash/ghostty.bash"`。
240
243
  - bash: パイプラインの次の行では、`PIPESTATUS` に最後の終了ステータスしか入りません(`false | true` の後に `echo ${PIPESTATUS[*]}` を実行すると、`1 0` ではなく `0` と表示されます)。oops の `PROMPT_COMMAND` の項目が先に実行されるためです。`$?` と `$_` は保たれます。パイプラインの各ステータスを表示するプロンプト(starship の `pipestatus`)は、bash では表示が少なくなります。zsh は `pipestatus` を保ちます。
241
244
  - macOS: `pbcopy` は文字エンコーディングを `LANG` / `LC_*` から決めます。日本語などの非 ASCII 文字が文字化けして届くときは、UTF-8 のロケール(例: `LANG=en_US.UTF-8`)が設定されているか確認してください。SSH 越しで起動したシェルでは設定されていないことがあります。
242
245
  - ネイティブ Windows にはまだ対応していません。
@@ -279,11 +282,11 @@ bundle exec exe/oops doctor
279
282
 
280
283
  ```sh
281
284
  gem build oops-cli.gemspec
282
- gem install ./oops-cli-0.3.0.gem # ファイル名は lib/oops/version.rb に合わせる
285
+ gem install ./oops-cli-0.4.1.gem # ファイル名は lib/oops/version.rb に合わせる
283
286
  rbenv rehash # rbenv を使う場合のみ
284
287
  ```
285
288
 
286
- - gem は Ruby のバージョンごとに入ります。新しいタブが、インストールした Ruby とは別の Ruby を使っていると(たとえばリポジトリは 4.0.9 を指定しているのに、標準の Ruby が 3.3.5 の場合)、シェルの起動時に oops が見つからなくなります(bash では `bash: oops: command not found`、zsh では `command not found: oops` と出ます)。その Ruby でも `gem install` を実行してください(例: `RBENV_VERSION=3.3.5 gem install ./oops-cli-0.3.0.gem`)。
289
+ - gem は Ruby のバージョンごとに入ります。新しいタブが、インストールした Ruby とは別の Ruby を使っていると(たとえばリポジトリは 4.0.9 を指定しているのに、標準の Ruby が 3.3.5 の場合)、シェルの起動時に oops が見つからなくなります(bash では `bash: oops: command not found`、zsh では `command not found: oops` と出ます)。その Ruby でも `gem install` を実行してください(例: `RBENV_VERSION=3.3.5 gem install ./oops-cli-0.4.1.gem`)。
287
290
  - 変更のたびに入れ直してください。インストールされた gem はコピーで、チェックアウトへのリンクではありません。
288
291
  - 削除するには `gem uninstall oops-cli` です。
289
292
  - `eval "$(oops init zsh)"` は、プロンプトで打つだけでなく rc ファイルに書いてください。記録されるシェルは rc ファイルを読み直すため、行がないとフックが入りません(`oops doctor` に `hooks: missing` と出ます)。
@@ -294,7 +297,7 @@ rbenv rehash # rbenv を使う場合のみ
294
297
 
295
298
  リリース前の手動チェックリスト:
296
299
 
297
- - Ghostty、Terminal.app、VS Code の統合ターミナルで、マーカーのゴミが表示されない。
300
+ - Ghostty、Terminal.app、iTerm2、VS Code の統合ターミナルで、マーカーのゴミが表示されない。
298
301
  - vim、less、全画面の端末アプリが、ウィンドウをリサイズしても追従する。
299
302
  - 記録中のタブで `exec zsh` しても、2 つ目の記録が始まらない。
300
303
  - 記録中のタブから `code .` で開いた VS Code のターミナルが、独立して記録される。
@@ -303,6 +306,29 @@ rbenv rehash # rbenv を使う場合のみ
303
306
 
304
307
  バグ報告、アイデア、プルリクエストを歓迎します。[CONTRIBUTING.ja.md](CONTRIBUTING.ja.md) を読んでください。`good first issue` のラベルが付いた issue が、始めやすい入口です。プルリクエストには、テストと rubocop の結果、新しいタブでの動作確認を必ず貼ってください([プルリクエストに必ず貼るもの](CONTRIBUTING.ja.md#プルリクエストに必ず貼るもの))。
305
308
 
309
+ ## 貢献してくれた人たち
310
+
311
+ 手伝ってくれたみなさん、ありがとうございます([絵文字の意味](https://allcontributors.org/docs/en/emoji-key))。追加するときは、issue かプルリクエストに `@all-contributors please add @<ユーザー名> for <貢献の種類>` とコメントしてください。
312
+
313
+ <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
314
+ <!-- prettier-ignore-start -->
315
+ <!-- markdownlint-disable -->
316
+ <table>
317
+ <tbody>
318
+ <tr>
319
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/ysb3996-blip"><img src="https://avatars.githubusercontent.com/u/257992595?v=4?s=80" width="80px;" alt="ysb3996-blip"/><br /><sub><b>ysb3996-blip</b></sub></a><br /><a href="https://github.com/ysb3996-blip/oops/commits?author=ysb3996-blip" title="Code">💻</a> <a href="https://github.com/ysb3996-blip/oops/commits?author=ysb3996-blip" title="Documentation">📖</a> <a href="https://github.com/ysb3996-blip/oops/commits?author=ysb3996-blip" title="Tests">⚠️</a> <a href="#maintenance-ysb3996-blip" title="Maintenance">🚧</a></td>
320
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/ricky9408"><img src="https://avatars.githubusercontent.com/u/49530170?v=4?s=80" width="80px;" alt="Sanghyuk Lee"/><br /><sub><b>Sanghyuk Lee</b></sub></a><br /><a href="https://github.com/ysb3996-blip/oops/commits?author=ricky9408" title="Code">💻</a></td>
321
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/agenticsymphony-tech"><img src="https://avatars.githubusercontent.com/u/326739730?v=4?s=80" width="80px;" alt="agenticsymphony-tech"/><br /><sub><b>agenticsymphony-tech</b></sub></a><br /><a href="https://github.com/ysb3996-blip/oops/commits?author=agenticsymphony-tech" title="Documentation">📖</a></td>
322
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/ShahadatTest"><img src="https://avatars.githubusercontent.com/u/179203101?v=4?s=80" width="80px;" alt="ShahadatTest"/><br /><sub><b>ShahadatTest</b></sub></a><br /><a href="https://github.com/ysb3996-blip/oops/commits?author=ShahadatTest" title="Code">💻</a></td>
323
+ </tr>
324
+ </tbody>
325
+ </table>
326
+
327
+ <!-- markdownlint-restore -->
328
+ <!-- prettier-ignore-end -->
329
+
330
+ <!-- ALL-CONTRIBUTORS-LIST:END -->
331
+
306
332
  ## ライセンス
307
333
 
308
334
  MIT。[LICENSE](LICENSE) を参照してください。
data/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  English | [日本語](README.ja.md)
4
4
 
5
- [![Gem Version](https://img.shields.io/gem/v/oops-cli)](https://rubygems.org/gems/oops-cli) [![CI](https://github.com/ysb3996-blip/oops/actions/workflows/ci.yml/badge.svg)](https://github.com/ysb3996-blip/oops/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
5
+ [![Gem Version](https://img.shields.io/gem/v/oops-cli)](https://rubygems.org/gems/oops-cli) [![CI](https://github.com/ysb3996-blip/oops/actions/workflows/ci.yml/badge.svg)](https://github.com/ysb3996-blip/oops/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![codecov](https://codecov.io/gh/ysb3996-blip/oops/graph/badge.svg)](https://codecov.io/gh/ysb3996-blip/oops) [![All Contributors](https://img.shields.io/github/all-contributors/ysb3996-blip/oops?color=ee8449)](#contributors)
6
6
 
7
7
  Copy the last shell command and its output to the clipboard, ready to paste.
8
8
 
@@ -31,6 +31,8 @@ The Homebrew formula runs oops with Homebrew's own Ruby, so it works even if an
31
31
 
32
32
  Requires Ruby 3.3 or newer on macOS or Linux (WSL counts as Linux), and zsh, bash or fish. There are no runtime gem dependencies.
33
33
 
34
+ Checked by hand on macOS in Terminal.app, iTerm2, Ghostty and the VS Code integrated terminal. If it misbehaves in another terminal, please open an issue.
35
+
34
36
  `gem install` puts oops into the Ruby that is active at that moment; each Ruby version has its own gems. With rbenv, asdf or mise, a tab that uses another Ruby gives a `command not found` error for `oops`, also when the shell starts. The fix that always works is to run `gem install oops-cli` again under the active Ruby (with rbenv, follow with `rbenv rehash`). Outside directories that pin a Ruby with `.ruby-version`, `.tool-versions` or `mise.toml`, you can instead set the Ruby you installed into as your global Ruby (for example `rbenv global 3.3.5`).
35
37
 
36
38
  ### With a zsh plugin manager
@@ -112,13 +114,14 @@ Options for `oops`, `oops N` and `oops err`:
112
114
  | `--head N` | Keep only the first N output lines (with `--tail`, keeps both ends) |
113
115
  | `--time` | Add the time each command started as a `# 2026-10-31 19:30:09 +09:00` line |
114
116
  | `--output-only` | Leave out the `$ command` line and copy only the output |
117
+ | `-p`, `--print` | Write the text to stdout instead of the clipboard (no `copied:` line) |
115
118
  | `--show-secrets` | Do not mask secrets and do not apply the replace table |
116
119
 
117
120
  `N` must be a positive integer. Specify the command count once, either as a positional `N` or with `-n N`; combining them or repeating `-n` is a usage error. If fewer matching commands are available, oops copies those it finds. `-n` can be combined with the formatting options above.
118
121
 
119
122
  `oops` never copies itself: if the previous command was `oops`, you get the command before it.
120
123
 
121
- Exit codes: `0` copied, `1` nothing copied (not recording, no command yet, no failed command, paused, or the clipboard command failed), `2` usage error.
124
+ Exit codes: `0` copied (or printed with `--print`), `1` nothing copied (not recording, no command yet, no failed command, paused, or the clipboard command failed), `2` usage error.
122
125
 
123
126
  ### Default output
124
127
 
@@ -196,14 +199,14 @@ replace: # plain string replacements applied when copying
196
199
  secrets: # extra regular expressions to mask
197
200
  - "sk_live_[A-Za-z0-9]+"
198
201
  clipboard: auto # auto | pbcopy | wl-copy | xclip | xsel | clip.exe | osc52 | any command (reads stdin)
199
- retention_days: 7 # delete closed tabs' logs after this many days; false keeps them
202
+ retention_days: 7 # delete commands older than this many days; false keeps them
200
203
  ```
201
204
 
202
205
  - Replacements and masking are applied at the moment you copy; the recorded log stays untouched, so a config change also affects earlier commands.
203
206
  - `replace` keys are applied longest first and are case-sensitive.
204
207
  - Unknown keys produce a warning and are ignored. A broken YAML file produces a warning and oops carries on without a config.
205
208
  - With `clipboard: auto`, oops tries `pbcopy` on macOS, `clip.exe` on WSL, `wl-copy` on Wayland, `xclip` or `xsel` on X11, and falls back to the OSC 52 terminal escape sequence (also used over SSH). `oops doctor` shows which one it picked.
206
- - `retention_days` (default 7) counts from the last time a closed tab wrote its log. Old logs are deleted when a tab starts recording. With `false`, closed tabs' logs stay until the 50 MB limit removes them.
209
+ - `retention_days` (default 7) counts from the last time a closed tab wrote its log. Old logs are deleted when a tab starts recording. A tab that stays open also drops commands older than that from its own log when a command finishes (at most once an hour), so a tab that runs nothing keeps them until its next command. With `false`, logs stay until the 50 MB limit removes them.
207
210
  - A custom `clipboard:` command runs in its own process group with a 5 second timeout, so it must not read from or configure the terminal (no password prompts, no `stty`); Ctrl-C during a copy does not reach it.
208
211
 
209
212
  Built-in masking covers AWS access keys, GitHub, GitLab, Slack, npm, OpenAI/Anthropic (`sk-...`), Stripe and Google API tokens, Slack webhook URLs, JWTs, `Authorization` header values, private key blocks (also when the END line is missing), values assigned to names containing `key`, `token`, `secret`, `password`, `passwd` or `pwd`, passwords given as `--password <value>`, `curl -u user:pass`, `mysql -p<value>` or `docker login -p <value>`, email addresses, credentials inside URLs, and public IPv4 addresses (loopback and private ranges are left alone). It is applied to the command line as well as the output.
@@ -217,12 +220,12 @@ Masking is pattern based, so it is a safety net, not a guarantee: a secret in a
217
220
  1. `oops init` prints a snippet that you `eval` from your rc file (`| source` in fish). In an interactive shell on a terminal that is not recorded yet, it restarts the shell under `oops record`.
218
221
  2. `oops record` is a small Ruby pty relay: it passes your keystrokes and the shell's output through untouched and forwards window resizes to the shell.
219
222
  3. Hooks in the shell (zsh `preexec`/`precmd`, bash `DEBUG` trap and `PROMPT_COMMAND`, fish `fish_preexec`/`fish_postexec` events) emit invisible APC markers around each command. The relay strips them, so your terminal never sees them.
220
- 4. For each finished command the relay appends one JSON line (command, directory, times, exit code, raw output) to a per-tab log under `${XDG_STATE_HOME:-~/.local/state}/oops/sessions/`. Output is capped at 1 MB per command (the tail is kept). Each tab's log is capped at 50 MB: when it passes that, it is rewritten to keep only its newest commands (down to about 37 MiB). When a tab starts recording, logs of closed tabs older than `retention_days` (7 by default) are deleted, and then the oldest of the rest until all logs together take at most 50 MB; logs of open tabs are never deleted, so several busy tabs can together use more.
223
+ 4. For each finished command the relay appends one JSON line (command, directory, times, exit code, raw output) to a per-tab log under `${XDG_STATE_HOME:-~/.local/state}/oops/sessions/`. Output is capped at 1 MB per command (the tail is kept). Each tab's log is capped at 50 MB: when it passes that, it is rewritten to keep only its newest commands (down to about 37 MiB). When a tab starts recording, logs of closed tabs older than `retention_days` (7 by default) are deleted, and then the oldest of the rest until all logs together take at most 50 MB; logs of open tabs are never deleted, so several busy tabs can together use more. A tab counts as open while the process in its log name is running and started before the log was last written. An open tab also drops commands older than `retention_days` from its own log when a command finishes, at most once an hour.
221
224
  5. `oops` reads the end of the current tab's log, cleans and masks the text, builds the code block and hands it to the clipboard. Nothing is ever re-run.
222
225
 
223
226
  ## Privacy and security
224
227
 
225
- - The session logs hold the raw, **unmasked** output of every recorded command. Masking and the replace table are applied only when you copy. The logs live under `${XDG_STATE_HOME:-~/.local/state}/oops/sessions/`, readable only by you (mode 0600, directory 0700). Logs of closed tabs are deleted after 7 days (`retention_days`). `oops clear` deletes them now, and `oops clear --all` also empties the current tab's log. To delete everything, including the logs of other open tabs, run `rm -rf "${XDG_STATE_HOME:-$HOME/.local/state}/oops"` (by default `rm -rf ~/.local/state/oops`). Use `oops pause` before showing secrets you do not want on disk.
228
+ - The session logs hold the raw, **unmasked** output of every recorded command. Masking and the replace table are applied only when you copy. The logs live under `${XDG_STATE_HOME:-~/.local/state}/oops/sessions/`, readable only by you (mode 0600, directory 0700). With the default `retention_days` of 7, a closed tab's log is deleted once 7 days have passed since its last command (when another tab starts recording), and an open tab drops commands older than 7 days when it finishes a command. `oops clear` deletes the logs of closed tabs now, and `oops clear --all` also empties the current tab's log. To delete everything, including the logs of other open tabs, run `rm -rf "${XDG_STATE_HOME:-$HOME/.local/state}/oops"` (by default `rm -rf ~/.local/state/oops`). Use `oops pause` before showing secrets you do not want on disk.
226
229
  - To report a security problem privately, see [SECURITY.md](SECURITY.md). Please do not open a public issue for it.
227
230
  - Recorded output is untrusted: any program you run can print text that looks like oops's markers. oops therefore obeys a pause or resume marker only when it agrees with the flag file that `oops pause` and `oops resume` set, so output cannot silently pause recording. A program can still fake where a command starts and ends in the log, so check what you paste.
228
231
 
@@ -233,10 +236,10 @@ Masking is pattern based, so it is a safety net, not a guarantee: a secret in a
233
236
  - Only the current tab is available. A tab you closed, or an earlier tab, cannot be retrieved.
234
237
  - Via OSC 52 (SSH, or no clipboard tool), terminals limit how much can be sent at once. oops truncates to roughly 100 KB and warns. OSC 52 is a one-way escape sequence, so oops cannot tell whether the terminal accepted the copy; some terminals ignore it or ask first, and tmux needs `set -g set-clipboard on`.
235
238
  - Commands longer than 8192 characters are truncated in the recorded command line.
236
- - Output of full-screen apps (vim, less, tmux and so on) is not kept; it is replaced by `[full-screen app output omitted]`.
239
+ - Output of full-screen apps (vim, less, tmux and so on) is not kept; it is replaced by one line. When the command line holds a single command with a plain name (letters, digits and `. _ + - /`), that line names it, such as `[git: full-screen output omitted]` for `git log` through a pager; otherwise it reads `[full-screen app output omitted]`. Lines printed before and after the full-screen part are kept.
237
240
  - A command line that starts with a space is recorded in zsh but dropped in bash (bash does not save it to history, which is where oops reads the command).
238
241
  - bash with [bash-preexec](https://github.com/rcaloras/bash-preexec) (also behind atuin and Ghostty's bash integration): oops registers its hooks with it instead of using its own `DEBUG` trap, whichever of the two comes first in your rc file. A line that bash did not save to history (`HISTCONTROL=ignorespace`, `HISTIGNORE`) is then recorded as `(not saved in history)`, because the text of the line is read from history there. Without bash-preexec, oops records the first command of such a line instead.
239
- - bash in Ghostty: Ghostty adds its shell integration (prompt marks, new tabs in the same directory, titles) only to the outer shell, so the recorded shell does not get it. To add it back, put this below the oops line in `~/.bashrc` (checked with bash 3.2): `[ -n "$GHOSTTY_RESOURCES_DIR" ] && source "$GHOSTTY_RESOURCES_DIR/shell-integration/bash/ghostty.bash"`. zsh and fish need nothing: the snippet does it.
242
+ - Ghostty adds its shell integration (prompt marks, new tabs in the same directory, titles) only to the outer shell. When it did, the snippet loads it again in the recorded shell, for zsh, fish and bash. Ghostty cannot add it to bash 3.2 (macOS's `/bin/bash`), so there it is not loaded unless you load it yourself below the oops line in `~/.bashrc`: `[ -n "$GHOSTTY_RESOURCES_DIR" ] && source "$GHOSTTY_RESOURCES_DIR/shell-integration/bash/ghostty.bash"`.
240
243
  - bash: the line after a pipeline sees `PIPESTATUS` with only the last status (`false | true`, then `echo ${PIPESTATUS[*]}` prints `0`, not `1 0`), because oops's `PROMPT_COMMAND` entry runs first. `$?` and `$_` are kept. A prompt that shows pipeline statuses (starship's `pipestatus`) shows less in bash. zsh keeps `pipestatus`.
241
244
  - macOS: `pbcopy` chooses its text encoding from `LANG` / `LC_*`. If Japanese or other non-ASCII text arrives garbled, check that a UTF-8 locale is set (for example `LANG=en_US.UTF-8`), which can be missing in shells started over SSH.
242
245
  - Native Windows is not supported yet.
@@ -279,11 +282,11 @@ To try it as your shell does, build and install the gem into the Ruby you are us
279
282
 
280
283
  ```sh
281
284
  gem build oops-cli.gemspec
282
- gem install ./oops-cli-0.3.0.gem # the file name follows lib/oops/version.rb
285
+ gem install ./oops-cli-0.4.1.gem # the file name follows lib/oops/version.rb
283
286
  rbenv rehash # only with rbenv
284
287
  ```
285
288
 
286
- - A gem is installed per Ruby version. If a new tab uses another Ruby than the one you installed into (for example the repository pins 4.0.9, but your global Ruby is 3.3.5), the shell cannot find oops when it starts (bash prints `bash: oops: command not found`, zsh prints `command not found: oops`). Run `gem install` again under that Ruby, e.g. `RBENV_VERSION=3.3.5 gem install ./oops-cli-0.3.0.gem`.
289
+ - A gem is installed per Ruby version. If a new tab uses another Ruby than the one you installed into (for example the repository pins 4.0.9, but your global Ruby is 3.3.5), the shell cannot find oops when it starts (bash prints `bash: oops: command not found`, zsh prints `command not found: oops`). Run `gem install` again under that Ruby, e.g. `RBENV_VERSION=3.3.5 gem install ./oops-cli-0.4.1.gem`.
287
290
  - Reinstall after every change. The installed gem is a copy, not a link to your checkout.
288
291
  - To remove it: `gem uninstall oops-cli`.
289
292
  - Put `eval "$(oops init zsh)"` in your rc file, not just at the prompt: the recorded shell reads the rc file again, and without the line it has no hooks (`oops doctor` shows `hooks: missing`).
@@ -294,7 +297,7 @@ The tests cover formatting, secret masking, the log reader, the stream parser an
294
297
 
295
298
  Manual checklist before a release:
296
299
 
297
- - No marker garbage is visible in Ghostty, Terminal.app and the VS Code integrated terminal.
300
+ - No marker garbage is visible in Ghostty, Terminal.app, iTerm2 and the VS Code integrated terminal.
298
301
  - vim, less and a full-screen terminal app keep up while you resize the window.
299
302
  - `exec zsh` in a recorded tab does not start a second recording.
300
303
  - A VS Code terminal opened with `code .` from a recorded tab is recorded on its own.
@@ -303,6 +306,29 @@ Manual checklist before a release:
303
306
 
304
307
  Bug reports, ideas and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md); issues labeled `good first issue` are a good place to start. Every pull request must include the test and rubocop results and a check in a new terminal tab; see [What every pull request must include](CONTRIBUTING.md#what-every-pull-request-must-include).
305
308
 
309
+ ## Contributors
310
+
311
+ Thanks to everyone who has helped ([emoji key](https://allcontributors.org/docs/en/emoji-key)). To add someone, comment `@all-contributors please add @<username> for <contributions>` on an issue or pull request.
312
+
313
+ <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
314
+ <!-- prettier-ignore-start -->
315
+ <!-- markdownlint-disable -->
316
+ <table>
317
+ <tbody>
318
+ <tr>
319
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/ysb3996-blip"><img src="https://avatars.githubusercontent.com/u/257992595?v=4?s=80" width="80px;" alt="ysb3996-blip"/><br /><sub><b>ysb3996-blip</b></sub></a><br /><a href="https://github.com/ysb3996-blip/oops/commits?author=ysb3996-blip" title="Code">💻</a> <a href="https://github.com/ysb3996-blip/oops/commits?author=ysb3996-blip" title="Documentation">📖</a> <a href="https://github.com/ysb3996-blip/oops/commits?author=ysb3996-blip" title="Tests">⚠️</a> <a href="#maintenance-ysb3996-blip" title="Maintenance">🚧</a></td>
320
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/ricky9408"><img src="https://avatars.githubusercontent.com/u/49530170?v=4?s=80" width="80px;" alt="Sanghyuk Lee"/><br /><sub><b>Sanghyuk Lee</b></sub></a><br /><a href="https://github.com/ysb3996-blip/oops/commits?author=ricky9408" title="Code">💻</a></td>
321
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/agenticsymphony-tech"><img src="https://avatars.githubusercontent.com/u/326739730?v=4?s=80" width="80px;" alt="agenticsymphony-tech"/><br /><sub><b>agenticsymphony-tech</b></sub></a><br /><a href="https://github.com/ysb3996-blip/oops/commits?author=agenticsymphony-tech" title="Documentation">📖</a></td>
322
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/ShahadatTest"><img src="https://avatars.githubusercontent.com/u/179203101?v=4?s=80" width="80px;" alt="ShahadatTest"/><br /><sub><b>ShahadatTest</b></sub></a><br /><a href="https://github.com/ysb3996-blip/oops/commits?author=ShahadatTest" title="Code">💻</a></td>
323
+ </tr>
324
+ </tbody>
325
+ </table>
326
+
327
+ <!-- markdownlint-restore -->
328
+ <!-- prettier-ignore-end -->
329
+
330
+ <!-- ALL-CONTRIBUTORS-LIST:END -->
331
+
306
332
  ## License
307
333
 
308
334
  MIT. See [LICENSE](LICENSE).
data/lib/oops/cli.rb CHANGED
@@ -25,7 +25,8 @@ module Oops
25
25
  when "clear" then return clear(argv.drop(1), env: env, stdout: stdout)
26
26
  end
27
27
 
28
- options = { head: nil, tail: nil, github: false, show_secrets: false, time: false, output_only: false }
28
+ options = { head: nil, tail: nil, github: false, show_secrets: false, time: false, output_only: false,
29
+ print: false }
29
30
  count = nil
30
31
  parser = OptionParser.new do |o|
31
32
  o.banner = "Usage: oops [N | err] [-n N] [options]\n " \
@@ -41,6 +42,7 @@ module Oops
41
42
  o.on("--time", "Add the time each command started") { options[:time] = true }
42
43
  o.on("--output-only", "Leave out the command line, keep the output") { options[:output_only] = true }
43
44
  o.on("--show-secrets", "Do not mask secrets or apply the replace table") { options[:show_secrets] = true }
45
+ o.on("-p", "--print", "Write the text to stdout instead of the clipboard") { options[:print] = true }
44
46
  o.on("-v", "--version", "Print version and exit") do
45
47
  stdout.puts "oops #{VERSION}"
46
48
  return 0
@@ -89,7 +91,13 @@ module Oops
89
91
  raise Failure, (target.failed_only ? "no failed command found." : "no command found yet.") if records.empty?
90
92
 
91
93
  home = env["HOME"].to_s.empty? ? Dir.home : env["HOME"]
92
- result = Formatter.new(config: config, home: home, **options).format(records)
94
+ format_options = options.except(:print)
95
+ result = Formatter.new(config: config, home: home, **format_options).format(records)
96
+ if options[:print]
97
+ stdout.write result.text
98
+ return 0
99
+ end
100
+
93
101
  backend = Clipboard.detect(config.clipboard, env: env)
94
102
  raise Failure, NO_CLIPBOARD if backend.nil?
95
103
 
data/lib/oops/recorder.rb CHANGED
@@ -148,10 +148,11 @@ module Oops
148
148
  dir = Paths.sessions_dir(env: @env)
149
149
  @session_path = SessionLog.new_path(dir)
150
150
  Paths.ensure_sessions_dir!(env: @env)
151
- rotate_logs(dir)
151
+ max_age = retention_seconds
152
+ rotate_logs(dir, max_age)
152
153
  File.open(@session_path, File::WRONLY | File::CREAT | File::APPEND, 0o600, &:itself)
153
154
  write_status("ok")
154
- SessionLog.new(@session_path)
155
+ SessionLog.new(@session_path, max_age: max_age)
155
156
  rescue StandardError => e
156
157
  @log_failed = true
157
158
  warn_line "oops: warning: session log unavailable (#{e.message}); recording disabled"
@@ -170,10 +171,14 @@ module Oops
170
171
  end
171
172
  end
172
173
 
173
- # Rotation only frees space; failing to rotate must not stop recording.
174
- def rotate_logs(dir)
174
+ def retention_seconds
175
175
  days = Config.load(env: @env).retention_days
176
- SessionLog.rotate!(dir, max_age: days && (days * 86_400))
176
+ days && (days * 86_400)
177
+ end
178
+
179
+ # Rotation only frees space; failing to rotate must not stop recording.
180
+ def rotate_logs(dir, max_age)
181
+ SessionLog.rotate!(dir, max_age: max_age)
177
182
  rescue SystemCallError
178
183
  nil
179
184
  end
@@ -1,3 +1,5 @@
1
+ require "time"
2
+
1
3
  module Oops
2
4
  # Append-only JSONL log of captured commands for one shell session. A log
3
5
  # that grows past its cap is rewritten to keep only its newest records.
@@ -8,6 +10,11 @@ module Oops
8
10
  # tab is not rewritten on every command.
9
11
  TRIM_TO = 0.75
10
12
  LOG_NAME = /\A(\d{8}-\d{6})-(\d+)\.jsonl\z/
13
+ # `ps` rounds a start time down to the second and file systems may round
14
+ # mtimes; the slack keeps such rounding from closing a live tab.
15
+ START_SLACK = 5
16
+ # How often an open tab checks its log for records older than max_age.
17
+ AGE_CHECK_INTERVAL = 3600
11
18
 
12
19
  attr_reader :path
13
20
 
@@ -21,19 +28,43 @@ module Oops
21
28
  true
22
29
  rescue Errno::EPERM
23
30
  true
24
- rescue SystemCallError
31
+ rescue SystemCallError, RangeError
25
32
  false
26
33
  end
27
34
 
35
+ # Whether the tab whose log was last written at written_at is still open.
36
+ # Process ids are reused, and the recorder starts before it ever writes its
37
+ # log, so a live process that started after the last write is someone
38
+ # else and the log is closed. The mtime is used rather than the time in
39
+ # the log name, which is local time without a zone. When the start time
40
+ # cannot be read, the log is kept.
41
+ def self.session_alive?(pid, written_at, alive: method(:process_alive?),
42
+ started_at: method(:process_started_at))
43
+ return false unless alive.call(pid)
44
+
45
+ started = started_at.call(pid)
46
+ started.nil? || started <= written_at + START_SLACK
47
+ end
48
+
49
+ # `ps -o lstart` prints the same fixed format on macOS and Linux in the C
50
+ # locale, e.g. "Wed Nov 4 22:33:04 2026". Nil when it cannot be read.
51
+ def self.process_started_at(pid)
52
+ out = IO.popen({ "LC_ALL" => "C" }, ["ps", "-o", "lstart=", "-p", pid.to_s],
53
+ err: File::NULL, &:read)
54
+ Time.strptime(out.split.join(" "), "%a %b %d %H:%M:%S %Y")
55
+ rescue SystemCallError, ArgumentError
56
+ nil
57
+ end
58
+
28
59
  # Deletes logs of finished sessions: with max_age, those last written more
29
60
  # than max_age seconds ago; then the oldest, until the total size of all
30
61
  # session logs is at most max_bytes. Logs of live sessions are kept.
31
62
  def self.rotate!(dir, max_bytes: DEFAULT_MAX_BYTES, max_age: nil, now: Time.now,
32
- alive: method(:process_alive?))
63
+ alive: method(:session_alive?))
33
64
  logs = list(dir)
34
65
  if max_age
35
66
  logs = logs.reject do |log|
36
- next false if log[:mtime] >= now - max_age || alive.call(log[:pid])
67
+ next false if log[:mtime] >= now - max_age || alive.call(log[:pid], log[:mtime])
37
68
 
38
69
  remove_log(File.join(dir, log[:name]))
39
70
  true
@@ -42,7 +73,7 @@ module Oops
42
73
  total = logs.sum { |l| l[:size] }
43
74
  logs.sort_by { |l| l[:name] }.each do |log|
44
75
  break if total <= max_bytes
45
- next if alive.call(log[:pid])
76
+ next if alive.call(log[:pid], log[:mtime])
46
77
 
47
78
  remove_log(File.join(dir, log[:name]))
48
79
  total -= log[:size]
@@ -52,8 +83,8 @@ module Oops
52
83
  end
53
84
 
54
85
  # Deletes the logs of all finished sessions. Returns how many it deleted.
55
- def self.clear!(dir, alive: method(:process_alive?))
56
- dead = list(dir).reject { |log| alive.call(log[:pid]) }
86
+ def self.clear!(dir, alive: method(:session_alive?))
87
+ dead = list(dir).reject { |log| alive.call(log[:pid], log[:mtime]) }
57
88
  dead.each { |log| remove_log(File.join(dir, log[:name])) }
58
89
  dead.size
59
90
  rescue Errno::ENOENT
@@ -83,20 +114,28 @@ module Oops
83
114
  end
84
115
  private_class_method :list, :remove_log
85
116
 
86
- def initialize(path, max_bytes: DEFAULT_MAX_BYTES)
117
+ # With max_age (seconds), records that ended longer ago than that are
118
+ # dropped from the log as new ones are appended.
119
+ def initialize(path, max_bytes: DEFAULT_MAX_BYTES, max_age: nil)
87
120
  @path = path
88
121
  @max_bytes = max_bytes
122
+ @max_age = max_age
123
+ @next_age_check = nil
89
124
  end
90
125
 
91
- # Raises if the record cannot be written. Trimming an oversized log is
92
- # best effort and never raises.
93
- def append(record)
126
+ # Raises if the record cannot be written. Trimming the log, by size or by
127
+ # age, is best effort and never raises.
128
+ def append(record, now: Time.now)
94
129
  line = record.to_json_line
95
130
  size = File.open(@path, File::APPEND | File::CREAT | File::WRONLY, 0o600) do |f|
96
131
  f.syswrite(line)
97
132
  f.size
98
133
  end
99
- trim if size > @max_bytes
134
+ if size > @max_bytes
135
+ trim
136
+ elsif age_check_due?(now)
137
+ expire((now - @max_age).to_i)
138
+ end
100
139
  end
101
140
 
102
141
  # Yields records newest first. Unparsable lines are skipped. The block can
@@ -161,11 +200,52 @@ module Oops
161
200
  end
162
201
 
163
202
  # Rewrites the log with the newest complete records that fit in TRIM_TO
164
- # of the cap (always at least the newest one). The new file is written
165
- # next to the log and renamed over it, so a reader sees either the old or
166
- # the new log, never a mix.
203
+ # of the cap (always at least the newest one).
167
204
  def trim
168
- keep = newest_lines((@max_bytes * TRIM_TO).to_i)
205
+ rewrite(newest_lines((@max_bytes * TRIM_TO).to_i))
206
+ end
207
+
208
+ def age_check_due?(now)
209
+ return false unless @max_age
210
+ return false if @next_age_check && now < @next_age_check
211
+
212
+ @next_age_check = now + AGE_CHECK_INTERVAL
213
+ true
214
+ end
215
+
216
+ # Records are appended in the order they end, so the first line is the
217
+ # oldest; the log is rewritten only when that one is too old or unreadable.
218
+ def expire(cutoff)
219
+ first = File.open(@path, "rb", &:gets)
220
+ return if first.nil?
221
+
222
+ record = parse(first.chomp)
223
+ return if record && record.ended_at.to_i >= cutoff
224
+
225
+ rewrite(lines_ended_since(cutoff))
226
+ rescue StandardError
227
+ nil
228
+ end
229
+
230
+ # Newest lines first, back to the first record that ended before cutoff.
231
+ def lines_ended_since(cutoff)
232
+ lines = []
233
+ File.open(@path, "rb") do |io|
234
+ each_line_backward(io) do |line|
235
+ record = parse(line)
236
+ next unless record
237
+ break if record.ended_at.to_i < cutoff
238
+
239
+ lines << line
240
+ end
241
+ end
242
+ lines
243
+ end
244
+
245
+ # Replaces the log with keep (newest first). The new file is written next
246
+ # to the log and renamed over it, so a reader sees either the old or the
247
+ # new log, never a mix.
248
+ def rewrite(keep)
169
249
  tmp = "#{@path}.trim"
170
250
  remove_file(tmp)
171
251
  File.open(tmp, File::WRONLY | File::CREAT | File::EXCL, 0o600) do |f|
@@ -68,6 +68,16 @@ if [[ $- == *i* ]] && [ -t 0 ] && [ -t 1 ] && [ -z "${OOPS_DISABLE:-}" ] &&
68
68
  if __oops_runs_script; then
69
69
  : # not a prompt to record; run the script as asked
70
70
  elif command -v "$__oops_bin" >/dev/null 2>&1; then
71
+ # Ghostty injects its bash integration by starting bash in POSIX mode
72
+ # with ENV pointing at it; that file sources the rc files (this one)
73
+ # with __ghostty_bash_flags set, and loads the integration afterwards.
74
+ # The restarted shell is not injected, so note whether this one is;
75
+ # the restarted shell loads the integration again (see the end).
76
+ if [ -n "${__ghostty_bash_flags+x}" ]; then
77
+ export __OOPS_GHOSTTY=1
78
+ else
79
+ unset __OOPS_GHOSTTY
80
+ fi
71
81
  # execfail: if the exec fails anyway, keep this shell running.
72
82
  __oops_execfail=$(shopt -p execfail || :)
73
83
  shopt -s execfail
@@ -128,9 +138,13 @@ if [[ $- == *i* ]] && [ -t 0 ] && [ -t 1 ] && [ -z "${OOPS_DISABLE:-}" ] &&
128
138
  [ "${BASH_SUBSHELL:-0}" = 0 ]; then
129
139
  case $BASH_COMMAND in
130
140
  __oops_precmd*) ;; # empty line: the prompt is drawn again
141
+ # Ghostty's PS0 hook, run in this shell by bash 5.3 before the line.
142
+ __ghostty_preexec_hook) ;;
131
143
  *)
132
- case $__oops_tail in
133
- *"$BASH_COMMAND"*) ;; # entries after a rewrap, see __oops_wrap
144
+ # Entries after a rewrap, see __oops_wrap. Blanks are ignored:
145
+ # bash prints `a 2>/dev/null` back as `a 2> /dev/null`.
146
+ case ${__oops_tail//[[:space:]]/} in
147
+ *"${BASH_COMMAND//[[:space:]]/}"*) ;;
134
148
  *)
135
149
  __oops_armed=
136
150
  __oops_tail=
@@ -331,6 +345,20 @@ if [[ $- == *i* ]] && [ -t 0 ] && [ -t 1 ] && [ -z "${OOPS_DISABLE:-}" ] &&
331
345
  *) PROMPT_COMMAND="${PROMPT_COMMAND:-}"$'\n'"$__oops_e_install" ;;
332
346
  esac
333
347
  fi
348
+
349
+ # The shell this one replaced was injected with Ghostty's integration
350
+ # (see above); load it here, after our hooks, as Ghostty documents for a
351
+ # manual setup. Once per shell process.
352
+ if [ -n "${__OOPS_GHOSTTY:-}" ] && [ -z "${__oops_ghostty_loaded:-}" ] &&
353
+ [ -n "${GHOSTTY_RESOURCES_DIR:-}" ] &&
354
+ [ -r "$GHOSTTY_RESOURCES_DIR/shell-integration/bash/ghostty.bash" ]; then
355
+ __oops_ghostty_loaded=1
356
+ # It reads unset variables, which `set -u` earlier in ~/.bashrc rejects.
357
+ case $- in *u*) __oops_nounset=1 && set +u ;; *) __oops_nounset= ;; esac
358
+ builtin source "$GHOSTTY_RESOURCES_DIR/shell-integration/bash/ghostty.bash"
359
+ if [ -n "$__oops_nounset" ]; then set -u; fi
360
+ unset __oops_nounset
361
+ fi
334
362
  fi
335
363
  unset -f __oops_runs_script
336
364
  fi
@@ -19,7 +19,8 @@ module Oops
19
19
  # 2. Recording. Content bytes seen between a start marker and the matching
20
20
  # end marker are stored for that command, except inside alternate-screen
21
21
  # spans ("ESC [ ? 1049 h", "ESC [ ? 1047 h", "ESC [ ? 47 h" up to any of
22
- # the matching "l" forms), which are replaced by one OMITTED line. The
22
+ # the matching "l" forms), which are replaced by one line, e.g.
23
+ # "[git: full-screen output omitted]" (see omitted_line). The
23
24
  # alternate-screen detector keeps its own small pending tail so that a
24
25
  # sequence split across chunks is still recognised; this only delays
25
26
  # storing, never forwarding.
@@ -32,6 +33,14 @@ module Oops
32
33
  # and the marker is ignored when it returns false.
33
34
  class StreamParser
34
35
  OMITTED = "[full-screen app output omitted]\n".b.freeze
36
+ # A shell variable assignment before the command, as in LANG=C git log.
37
+ ASSIGNMENT = /\A[A-Za-z_][A-Za-z0-9_]*=/n
38
+ # Only a plain word is shown as the name. Anything else (quotes, a URL
39
+ # with a password, a NUL byte) is not a command name worth the risk.
40
+ PLAIN_WORD = %r{\A[A-Za-z0-9_.+/-]+\z}n
41
+ # In a line with several commands the first word may not be the program
42
+ # that went full screen (echo a; less b), so such lines get no name.
43
+ SEVERAL_COMMANDS = /[;&|()`{}\n]|\$\(/n
35
44
  MAX_HELD_MARKER = 65_536
36
45
 
37
46
  PREFIX = Marker::PREFIX
@@ -323,7 +332,7 @@ module Oops
323
332
  return
324
333
  end
325
334
  cmd.buffer << data.byteslice(pos, match.begin(0) - pos)
326
- cmd.buffer << OMITTED
335
+ cmd.buffer << omitted_line(cmd.cmd)
327
336
  cmd.fullscreen = true
328
337
  cmd.in_span = true
329
338
  end
@@ -331,6 +340,20 @@ module Oops
331
340
  end
332
341
  end
333
342
 
343
+ # Names the command's first word (after any VAR=value), without its
344
+ # directory. The program that switched screens may be one it started, as
345
+ # git starts less, so this is the command the user typed, not the pager.
346
+ def omitted_line(command_line)
347
+ line = command_line.to_s.b
348
+ return OMITTED if line.match?(SEVERAL_COMMANDS)
349
+
350
+ word = line.split.find { |w| !w.match?(ASSIGNMENT) }
351
+ name = word[%r{[^/]+\z}n] if word&.match?(PLAIN_WORD)
352
+ return OMITTED unless name
353
+
354
+ "[#{name}: full-screen output omitted]\n".b
355
+ end
356
+
334
357
  # Index of the earliest ESC at or after from whose tail is a proper prefix
335
358
  # of one of seqs, or nil.
336
359
  def partial_start(data, from, seqs)
data/lib/oops/version.rb CHANGED
@@ -1,3 +1,3 @@
1
1
  module Oops
2
- VERSION = "0.3.0".freeze
2
+ VERSION = "0.4.1".freeze
3
3
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: oops-cli
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.0
4
+ version: 0.4.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - ysb3996-blip
@@ -68,7 +68,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
68
68
  - !ruby/object:Gem::Version
69
69
  version: '0'
70
70
  requirements: []
71
- rubygems_version: 4.0.20
71
+ rubygems_version: 4.0.23
72
72
  specification_version: 4
73
73
  summary: Copy the last shell command and its output to the clipboard
74
74
  test_files: []