ccy 0.1.0

Console Command Yank - captures and yanks the last terminal command output to clipboard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use clap::{Arg, Command};
use dirs::cache_dir;
use std::fs;
use std::path::PathBuf;
use std::process;
use thiserror::Error;

mod session;

#[derive(Error, Debug)]
pub enum CcyError {
    #[error("No cache directory found")]
    NoCacheDir,
    #[error("No recent command output found")]
    NoRecentOutput,
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),
    #[cfg(feature = "clipboard")]
    #[error("Clipboard error: {0}")]
    Clipboard(String),
}

#[derive(serde::Deserialize, serde::Serialize, Debug)]
struct CommandOutput {
    command: String,
    output: String,
    timestamp: u64,
    session_id: String,
}

fn get_cache_dir() -> Result<PathBuf, CcyError> {
    let cache_dir = cache_dir().ok_or(CcyError::NoCacheDir)?;
    let ccy_dir = cache_dir.join("ccy");
    fs::create_dir_all(&ccy_dir)?;
    Ok(ccy_dir)
}

fn get_current_session_id() -> Result<String, CcyError> {
    Ok(session::get_session_id())
}

fn find_latest_output() -> Result<CommandOutput, CcyError> {
    let cache_dir = get_cache_dir()?;
    
    // First try to find output for current session
    if let Ok(session_id) = get_current_session_id() {
        let session_file = cache_dir.join(format!("{}.json", session_id));
        if session_file.exists() {
            let content = fs::read_to_string(&session_file)?;
            if let Ok(output) = serde_json::from_str::<CommandOutput>(&content) {
                return Ok(output);
            }
        }
    }
    
    // If no current session output, find the most recent across all sessions
    let mut latest_output: Option<CommandOutput> = None;
    let mut latest_timestamp = 0u64;
    
    for entry in fs::read_dir(&cache_dir)? {
        let entry = entry?;
        let path = entry.path();
        
        if path.extension().and_then(|s| s.to_str()) == Some("json") {
            if let Ok(content) = fs::read_to_string(&path) {
                if let Ok(output) = serde_json::from_str::<CommandOutput>(&content) {
                    if output.timestamp > latest_timestamp {
                        latest_timestamp = output.timestamp;
                        latest_output = Some(output);
                    }
                }
            }
        }
    }
    
    latest_output.ok_or(CcyError::NoRecentOutput)
}

#[cfg(feature = "clipboard")]
fn check_clipboard_utilities() -> bool {
    process::Command::new("xclip").arg("--version").output().is_ok() ||
    process::Command::new("xsel").arg("--version").output().is_ok() ||
    process::Command::new("wl-copy").arg("--version").output().is_ok()
}

#[cfg(feature = "clipboard")]
fn copy_to_clipboard(text: &str) -> Result<(), CcyError> {
    // Try using system clipboard utilities directly as fallback
    // This is more reliable than the Rust clipboard crate in some environments
    
    // Try xclip first with timeout handling
    let xclip_result = process::Command::new("xclip")
        .arg("-selection")
        .arg("clipboard")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .and_then(|mut child| {
            use std::io::Write;
            if let Some(stdin) = child.stdin.as_mut() {
                stdin.write_all(text.as_bytes())?;
                let _ = child.stdin.take(); // Close stdin to signal end of input
            }
            // Don't wait for child to avoid hanging
            Ok(())
        });
    
    if xclip_result.is_ok() {
        return Ok(());
    }
    
    // Try xsel as fallback
    if let Ok(_) = process::Command::new("xsel")
        .arg("--clipboard")
        .arg("--input")
        .stdin(std::process::Stdio::piped())
        .spawn()
        .and_then(|mut child| {
            use std::io::Write;
            if let Some(stdin) = child.stdin.as_mut() {
                stdin.write_all(text.as_bytes())?;
            }
            child.wait().map(|_| ())
        }) {
        return Ok(());
    }
    
    // Try wl-copy for Wayland
    if let Ok(_) = process::Command::new("wl-copy")
        .stdin(std::process::Stdio::piped())
        .spawn()
        .and_then(|mut child| {
            use std::io::Write;
            if let Some(stdin) = child.stdin.as_mut() {
                stdin.write_all(text.as_bytes())?;
            }
            child.wait().map(|_| ())
        }) {
        return Ok(());
    }
    
    // If all direct methods fail, try the Rust clipboard crate as last resort
    use clipboard::{ClipboardContext, ClipboardProvider};
    let mut ctx: ClipboardContext = ClipboardProvider::new()
        .map_err(|e| CcyError::Clipboard(format!("Failed to create clipboard context: {}", e)))?;
    ctx.set_contents(text.to_owned())
        .map_err(|e| CcyError::Clipboard(format!("Failed to set clipboard contents: {}", e)))?;
    
    Ok(())
}

