Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

feat: add --hook flag to wt config state logs get (#803) (#816)

Maximilian Roos583a43764af6
diff --git a/.claude-plugin/skills/worktrunk/reference/config.md b/.claude-plugin/skills/worktrunk/reference/config.md
index 57413422a..5750be59d 100644
--- a/.claude-plugin/skills/worktrunk/reference/config.md
+++ b/.claude-plugin/skills/worktrunk/reference/config.md
@@ -744,7 +744,7 @@ wt config state logs - Background operation logs
Usage: <b><span class=c>wt config state logs</span></b> <span class=c>[OPTIONS]</span> <span class=c>[COMMAND]</span>
<b><span class=g>Commands:</span></b>
- <b><span class=c>get</span></b> List background operation log files
+ <b><span class=c>get</span></b> Get log file paths
<b><span class=c>clear</span></b> Clear background operation logs
<b><span class=g>Options:</span></b>
diff --git a/docs/content/config.md b/docs/content/config.md
index 4744f600f..51abfba4e 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -765,7 +765,7 @@ wt config state logs - Background operation logs
Usage: <b><span class=c>wt config state logs</span></b> <span class=c>[OPTIONS]</span> <span class=c>[COMMAND]</span>
<b><span class=g>Commands:</span></b>
- <b><span class=c>get</span></b> List background operation log files
+ <b><span class=c>get</span></b> Get log file paths
<b><span class=c>clear</span></b> Clear background operation logs
<b><span class=g>Options:</span></b>
diff --git a/docs/content/hook.md b/docs/content/hook.md
index 9c7b26460..d8492269c 100644
--- a/docs/content/hook.md
+++ b/docs/content/hook.md
@@ -426,6 +426,7 @@ For copying dependencies and caches between worktrees, see [`wt step copy-ignore
- [`wt merge`](@/merge.md) — Runs hooks automatically during merge
- [`wt switch`](@/switch.md) — Runs post-create/post-start hooks on `--create`
- [`wt config`](@/config.md) — Manage hook approvals
+- [`wt config state logs`](@/config.md#wt-config-state-logs) — Access background hook logs
## Command reference
diff --git a/src/cli/config.rs b/src/cli/config.rs
index c8a5f6edc..3954ab4a1 100644
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -691,18 +691,50 @@ wt config state marker clear --all
#[derive(Subcommand)]
pub enum LogsAction {
- /// List background operation log files
+ /// Get log file paths
#[command(
- after_long_help = r#"Lists log files from background operations like post-start commands and worktree removal.
+ after_long_help = r#"Lists log files, or gets the path to a specific log.
## Examples
-List log files:
+List all log files:
```console
wt config state logs
+```
+
+Get path to a specific hook log:
+```console
+wt config state logs get --hook=user:post-start:server
+```
+
+Stream a hook's log output:
+```console
+tail -f "$(wt config state logs get --hook=user:post-start:server)"
+```
+
+Get log for background worktree removal:
+```console
+wt config state logs get --hook=internal:remove
+```
+
+Get log for a different branch:
+```console
+wt config state logs get --hook=user:post-start:server --branch=feature
```"#
)]
- Get,
+ Get {
+ /// Get path for a specific log file
+ ///
+ /// Format: source:hook-type:name (e.g., user:post-start:server) for
+ /// hook commands, or internal:op (e.g., internal:remove) for internal
+ /// operations.
+ #[arg(long)]
+ hook: Option<String>,
+
+ /// Target branch (defaults to current)
+ #[arg(long, add = crate::completion::branch_value_completer())]
+ branch: Option<String>,
+ },
/// Clear background operation logs
Clear,
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index d084c627b..68fc7b26a 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1452,6 +1452,7 @@ For copying dependencies and caches between worktrees, see [`wt step copy-ignore
- [`wt merge`](@/merge.md) — Runs hooks automatically during merge
- [`wt switch`](@/switch.md) — Runs post-create/post-start hooks on `--create`
- [`wt config`](@/config.md) — Manage hook approvals
+- [`wt config state logs`](@/config.md#wt-config-state-logs) — Access background hook logs
<!-- subdoc: approvals -->
"#
diff --git a/src/commands/config/mod.rs b/src/commands/config/mod.rs
index 7c7c81877..037274fc4 100644
--- a/src/commands/config/mod.rs
+++ b/src/commands/config/mod.rs
@@ -12,8 +12,8 @@ pub use create::handle_config_create;
pub use hints::{handle_hints_clear, handle_hints_get};
pub use show::handle_config_show;
pub use state::{
- handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,
- handle_state_show,
+ handle_logs_get, handle_state_clear, handle_state_clear_all, handle_state_get,
+ handle_state_set, handle_state_show,
};
#[cfg(test)]
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index 7b2413101..b332aabe9 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -9,11 +9,14 @@ use std::path::PathBuf;
use color_print::cformat;
use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};
use worktrunk::git::Repository;
-use worktrunk::path::format_path_for_display;
+use worktrunk::path::{format_path_for_display, sanitize_for_filename};
use worktrunk::styling::{
eprintln, format_heading, format_with_gutter, info_message, println, success_message,
warning_message,
};
+
+use crate::cli::OutputFormat;
+use crate::commands::process::HookLog;
use worktrunk::utils::get_now;
use super::super::list::ci_status::{CachedCiStatus, CiBranchName};
@@ -161,6 +164,95 @@ pub(super) fn render_log_files(out: &mut String, repo: &Repository) -> anyhow::R
Ok(())
}
+// ==================== Logs Get Command ====================
+
+/// Handle the logs get command
+///
+/// When `hook` is None, lists all log files.
+/// When `hook` is Some, returns the path to the specific log file for that hook.
+///
+/// # Hook spec format
+///
+/// - `source:hook-type:name` for hook commands (e.g., `user:post-start:server`)
+/// - `internal:op` for internal operations (e.g., `internal:remove`)
+pub fn handle_logs_get(hook: Option<String>, branch: Option<String>) -> anyhow::Result<()> {
+ let repo = Repository::current()?;
+
+ match hook {
+ None => {
+ // No hook specified, show all log files (existing behavior)
+ let mut out = String::new();
+ render_log_files(&mut out, &repo)?;
+
+ // Display through pager (fall back to stderr if pager unavailable)
+ if show_help_in_pager(&out, true).is_err() {
+ eprintln!("{}", out);
+ }
+ }
+ Some(hook_spec) => {
+ // Get the branch name
+ let branch = match branch {
+ Some(b) => b,
+ None => repo.require_current_branch("get log for current branch")?,
+ };
+
+ let log_dir = repo.wt_logs_dir();
+
+ // Parse the hook spec using HookLog
+ let hook_log = HookLog::parse(&hook_spec).map_err(|e| anyhow::anyhow!("{}", e))?;
+
+ // Check log directory exists
+ if !log_dir.exists() {
+ anyhow::bail!(
+ "No log directory exists. Run a background hook first to create logs."
+ );
+ }
+
+ // Get the expected log path
+ let log_path = hook_log.path(&log_dir, &branch);
+
+ if log_path.exists() {
+ // Output just the path to stdout for easy piping
+ println!("{}", log_path.display());
+ return Ok(());
+ }
+
+ // No match found - show expected filename and available files
+ let expected_filename = hook_log.filename(&branch);
+ let safe_branch = sanitize_for_filename(&branch);
+ let mut available = Vec::new();
+ if let Ok(entries) = std::fs::read_dir(&log_dir) {
+ for entry in entries.filter_map(|e| e.ok()) {
+ let name = entry.file_name().to_string_lossy().to_string();
+ if name.starts_with(&format!("{}-", safe_branch)) && name.ends_with(".log") {
+ available.push(name);
+ }
+ }
+ }
+
+ if available.is_empty() {
+ anyhow::bail!(cformat!(
+ "No log files for branch <bold>{}</>. Run a background hook first.",
+ branch
+ ));
+ } else {
+ let available_list = available.join(", ");
+ let details = format!(
+ "Expected: {}\nAvailable: {}",
+ expected_filename, available_list
+ );
+ return Err(anyhow::anyhow!(details).context(cformat!(
+ "No log file matches <bold>{}</> for branch <bold>{}</>",
+ hook_log.to_spec(),
+ branch
+ )));
+ }
+ }
+ }
+
+ Ok(())
+}
+
// ==================== State Get/Set/Clear Commands ====================
/// Handle the state get command
@@ -498,9 +590,7 @@ pub fn handle_state_clear_all() -> anyhow::Result<()> {
// ==================== State Show Commands ====================
/// Handle the state get command (shows all state)
-pub fn handle_state_show(format: crate::cli::OutputFormat) -> anyhow::Result<()> {
- use crate::cli::OutputFormat;
-
+pub fn handle_state_show(format: OutputFormat) -> anyhow::Result<()> {
let repo = Repository::current()?;
match format {
diff --git a/src/commands/hook_filter.rs b/src/commands/hook_filter.rs
index cf3fadd08..e7b0d0e64 100644
--- a/src/commands/hook_filter.rs
+++ b/src/commands/hook_filter.rs
@@ -8,7 +8,7 @@
///
/// Approval for project hooks is handled at the gate (command entry point),
/// not during hook execution.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, strum::Display)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq, strum::Display, strum::EnumString)]
#[strum(serialize_all = "kebab-case")]
pub enum HookSource {
/// User hooks from ~/.config/worktrunk/config.toml (no approval required)
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index fd663eecb..a08df31f7 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -10,7 +10,7 @@ use worktrunk::styling::{
};
use super::command_executor::{CommandContext, PreparedCommand, prepare_commands};
-use crate::commands::process::spawn_detached;
+use crate::commands::process::{HookLog, spawn_detached};
use crate::output::execute_command_in_worktree;
/// A prepared command with its source information.
@@ -183,8 +183,6 @@ pub fn spawn_hook_commands_background(
eprintln!("{}", progress_message(message));
}
- let operation_prefix = hook_type.to_string();
-
// Track index for unnamed commands to prevent log collisions
let mut unnamed_index = 0usize;
@@ -201,16 +199,15 @@ pub fn spawn_hook_commands_background(
format!("cmd-{idx}")
}
};
- // Include source in operation name to prevent log file collisions between
- // user and project hooks with the same name
- let operation = format!("{}-{}-{}", cmd.source, operation_prefix, name);
+ // Use HookLog for consistent log file naming
+ let hook_log = HookLog::hook(cmd.source, hook_type, &name);
if let Err(err) = spawn_detached(
ctx.repo,
ctx.worktree_path,
&cmd.prepared.expanded,
ctx.branch_or_head(),
- &operation,
+ &hook_log,
Some(&cmd.prepared.context_json),
) {
let err_msg = err.to_string();
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 7b7b0c51b..a486333ff 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -23,8 +23,8 @@ pub(crate) mod worktree;
pub(crate) use config::{
handle_config_create, handle_config_show, handle_hints_clear, handle_hints_get,
- handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,
- handle_state_show,
+ handle_logs_get, handle_state_clear, handle_state_clear_all, handle_state_get,
+ handle_state_set, handle_state_show,
};
pub(crate) use configure_shell::{
handle_configure_shell, handle_show_theme, handle_unconfigure_shell,
diff --git a/src/commands/process.rs b/src/commands/process.rs
index 958e8ff8b..e9aaaf318 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -1,12 +1,173 @@
use anyhow::Context;
+use color_print::cformat;
use std::fs;
-use std::path::Path;
+use std::path::{Path, PathBuf};
#[cfg(unix)]
use std::process::Command;
use std::process::Stdio;
-use worktrunk::git::Repository;
+use std::str::FromStr;
+use strum::IntoEnumIterator;
+use worktrunk::git::{HookType, Repository};
use worktrunk::path::{format_path_for_display, sanitize_for_filename};
+use crate::commands::hook_filter::HookSource;
+
+// ==================== Hook Log Specification ====================
+
+/// Internal worktrunk operations that produce log files.
+///
+/// These are operations performed by worktrunk itself (not user-defined hooks).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::EnumString, strum::Display)]
+#[strum(serialize_all = "kebab-case")]
+pub enum InternalOp {
+ /// Background worktree removal (`wt remove` in background mode)
+ Remove,
+}
+
+/// Specification for a hook log file.
+///
+/// This is the single source of truth for hook log file naming.
+/// Used by both log creation (in `spawn_detached`) and log lookup (in `handle_logs_get`).
+///
+/// # Log file naming
+///
+/// Hook commands produce logs named: `{branch}-{source}-{hook_type}-{name}.log`
+/// - Example: `feature-user-post-start-server.log`
+///
+/// Internal operations produce logs named: `{branch}-{op}.log`
+/// - Example: `feature-remove.log`
+///
+/// # CLI format for lookup
+///
+/// The first segment determines the log type:
+/// - `user:hook-type:name` → User hook (e.g., `user:post-start:server`)
+/// - `project:hook-type:name` → Project hook (e.g., `project:post-create:build`)
+/// - `internal:op` → Internal operation (e.g., `internal:remove`)
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum HookLog {
+ /// Hook command log: `{branch}-{source}-{hook_type}-{name}.log`
+ Hook {
+ source: HookSource,
+ hook_type: HookType,
+ name: String,
+ },
+ /// Internal operation log: `{branch}-{op}.log`
+ Internal(InternalOp),
+}
+
+impl HookLog {
+ /// Create a hook command log specification.
+ pub fn hook(source: HookSource, hook_type: HookType, name: impl Into<String>) -> Self {
+ Self::Hook {
+ source,
+ hook_type,
+ name: name.into(),
+ }
+ }
+
+ /// Create an internal operation log specification.
+ pub fn internal(op: InternalOp) -> Self {
+ Self::Internal(op)
+ }
+
+ /// Generate the suffix (without branch) for the log filename.
+ ///
+ /// This is what gets appended after `{branch}-` in the log filename.
+ pub fn suffix(&self) -> String {
+ match self {
+ HookLog::Hook {
+ source,
+ hook_type,
+ name,
+ } => {
+ // HookSource uses #[strum(serialize_all = "kebab-case")] which produces lowercase
+ format!("{}-{}-{}", source, hook_type, sanitize_for_filename(name))
+ }
+ HookLog::Internal(op) => op.to_string(),
+ }
+ }
+
+ /// Generate full log filename for a branch.
+ pub fn filename(&self, branch: &str) -> String {
+ let safe_branch = sanitize_for_filename(branch);
+ format!("{}-{}.log", safe_branch, self.suffix())
+ }
+
+ /// Generate full log path for a branch in the given log directory.
+ pub fn path(&self, log_dir: &Path, branch: &str) -> PathBuf {
+ log_dir.join(self.filename(branch))
+ }
+
+ /// Convert to CLI spec format (for error messages and roundtrip).
+ ///
+ /// Returns the format used by `parse()`: `source:hook-type:name` or `internal:op`.
+ pub fn to_spec(&self) -> String {
+ match self {
+ HookLog::Hook {
+ source,
+ hook_type,
+ name,
+ } => format!("{}:{}:{}", source, hook_type, name),
+ HookLog::Internal(op) => format!("internal:{}", op),
+ }
+ }
+
+ /// Parse from CLI argument.
+ ///
+ /// # Formats
+ ///
+ /// The first segment determines the type:
+ /// - `user:hook-type:name` → User hook log
+ /// - `project:hook-type:name` → Project hook log
+ /// - `internal:op` → Internal operation log
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if the format is invalid or unrecognized.
+ pub fn parse(s: &str) -> Result<Self, String> {
+ let parts: Vec<&str> = s.split(':').collect();
+
+ match parts.as_slice() {
+ // internal:op
+ ["internal", op_str] => {
+ let op = InternalOp::from_str(op_str).map_err(|_| {
+ cformat!(
+ "Unknown internal operation: <bold>{}</>. Valid: remove",
+ op_str
+ )
+ })?;
+ Ok(Self::Internal(op))
+ }
+ // source:hook-type:name
+ [source_str, hook_type_str, name] => {
+ let source = HookSource::from_str(source_str).map_err(|_| {
+ cformat!(
+ "Unknown source: <bold>{}</>. Valid: user, project",
+ source_str
+ )
+ })?;
+ let hook_type = HookType::from_str(hook_type_str).map_err(|_| {
+ let valid: Vec<_> = HookType::iter().map(|h| h.to_string()).collect();
+ cformat!(
+ "Unknown hook type: <bold>{}</>. Valid: {}",
+ hook_type_str,
+ valid.join(", ")
+ )
+ })?;
+ Ok(Self::Hook {
+ source,
+ hook_type,
+ name: (*name).to_string(),
+ })
+ }
+ _ => Err(cformat!(
+ "Invalid log spec: <bold>{}</>. Format: source:hook-type:name or internal:op",
+ s
+ )),
+ }
+ }
+}
+
/// Get the separator needed before closing brace in POSIX shell command grouping.
/// Returns empty string if command already ends with newline or semicolon.
fn posix_command_separator(command: &str) -> &'static str {
@@ -30,7 +191,7 @@ fn posix_command_separator(command: &str) -> &'static str {
/// * `worktree_path` - Working directory for the command
/// * `command` - Shell command to execute
/// * `branch` - Branch name for log organization
-/// * `name` - Operation identifier (e.g., "post-start-npm", "remove")
+/// * `hook_log` - Log specification (determines the log filename)
/// * `context_json` - Optional JSON context to pipe to command's stdin
///
/// # Returns
@@ -40,7 +201,7 @@ pub fn spawn_detached(
worktree_path: &Path,
command: &str,
branch: &str,
- name: &str,
+ hook_log: &HookLog,
context_json: Option<&str>,
) -> anyhow::Result<std::path::PathBuf> {
// Create log directory in the common git directory
@@ -52,11 +213,8 @@ pub fn spawn_detached(
)
})?;
- // Generate log filename (no timestamp - overwrites on each run)
- // Format: {branch}-{name}.log (e.g., "feature-post-start-npm.log", "bugfix-remove.log")
- let safe_branch = sanitize_for_filename(branch);
- let safe_name = sanitize_for_filename(name);
- let log_path = log_dir.join(format!("{}-{}.log", safe_branch, safe_name));
+ // Generate log path using the HookLog specification
+ let log_path = hook_log.path(&log_dir, branch);
// Create log file
let log_file = fs::File::create(&log_path).with_context(|| {
@@ -67,10 +225,9 @@ pub fn spawn_detached(
})?;
log::debug!(
- "$ {} (detached, logging to {}-{}.log)",
+ "$ {} (detached, logging to {})",
command,
- safe_branch,
- safe_name
+ log_path.file_name().unwrap_or_default().to_string_lossy()
);
#[cfg(unix)]
@@ -373,4 +530,135 @@ mod tests {
let cmd = build_remove_command(&special_path, Some("feature/branch"), false);
assert!(cmd.contains("worktree remove"));
}
+
+ #[test]
+ fn test_hook_log_hook_suffix() {
+ use worktrunk::git::HookType;
+
+ let log = HookLog::hook(HookSource::User, HookType::PostStart, "server");
+ assert_eq!(log.suffix(), "user-post-start-server");
+
+ let log = HookLog::hook(HookSource::Project, HookType::PostCreate, "build");
+ assert_eq!(log.suffix(), "project-post-create-build");
+
+ let log = HookLog::hook(HookSource::User, HookType::PreRemove, "cleanup");
+ assert_eq!(log.suffix(), "user-pre-remove-cleanup");
+ }
+
+ #[test]
+ fn test_hook_log_internal_suffix() {
+ let log = HookLog::internal(InternalOp::Remove);
+ assert_eq!(log.suffix(), "remove");
+ }
+
+ #[test]
+ fn test_hook_log_filename() {
+ use worktrunk::git::HookType;
+
+ let log = HookLog::hook(HookSource::User, HookType::PostStart, "server");
+ assert_eq!(log.filename("main"), "main-user-post-start-server.log");
+ assert_eq!(
+ log.filename("feature/auth"),
+ "feature-auth-user-post-start-server.log"
+ );
+
+ let log = HookLog::internal(InternalOp::Remove);
+ assert_eq!(log.filename("main"), "main-remove.log");
+ }
+
+ #[test]
+ fn test_hook_log_parse_hook() {
+ let log = HookLog::parse("user:post-start:server").unwrap();
+ assert_eq!(log.suffix(), "user-post-start-server");
+
+ let log = HookLog::parse("project:post-create:build").unwrap();
+ assert_eq!(log.suffix(), "project-post-create-build");
+ }
+
+ #[test]
+ fn test_hook_log_parse_internal() {
+ let log = HookLog::parse("internal:remove").unwrap();
+ assert_eq!(log, HookLog::Internal(InternalOp::Remove));
+ assert_eq!(log.suffix(), "remove");
+ }
+
+ #[test]
+ fn test_hook_log_parse_invalid_source() {
+ let result = HookLog::parse("invalid:post-start:server");
+ assert!(result.is_err());
+ assert!(result.unwrap_err().contains("Unknown source"));
+ }
+
+ #[test]
+ fn test_hook_log_parse_invalid_hook_type() {
+ let result = HookLog::parse("user:invalid-hook:server");
+ assert!(result.is_err());
+ assert!(result.unwrap_err().contains("Unknown hook type"));
+ }
+
+ #[test]
+ fn test_hook_log_parse_invalid_internal_op() {
+ let result = HookLog::parse("internal:unknown");
+ assert!(result.is_err());
+ assert!(result.unwrap_err().contains("Unknown internal operation"));
+ }
+
+ #[test]
+ fn test_hook_log_parse_invalid_format() {
+ // Too many colons
+ let result = HookLog::parse("user:post-start:server:extra");
+ assert!(result.is_err());
+ assert!(result.unwrap_err().contains("Invalid log spec"));
+
+ // Single word (not valid anymore)
+ let result = HookLog::parse("remove");
+ assert!(result.is_err());
+ assert!(result.unwrap_err().contains("Invalid log spec"));
+
+ // Two colons but not internal:op
+ let result = HookLog::parse("foo:bar");
+ assert!(result.is_err());
+ }
+
+ #[test]
+ fn test_hook_log_roundtrip() {
+ // What gets created should match what gets looked up
+ use worktrunk::git::HookType;
+
+ // Hook: create the same way hooks.rs does, parse the same way state.rs does
+ let created = HookLog::hook(HookSource::User, HookType::PostStart, "server");
+ let parsed = HookLog::parse("user:post-start:server").unwrap();
+ assert_eq!(created.filename("main"), parsed.filename("main"));
+
+ // Internal: create the same way handlers.rs does, parse from CLI
+ let created = HookLog::internal(InternalOp::Remove);
+ let parsed = HookLog::parse("internal:remove").unwrap();
+ assert_eq!(created.filename("main"), parsed.filename("main"));
+ }
+
+ #[test]
+ fn test_hook_log_to_spec_roundtrip() {
+ use worktrunk::git::HookType;
+
+ // Hook roundtrip: to_spec -> parse -> equals original
+ let original = HookLog::hook(HookSource::User, HookType::PostStart, "server");
+ let spec = original.to_spec();
+ assert_eq!(spec, "user:post-start:server");
+ let parsed = HookLog::parse(&spec).unwrap();
+ assert_eq!(original, parsed);
+
+ // Project hook
+ let original = HookLog::hook(HookSource::Project, HookType::PreMerge, "lint");
+ let spec = original.to_spec();
+ assert_eq!(spec, "project:pre-merge:lint");
+ let parsed = HookLog::parse(&spec).unwrap();
+ assert_eq!(original, parsed);
+
+ // Internal roundtrip
+ let original = HookLog::internal(InternalOp::Remove);
+ let spec = original.to_spec();
+ assert_eq!(spec, "internal:remove");
+ let parsed = HookLog::parse(&spec).unwrap();
+ assert_eq!(original, parsed);
+ }
}
diff --git a/src/main.rs b/src/main.rs
index 90bd8e423..26a9cbfcb 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -49,10 +49,11 @@ use commands::{
MergeOptions, OperationMode, RebaseResult, SquashResult, add_approvals, clear_approvals,
execute_switch, handle_completions, handle_config_create, handle_config_show,
handle_configure_shell, handle_hints_clear, handle_hints_get, handle_hook_show, handle_init,
- handle_list, handle_merge, handle_rebase, handle_remove, handle_remove_current,
- handle_show_theme, handle_squash, handle_state_clear, handle_state_clear_all, handle_state_get,
- handle_state_set, handle_state_show, handle_unconfigure_shell, plan_switch,
- resolve_worktree_arg, run_hook, step_commit, step_copy_ignored, step_for_each,
+ handle_list, handle_logs_get, handle_merge, handle_rebase, handle_remove,
+ handle_remove_current, handle_show_theme, handle_squash, handle_state_clear,
+ handle_state_clear_all, handle_state_get, handle_state_set, handle_state_show,
+ handle_unconfigure_shell, plan_switch, resolve_worktree_arg, run_hook, step_commit,
+ step_copy_ignored, step_for_each,
};
use output::{execute_user_command, handle_remove_output, handle_switch_output};
@@ -488,7 +489,8 @@ fn main() {
}
},
StateCommand::Logs { action } => match action {
- Some(LogsAction::Get) | None => handle_state_get("logs", None),
+ Some(LogsAction::Get { hook, branch }) => handle_logs_get(hook, branch),
+ None => handle_logs_get(None, None),
Some(LogsAction::Clear) => handle_state_clear("logs", None, false),
},
StateCommand::Hints { action } => match action {
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index a71f68729..18b3d7674 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -13,7 +13,7 @@ use crate::commands::branch_deletion::{
};
use crate::commands::command_executor::CommandContext;
use crate::commands::execute_pre_remove_commands;
-use crate::commands::process::{build_remove_command, spawn_detached};
+use crate::commands::process::{HookLog, InternalOp, build_remove_command, spawn_detached};
use crate::commands::worktree::{BranchDeletionMode, RemoveResult, SwitchBranchInfo, SwitchResult};
use worktrunk::config::UserConfig;
use worktrunk::git::GitError;
@@ -917,7 +917,7 @@ fn handle_removed_worktree_output(
main_path,
&remove_command,
"detached",
- "remove",
+ &HookLog::internal(InternalOp::Remove),
None,
)?;
} else {
@@ -980,7 +980,7 @@ fn handle_removed_worktree_output(
main_path,
&remove_command,
branch_name,
- "remove",
+ &HookLog::internal(InternalOp::Remove),
None,
)?;
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index 98c20bb97..e0740ef2b 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -1113,3 +1113,230 @@ fn test_state_hints_clear_specific_not_set(repo: TestRepo) {
assert!(output.status.success());
assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"○ Hint nonexistent was not set");
}
+
+// ============================================================================
+// logs get --hook
+// ============================================================================
+
+#[rstest]
+fn test_state_logs_get_hook_returns_path(repo: TestRepo) {
+ // Create wt-logs directory with a post-start log file
+ let git_dir = repo.root_path().join(".git");
+ let log_dir = git_dir.join("wt-logs");
+ std::fs::create_dir_all(&log_dir).unwrap();
+ let log_file = log_dir.join("main-user-post-start-server.log");
+ std::fs::write(&log_file, "server output here").unwrap();
+
+ // Use explicit format: source:hook-type:name
+ let output = wt_state_cmd(&repo, "logs", "get", &["--hook=user:post-start:server"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ // The path should be printed to stdout for piping
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("main-user-post-start-server.log"),
+ "Expected log path in stdout: {}",
+ stdout
+ );
+}
+
+#[rstest]
+fn test_state_logs_get_hook_project_source(repo: TestRepo) {
+ // Test that project source logs are found with explicit format
+ let git_dir = repo.root_path().join(".git");
+ let log_dir = git_dir.join("wt-logs");
+ std::fs::create_dir_all(&log_dir).unwrap();
+ let log_file = log_dir.join("main-project-post-start-build.log");
+ std::fs::write(&log_file, "build output here").unwrap();
+
+ // Use explicit format: source:hook-type:name
+ let output = wt_state_cmd(&repo, "logs", "get", &["--hook=project:post-start:build"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("main-project-post-start-build.log"),
+ "Expected log path in stdout: {}",
+ stdout
+ );
+}
+
+#[rstest]
+fn test_state_logs_get_hook_internal_op(repo: TestRepo) {
+ // Test finding an internal operation log (e.g., "internal:remove")
+ let git_dir = repo.root_path().join(".git");
+ let log_dir = git_dir.join("wt-logs");
+ std::fs::create_dir_all(&log_dir).unwrap();
+ let log_file = log_dir.join("main-remove.log");
+ std::fs::write(&log_file, "remove output").unwrap();
+
+ let output = wt_state_cmd(&repo, "logs", "get", &["--hook=internal:remove"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("main-remove.log"),
+ "Expected log path in stdout: {}",
+ stdout
+ );
+}
+
+#[rstest]
+fn test_state_logs_get_hook_not_found(repo: TestRepo) {
+ // Create wt-logs directory with some log files but not the requested one
+ let git_dir = repo.root_path().join(".git");
+ let log_dir = git_dir.join("wt-logs");
+ std::fs::create_dir_all(&log_dir).unwrap();
+ std::fs::write(
+ log_dir.join("main-user-post-start-other.log"),
+ "other output",
+ )
+ .unwrap();
+
+ // Use explicit format: source:hook-type:name
+ let output = wt_state_cmd(&repo, "logs", "get", &["--hook=user:post-start:server"])
+ .output()
+ .unwrap();
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ // Check key parts separately (ANSI bold codes may appear around values)
+ assert!(
+ stderr.contains("No log file matches") && stderr.contains("user:post-start:server"),
+ "Expected spec echo in error: {}",
+ stderr
+ );
+ assert!(
+ stderr.contains("Expected: main-user-post-start-server.log"),
+ "Expected filename in error: {}",
+ stderr
+ );
+ assert!(
+ stderr.contains("Available:"),
+ "Expected list of available logs: {}",
+ stderr
+ );
+}
+
+#[rstest]
+fn test_state_logs_get_hook_no_logs_dir(repo: TestRepo) {
+ // No log directory exists
+ // Use explicit format: source:hook-type:name
+ let output = wt_state_cmd(&repo, "logs", "get", &["--hook=user:post-start:server"])
+ .output()
+ .unwrap();
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("No log directory exists"),
+ "Expected 'No log directory exists' error: {}",
+ stderr
+ );
+}
+
+#[rstest]
+fn test_state_logs_get_hook_no_logs_for_branch(repo: TestRepo) {
+ // Create wt-logs directory with logs for different branch
+ let git_dir = repo.root_path().join(".git");
+ let log_dir = git_dir.join("wt-logs");
+ std::fs::create_dir_all(&log_dir).unwrap();
+ std::fs::write(
+ log_dir.join("other-branch-user-post-start-server.log"),
+ "other output",
+ )
+ .unwrap();
+
+ // Use explicit format: source:hook-type:name
+ let output = wt_state_cmd(&repo, "logs", "get", &["--hook=user:post-start:server"])
+ .output()
+ .unwrap();
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("No log files for branch"),
+ "Expected 'No log files for branch' error: {}",
+ stderr
+ );
+}
+
+#[rstest]
+fn test_state_logs_get_hook_with_branch_flag(repo: TestRepo) {
+ // Create log file for a different branch
+ repo.git_command()
+ .args(["branch", "feature"])
+ .status()
+ .unwrap();
+
+ let git_dir = repo.root_path().join(".git");
+ let log_dir = git_dir.join("wt-logs");
+ std::fs::create_dir_all(&log_dir).unwrap();
+ std::fs::write(
+ log_dir.join("feature-user-post-start-dev.log"),
+ "dev output",
+ )
+ .unwrap();
+
+ // Use explicit format: source:hook-type:name
+ let output = wt_state_cmd(
+ &repo,
+ "logs",
+ "get",
+ &["--hook=user:post-start:dev", "--branch=feature"],
+ )
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("feature-user-post-start-dev.log"),
+ "Expected log path in stdout: {}",
+ stdout
+ );
+}
+
+#[rstest]
+fn test_state_logs_get_hook_invalid_format(repo: TestRepo) {
+ // Test invalid hook spec format (too many colons)
+ let output = wt_state_cmd(&repo, "logs", "get", &["--hook=a:b:c:d"])
+ .output()
+ .unwrap();
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("Invalid log spec"),
+ "Expected 'Invalid log spec' error: {}",
+ stderr
+ );
+}
+
+#[rstest]
+fn test_state_logs_get_hook_invalid_source(repo: TestRepo) {
+ // Test invalid source
+ let output = wt_state_cmd(&repo, "logs", "get", &["--hook=invalid:post-start:server"])
+ .output()
+ .unwrap();
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("Unknown source"),
+ "Expected 'Unknown source' error: {}",
+ stderr
+ );
+}
+
+#[rstest]
+fn test_state_logs_get_hook_invalid_hook_type(repo: TestRepo) {
+ // Test invalid hook type
+ let output = wt_state_cmd(&repo, "logs", "get", &["--hook=user:invalid:server"])
+ .output()
+ .unwrap();
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("Unknown hook type"),
+ "Expected 'Unknown hook type' error: {}",
+ stderr
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap
index 660c733f6..57264a981 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap
@@ -11,6 +11,8 @@ info:
CLICOLOR_FORCE: "1"
COLUMNS: "500"
GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
RUST_LOG: warn
SHELL: ""
TERM: alacritty
@@ -29,7 +31,7 @@ wt config state logs - Background operation logs
Usage: wt config state logs [OPTIONS] [COMMAND]
Commands:
- get List background operation log files
+ get Get log file paths
clear Clear background operation logs
Options: