jarvish 1.0.1

Next Generation AI Integrated Shell inspired by J.A.R.V.I.S. on Marvel's Iron Man
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! シェル構文パーサー
//!
//! `shell_words::split()` で得たトークン列を、パイプライン(`|`)と
//! リダイレクト(`>`, `>>`, `<`)を含む構造化された `Pipeline` に変換する。

/// I/O リダイレクト
#[derive(Debug, Clone, PartialEq)]
pub enum Redirect {
    /// `> file` — stdout を上書き
    StdoutOverwrite(String),
    /// `>> file` — stdout に追記
    StdoutAppend(String),
    /// `< file` — stdin をファイルから読み込み
    StdinFrom(String),
}

/// パイプラインの 1 セグメント(単一コマンド)
#[derive(Debug, Clone, PartialEq)]
pub struct SimpleCommand {
    /// コマンド名(例: "git")
    pub cmd: String,
    /// コマンド引数(例: ["log", "--oneline"])
    pub args: Vec<String>,
    /// このコマンドに付与されたリダイレクト
    pub redirects: Vec<Redirect>,
}

/// パイプ(`|`)で接続された一連のコマンド
#[derive(Debug, Clone, PartialEq)]
pub struct Pipeline {
    pub commands: Vec<SimpleCommand>,
}

/// コマンドリストの接続演算子
#[derive(Debug, Clone, PartialEq)]
pub enum Connector {
    /// `&&` — 前のコマンドが成功 (exit_code == 0) した場合のみ次を実行
    And,
    /// `||` — 前のコマンドが失敗 (exit_code != 0) した場合のみ次を実行
    Or,
    /// `;` — 前のコマンドの結果に関わらず次を実行
    Semi,
}

/// `&&`, `||`, `;` で接続された一連のパイプライン
#[derive(Debug, Clone, PartialEq)]
pub struct CommandList {
    /// 先頭のパイプライン
    pub first: Pipeline,
    /// (接続演算子, パイプライン) のペアのリスト
    pub rest: Vec<(Connector, Pipeline)>,
}

/// パースエラー
#[derive(Debug, Clone, PartialEq)]
pub struct ParseError(pub String);

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// トークン列をコマンドリストにパースする。
///
/// `shell_words::split()` で分割済みのトークンを受け取り、
/// `&&`, `||`, `;` で分割した後、各セグメントを `parse_pipeline()` でパースする。
pub fn parse_command_list(tokens: Vec<String>) -> Result<CommandList, ParseError> {
    if tokens.is_empty() {
        return Err(ParseError("empty command".to_string()));
    }

    let (segments, connectors) = split_by_connector(&tokens)?;

    let first = parse_pipeline(segments[0].clone())?;
    let mut rest = Vec::new();
    for (i, conn) in connectors.into_iter().enumerate() {
        let pipeline = parse_pipeline(segments[i + 1].clone())?;
        rest.push((conn, pipeline));
    }

    Ok(CommandList { first, rest })
}

/// トークン列を `&&`, `||`, `;` で分割する。
///
/// 戻り値: (セグメント群, 接続演算子群)
/// segments.len() == connectors.len() + 1 が常に成立する。
fn split_by_connector(tokens: &[String]) -> Result<(Vec<Vec<String>>, Vec<Connector>), ParseError> {
    let mut segments: Vec<Vec<String>> = Vec::new();
    let mut connectors: Vec<Connector> = Vec::new();
    let mut current: Vec<String> = Vec::new();

    for token in tokens {
        match token.as_str() {
            "&&" => {
                if current.is_empty() {
                    return Err(ParseError(
                        "syntax error: unexpected token '&&'".to_string(),
                    ));
                }
                segments.push(std::mem::take(&mut current));
                connectors.push(Connector::And);
            }
            "||" => {
                if current.is_empty() {
                    return Err(ParseError(
                        "syntax error: unexpected token '||'".to_string(),
                    ));
                }
                segments.push(std::mem::take(&mut current));
                connectors.push(Connector::Or);
            }
            ";" => {
                if current.is_empty() {
                    return Err(ParseError("syntax error: unexpected token ';'".to_string()));
                }
                segments.push(std::mem::take(&mut current));
                connectors.push(Connector::Semi);
            }
            _ => {
                current.push(token.clone());
            }
        }
    }

    // 最後のセグメント
    if current.is_empty() && !connectors.is_empty() {
        return Err(ParseError(
            "syntax error: unexpected end of command after connector".to_string(),
        ));
    }
    if !current.is_empty() {
        segments.push(current);
    }

    Ok((segments, connectors))
}