fn get_home_dir() -> String {
    use std::env;
    
    // Try SUDO_USER first if running under sudo
    if let Ok(sudo_user) = env::var("SUDO_USER") {
        if sudo_user != "root" {
            return format!("/home/{}", sudo_user);
        }
    }
    
    // Fall back to HOME env var
    env::var("HOME").unwrap_or_else(|_| "/tmp".to_string())
}

fn handle_enable() {
    use std::env;
    use std::fs::OpenOptions;
    use std::io::Write;
    
    // Detect shell - handle sudo environment
    let shell = if env::var("BASH_VERSION").is_ok() {
        ("bash", get_home_dir() + "/.bashrc")
    } else if env::var("ZSH_VERSION").is_ok() {
        ("zsh", get_home_dir() + "/.zshrc")
    } else {
        // If no shell version vars, try to detect from SHELL env var
        let shell_path = env::var("SHELL").unwrap_or_default();
        if shell_path.contains("bash") {
            ("bash", get_home_dir() + "/.bashrc")
        } else if shell_path.contains("zsh") {
            ("zsh", get_home_dir() + "/.zshrc")
        } else {
            eprintln!("Unsupported shell. CCY supports bash and zsh.");
            eprintln!("Current SHELL: {}", shell_path);
            process::exit(1);
        }
    };
    
    let (shell_name, rc_file) = shell;
    let hook_file = format!("/etc/ccy/shell-hooks/{}_hook.sh", shell_name);
    
    // Check if already enabled
    if let Ok(content) = fs::read_to_string(&rc_file) {
        if content.contains("# CCO Hook - Copy Command Output") {
            println!("CCY is already enabled for {}", shell_name);
            return;
        }
    }
    
    // Add hook to shell config
    let hook_content = format!(
        "\n# CCY Hook - Console Command Yank\nif [[ -f \"{}\" ]]; then\n    source \"{}\"\nfi\n",
        hook_file, hook_file
    );
    
    match OpenOptions::new().create(true).append(true).open(&rc_file) {
        Ok(mut file) => {
            if let Err(e) = file.write_all(hook_content.as_bytes()) {
                eprintln!("Failed to write to {}: {}", rc_file, e);
                process::exit(1);
            }
            println!("CCY enabled for {}! Restart your shell or run: source {}", shell_name, rc_file);
        }
        Err(e) => {
            eprintln!("Failed to open {}: {}", rc_file, e);
            process::exit(1);
        }
    }
}

fn handle_disable() {
    use std::env;
    
    // Detect shell - handle sudo environment
    let shell = if env::var("BASH_VERSION").is_ok() {
        ("bash", get_home_dir() + "/.bashrc")
    } else if env::var("ZSH_VERSION").is_ok() {
        ("zsh", get_home_dir() + "/.zshrc")
    } else {
        // If no shell version vars, try to detect from SHELL env var
        let shell_path = env::var("SHELL").unwrap_or_default();
        if shell_path.contains("bash") {
            ("bash", get_home_dir() + "/.bashrc")
        } else if shell_path.contains("zsh") {
            ("zsh", get_home_dir() + "/.zshrc")
        } else {
            eprintln!("Unsupported shell. CCY supports bash and zsh.");
            eprintln!("Current SHELL: {}", shell_path);
            process::exit(1);
        }
    };
    
    let (shell_name, rc_file) = shell;
    
    // Remove CCO hook from shell config
    if !std::path::Path::new(&rc_file).exists() {
        eprintln!("Shell config file not found: {}", rc_file);
        return;
    }
    
    match fs::read_to_string(&rc_file) {
        Ok(content) => {
            // Create backup
            let backup_file = format!("{}.cco-backup", rc_file);
            if let Err(e) = fs::write(&backup_file, &content) {
                eprintln!("Warning: Failed to create backup: {}", e);
            }
            
            // Remove CCO hook section
            let lines: Vec<&str> = content.lines().collect();
            let mut new_lines = Vec::new();
            let mut in_cco_section = false;
            
            for line in lines {
                if line.trim() == "# CCY Hook - Console Command Yank" {
                    in_cco_section = true;
                    continue;
                }
                if in_cco_section && line.trim().is_empty() && new_lines.last().map_or(false, |l: &&str| l.starts_with("fi")) {
                    in_cco_section = false;
                    continue;
                }
                if !in_cco_section {
                    new_lines.push(line);
                }
            }
            
            let new_content = new_lines.join("\n");
            match fs::write(&rc_file, new_content) {
                Ok(()) => {
                    println!("CCY disabled for {}! Restart your shell to apply changes.", shell_name);
                    println!("Backup saved as: {}", backup_file);
                }
                Err(e) => {
                    eprintln!("Failed to write updated config: {}", e);
                    process::exit(1);
                }
            }
        }
        Err(e) => {
            eprintln!("Failed to read {}: {}", rc_file, e);
            process::exit(1);
        }
    }
}

fn main() {
    let matches = Command::new("ccy")
        .version("0.1.0")
        .about("Console Command Yank - yanks the last terminal command output")
        .arg(
            Arg::new("print")
                .short('p')
                .long("print")
                .help("Print to stdout instead of copying to clipboard")
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("command-only")
                .short('c')
                .long("command-only")
                .help("Only show the command, not the output")
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("output-only")
                .short('o')
                .long("output-only")
                .help("Only show the output, not the command")
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("enable")
                .long("enable")
                .help("Enable CCY shell hooks in current shell")
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("disable")
                .long("disable")
                .help("Disable CCY shell hooks in current shell")
                .action(clap::ArgAction::SetTrue),
        )
        .get_matches();

    let print_mode = matches.get_flag("print");
    let command_only = matches.get_flag("command-only");
    let output_only = matches.get_flag("output-only");
    let enable_mode = matches.get_flag("enable");
    let disable_mode = matches.get_flag("disable");

    // Handle enable/disable modes
    if enable_mode {
        handle_enable();
        return;
    }
    
    if disable_mode {
        handle_disable();
        return;
    }

    match find_latest_output() {
        Ok(cmd_output) => {
            let text = if command_only {
                cmd_output.command
            } else if output_only {
                cmd_output.output
            } else {
                format!("{}\n{}", cmd_output.command, cmd_output.output)
            };

            if print_mode {
                print!("{}", text);
            } else {
                #[cfg(feature = "clipboard")]
                {
                    if !check_clipboard_utilities() {
                        eprintln!("No clipboard utility found!");
                        eprintln!("Install one of the following:");
                        eprintln!("  - xclip: sudo apt install xclip");
                        eprintln!("  - xsel: sudo apt install xsel");
                        eprintln!("  - wl-copy: sudo apt install wl-clipboard");
                        eprintln!("Output:");
                        print!("{}", text);
                        process::exit(1);
                    }
                    
                    match copy_to_clipboard(&text) {
                        Ok(()) => {
                            eprintln!("Successfully copied to clipboard");
                        }
                        Err(e) => {
                            eprintln!("Failed to copy to clipboard: {}", e);
                            eprintln!("Output:");
                            print!("{}", text);
                            process::exit(1);
                        }
                    }
                }
                #[cfg(not(feature = "clipboard"))]
                {
                    print!("{}", text);
                }
            }
        }
        Err(CcyError::NoRecentOutput) => {
            // TODO: Better error handling
            eprintln!("No recent command output found");
            process::exit(1);
        }
        Err(e) => {
            eprintln!("Error: {}", e);
            process::exit(1);
        }
    }
}