/// トークン列をパイプラインにパースする。
///
/// `shell_words::split()` で分割済みのトークンを受け取り、
/// `|` でパイプライン分割し、各セグメントからリダイレクト演算子を抽出する。
pub fn parse_pipeline(tokens: Vec<String>) -> Result<Pipeline, ParseError> {
    if tokens.is_empty() {
        return Err(ParseError("empty command".to_string()));
    }

    // トークン列を "|" で分割
    let segments = split_by_pipe(&tokens)?;

    let mut commands = Vec::new();
    for segment in segments {
        let cmd = parse_simple_command(segment)?;
        commands.push(cmd);
    }

    Ok(Pipeline { commands })
}

/// トークン列を `|` で分割し、各セグメントを返す。
fn split_by_pipe(tokens: &[String]) -> Result<Vec<&[String]>, ParseError> {
    let mut segments: Vec<&[String]> = Vec::new();
    let mut start = 0;

    for (i, token) in tokens.iter().enumerate() {
        if token == "|" {
            if i == start {
                return Err(ParseError("syntax error: unexpected token '|'".to_string()));
            }
            segments.push(&tokens[start..i]);
            start = i + 1;
        }
    }

    // 最後のセグメント
    if start >= tokens.len() {
        return Err(ParseError(
            "syntax error: unexpected end of command after '|'".to_string(),
        ));
    }
    segments.push(&tokens[start..]);

    Ok(segments)
}

/// トークンのスライスからリダイレクトを抽出し、SimpleCommand を構築する。
fn parse_simple_command(tokens: &[String]) -> Result<SimpleCommand, ParseError> {
    let mut args: Vec<String> = Vec::new();
    let mut redirects: Vec<Redirect> = Vec::new();
    let mut iter = tokens.iter().peekable();

    while let Some(token) = iter.next() {
        match token.as_str() {
            ">>" => {
                let target = iter.next().ok_or_else(|| {
                    ParseError("syntax error: expected filename after '>>'".to_string())
                })?;
                redirects.push(Redirect::StdoutAppend(target.clone()));
            }
            ">" => {
                let target = iter.next().ok_or_else(|| {
                    ParseError("syntax error: expected filename after '>'".to_string())
                })?;
                redirects.push(Redirect::StdoutOverwrite(target.clone()));
            }
            "<" => {
                let target = iter.next().ok_or_else(|| {
                    ParseError("syntax error: expected filename after '<'".to_string())
                })?;
                redirects.push(Redirect::StdinFrom(target.clone()));
            }
            _ => {
                args.push(token.clone());
            }
        }
    }

    if args.is_empty() {
        return Err(ParseError("syntax error: missing command".to_string()));
    }

    let cmd = args.remove(0);
    Ok(SimpleCommand {
        cmd,
        args,
        redirects,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── parse_pipeline: 基本 ──

    #[test]
    fn single_command_no_args() {
        let tokens = vec!["ls".into()];
        let pipeline = parse_pipeline(tokens).unwrap();
        assert_eq!(pipeline.commands.len(), 1);
        assert_eq!(pipeline.commands[0].cmd, "ls");
        assert!(pipeline.commands[0].args.is_empty());
        assert!(pipeline.commands[0].redirects.is_empty());
    }

    #[test]
    fn single_command_with_args() {
        let tokens = vec!["git".into(), "log".into(), "--oneline".into()];
        let pipeline = parse_pipeline(tokens).unwrap();
        assert_eq!(pipeline.commands.len(), 1);
        assert_eq!(pipeline.commands[0].cmd, "git");
        assert_eq!(pipeline.commands[0].args, vec!["log", "--oneline"]);
    }

    // ── parse_pipeline: パイプ ──

    #[test]
    fn two_commands_piped() {
        let tokens = vec!["git".into(), "log".into(), "|".into(), "head".into()];
        let pipeline = parse_pipeline(tokens).unwrap();
        assert_eq!(pipeline.commands.len(), 2);
        assert_eq!(pipeline.commands[0].cmd, "git");
        assert_eq!(pipeline.commands[0].args, vec!["log"]);
        assert_eq!(pipeline.commands[1].cmd, "head");
        assert!(pipeline.commands[1].args.is_empty());
    }

    #[test]
    fn three_commands_piped() {
        let tokens = vec![
            "cat".into(),
            "file.txt".into(),
            "|".into(),
            "grep".into(),
            "error".into(),
            "|".into(),
            "wc".into(),
            "-l".into(),
        ];
        let pipeline = parse_pipeline(tokens).unwrap();
        assert_eq!(pipeline.commands.len(), 3);
        assert_eq!(pipeline.commands[0].cmd, "cat");
        assert_eq!(pipeline.commands[1].cmd, "grep");
        assert_eq!(pipeline.commands[1].args, vec!["error"]);
        assert_eq!(pipeline.commands[2].cmd, "wc");
        assert_eq!(pipeline.commands[2].args, vec!["-l"]);
    }

    // ── parse_pipeline: リダイレクト ──

    #[test]
    fn stdout_overwrite_redirect() {
        let tokens = vec!["echo".into(), "hello".into(), ">".into(), "out.txt".into()];
        let pipeline = parse_pipeline(tokens).unwrap();
        assert_eq!(pipeline.commands.len(), 1);
        assert_eq!(pipeline.commands[0].cmd, "echo");
        assert_eq!(pipeline.commands[0].args, vec!["hello"]);
        assert_eq!(
            pipeline.commands[0].redirects,
            vec![Redirect::StdoutOverwrite("out.txt".into())]
        );
    }

    #[test]
    fn stdout_append_redirect() {
        let tokens = vec!["echo".into(), "hello".into(), ">>".into(), "out.txt".into()];
        let pipeline = parse_pipeline(tokens).unwrap();
        assert_eq!(
            pipeline.commands[0].redirects,
            vec![Redirect::StdoutAppend("out.txt".into())]
        );
    }

    #[test]
    fn stdin_redirect() {
        let tokens = vec!["cat".into(), "<".into(), "input.txt".into()];
        let pipeline = parse_pipeline(tokens).unwrap();
        assert_eq!(
            pipeline.commands[0].redirects,
            vec![Redirect::StdinFrom("input.txt".into())]
        );
    }

    #[test]
    fn pipe_with_redirect() {
        // echo hello | cat > out.txt
        let tokens = vec![
            "echo".into(),
            "hello".into(),
            "|".into(),
            "cat".into(),
            ">".into(),
            "out.txt".into(),
        ];
        let pipeline = parse_pipeline(tokens).unwrap();
        assert_eq!(pipeline.commands.len(), 2);
        assert!(pipeline.commands[0].redirects.is_empty());
        assert_eq!(
            pipeline.commands[1].redirects,
            vec![Redirect::StdoutOverwrite("out.txt".into())]
        );
    }

    // ── parse_pipeline: エラーケース ──

    #[test]
    fn empty_tokens_returns_error() {
        let result = parse_pipeline(vec![]);
        assert!(result.is_err());
    }

    #[test]
    fn leading_pipe_returns_error() {
        let tokens = vec!["|".into(), "head".into()];
        let result = parse_pipeline(tokens);
        assert!(result.is_err());
    }

    #[test]
    fn trailing_pipe_returns_error() {
        let tokens = vec!["ls".into(), "|".into()];
        let result = parse_pipeline(tokens);
        assert!(result.is_err());
    }

    #[test]
    fn redirect_without_target_returns_error() {
        let tokens = vec!["echo".into(), "hello".into(), ">".into()];
        let result = parse_pipeline(tokens);
        assert!(result.is_err());
    }

    #[test]
    fn append_redirect_without_target_returns_error() {
        let tokens = vec!["echo".into(), "hello".into(), ">>".into()];
        let result = parse_pipeline(tokens);
        assert!(result.is_err());
    }

    // ── parse_command_list: && ──

    #[test]
    fn command_list_and_two_commands() {
        let tokens = vec![
            "make".into(),
            "build".into(),
            "&&".into(),
            "echo".into(),
            "done".into(),
        ];
        let list = parse_command_list(tokens).unwrap();
        assert_eq!(list.first.commands[0].cmd, "make");
        assert_eq!(list.first.commands[0].args, vec!["build"]);
        assert_eq!(list.rest.len(), 1);
        assert_eq!(list.rest[0].0, Connector::And);
        assert_eq!(list.rest[0].1.commands[0].cmd, "echo");
        assert_eq!(list.rest[0].1.commands[0].args, vec!["done"]);
    }

    #[test]
    fn command_list_and_three_commands() {
        let tokens = vec![
            "cmd1".into(),
            "&&".into(),
            "cmd2".into(),
            "&&".into(),
            "cmd3".into(),
        ];
        let list = parse_command_list(tokens).unwrap();
        assert_eq!(list.first.commands[0].cmd, "cmd1");
        assert_eq!(list.rest.len(), 2);
        assert_eq!(list.rest[0].0, Connector::And);
        assert_eq!(list.rest[0].1.commands[0].cmd, "cmd2");
        assert_eq!(list.rest[1].0, Connector::And);
        assert_eq!(list.rest[1].1.commands[0].cmd, "cmd3");
    }

    // ── parse_command_list: || ──

    #[test]
    fn command_list_or() {
        let tokens = vec![
            "false".into(),
            "||".into(),
            "echo".into(),
            "fallback".into(),
        ];
        let list = parse_command_list(tokens).unwrap();
        assert_eq!(list.first.commands[0].cmd, "false");
        assert_eq!(list.rest.len(), 1);
        assert_eq!(list.rest[0].0, Connector::Or);
        assert_eq!(list.rest[0].1.commands[0].cmd, "echo");
    }

    // ── parse_command_list: ; ──

    #[test]
    fn command_list_semi() {
        let tokens = vec![
            "echo".into(),
            "a".into(),
            ";".into(),
            "echo".into(),
            "b".into(),
        ];
        let list = parse_command_list(tokens).unwrap();
        assert_eq!(list.first.commands[0].cmd, "echo");
        assert_eq!(list.rest.len(), 1);
        assert_eq!(list.rest[0].0, Connector::Semi);
        assert_eq!(list.rest[0].1.commands[0].cmd, "echo");
    }

    // ── parse_command_list: 混合 ──

    #[test]
    fn command_list_mixed_connectors() {
        let tokens = vec![
            "cmd1".into(),
            "&&".into(),
            "cmd2".into(),
            "||".into(),
            "cmd3".into(),
            ";".into(),
            "cmd4".into(),
        ];
        let list = parse_command_list(tokens).unwrap();
        assert_eq!(list.first.commands[0].cmd, "cmd1");
        assert_eq!(list.rest.len(), 3);
        assert_eq!(list.rest[0].0, Connector::And);
        assert_eq!(list.rest[1].0, Connector::Or);
        assert_eq!(list.rest[2].0, Connector::Semi);
    }

    // ── parse_command_list: パイプとの組み合わせ ──

    #[test]
    fn command_list_with_pipe() {
        // echo hello | cat && echo done
        let tokens = vec![
            "echo".into(),
            "hello".into(),
            "|".into(),
            "cat".into(),
            "&&".into(),
            "echo".into(),
            "done".into(),
        ];
        let list = parse_command_list(tokens).unwrap();
        assert_eq!(list.first.commands.len(), 2); // echo hello | cat
        assert_eq!(list.rest.len(), 1);
        assert_eq!(list.rest[0].0, Connector::And);
        assert_eq!(list.rest[0].1.commands[0].cmd, "echo");
    }

    // ── parse_command_list: 単一コマンド (接続演算子なし) ──

    #[test]
    fn command_list_single_command() {
        let tokens = vec!["ls".into(), "-la".into()];
        let list = parse_command_list(tokens).unwrap();
        assert_eq!(list.first.commands[0].cmd, "ls");
        assert!(list.rest.is_empty());
    }

    // ── parse_command_list: エラーケース ──

    #[test]
    fn command_list_leading_and_returns_error() {
        let tokens = vec!["&&".into(), "echo".into()];
        let result = parse_command_list(tokens);
        assert!(result.is_err());
    }

    #[test]
    fn command_list_trailing_and_returns_error() {
        let tokens = vec!["echo".into(), "&&".into()];
        let result = parse_command_list(tokens);
        assert!(result.is_err());
    }

    #[test]
    fn command_list_leading_or_returns_error() {
        let tokens = vec!["||".into(), "echo".into()];
        let result = parse_command_list(tokens);
        assert!(result.is_err());
    }

    #[test]
    fn command_list_trailing_semi_is_ok() {
        // `echo hello ;` — 末尾のセミコロン後にコマンドがなくても許容
        // (実際のシェルでは `echo hello ;` は有効)
        // ただし現在の実装ではエラーになる — これはシンプルさのため
        let tokens = vec!["echo".into(), "hello".into(), ";".into()];
        let result = parse_command_list(tokens);
        assert!(result.is_err());
    }

    #[test]
    fn command_list_empty_returns_error() {
        let result = parse_command_list(vec![]);
        assert!(result.is_err());
    }
}