File size: 9,917 Bytes
94193b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { describe, it, expect, vi, beforeEach } from 'vitest';

let writtenContent = '';

const mockVfs = {
  init: vi.fn(),
  readFile: vi.fn(),
  writeFile: vi.fn(),
  createFile: vi.fn(),
  updateFile: vi.fn().mockImplementation((_pid: string, _path: string, content: string) => {
    writtenContent = content;
  }),
  listFiles: vi.fn().mockResolvedValue([]),
  listDirectories: vi.fn().mockResolvedValue([]),
  deleteFile: vi.fn(),
  renameFile: vi.fn(),
  getFileTree: vi.fn().mockResolvedValue([]),
  getAllFilesAndDirectories: vi.fn().mockResolvedValue([]),
};

vi.mock('@/lib/vfs', () => ({
  getActiveVFS: () => mockVfs,
  vfs: mockVfs,
}));

vi.mock('@/lib/utils', () => ({
  logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
}));

async function exec(cmd: string[], stdin?: string) {
  const { vfsShell } = await import('../cli-shell');
  return vfsShell.execute('test', cmd, stdin);
}

beforeEach(() => {
  vi.clearAllMocks();
  writtenContent = '';
});

// ---------- grep -o ----------

describe('grep -o (only matching)', () => {
  it('outputs only the matched portion from stdin', async () => {
    const result = await exec(
      ['grep', '-o', 'href="[^"]*"'],
      '<a href="page1.html">Link</a>\n<a href="page2.html">Other</a>'
    );
    expect(result.success).toBe(true);
    expect(result.stdout).toBe('href="page1.html"\nhref="page2.html"');
  });

  it('outputs multiple matches per line separately', async () => {
    const result = await exec(
      ['grep', '-o', '\\d+'],
      'abc 123 def 456 ghi'
    );
    expect(result.success).toBe(true);
    expect(result.stdout).toBe('123\n456');
  });

  it('combines -o with -n to show line numbers', async () => {
    const result = await exec(
      ['grep', '-on', '\\d+'],
      'no numbers\nabc 42 def\nxyz'
    );
    expect(result.success).toBe(true);
    expect(result.stdout).toBe('2:42');
  });

  it('outputs matched portions from files', async () => {
    mockVfs.getAllFilesAndDirectories.mockResolvedValueOnce([
      { path: '/test.html', content: '<img src="a.png"> and <img src="b.jpg">' },
    ]);
    const result = await exec(['grep', '-o', 'src="[^"]*"', '/test.html']);
    expect(result.success).toBe(true);
    expect(result.stdout).toBe('/test.html:src="a.png"\n/test.html:src="b.jpg"');
  });

  it('returns empty output when -o finds no matches', async () => {
    const result = await exec(['grep', '-o', 'zzz'], 'abc def');
    expect(result.success).toBe(true);
    expect(result.stdout).toBe('');
  });
});

// ---------- grep -P (no-op PCRE) ----------

describe('grep -P (PCRE no-op)', () => {
  it('accepts -P without error', async () => {
    const result = await exec(['grep', '-P', '\\d+'], 'abc 123\ndef');
    expect(result.success).toBe(true);
    expect(result.stdout).toBe('abc 123');
  });
});

// ---------- sed ! negate ----------

describe('sed ! negate modifier', () => {
  it('single-address !d deletes lines NOT matching pattern', async () => {
    const result = await exec(
      ['sed', '/keep/!d'],
      'drop this\nkeep this\ndrop that\nkeep that'
    );
    expect(result.success).toBe(true);
    expect(result.stdout).toBe('keep this\nkeep that');
  });

  it('single-address !p with -n prints non-matching lines', async () => {
    const result = await exec(
      ['sed', '-n', '/skip/!p'],
      'show\nskip\nshow too'
    );
    expect(result.success).toBe(true);
    expect(result.stdout).toBe('show\nshow too');
  });

  it('range !d deletes lines OUTSIDE the range', async () => {
    const result = await exec(
      ['sed', '2,4!d'],
      'line1\nline2\nline3\nline4\nline5'
    );
    expect(result.success).toBe(true);
    expect(result.stdout).toBe('line2\nline3\nline4');
  });
});

// ---------- sed {...} grouping ----------

describe('sed {...} command grouping', () => {
  it('applies sub-command within a range', async () => {
    const input = [
      '<section>',
      '  <p>content</p>',
      '  <p>more</p>',
      '</section>',
      'after',
    ].join('\n');

    const result = await exec(
      ['sed', '/<section>/,/<\\/section>/{/<\\/section>/!d}'],
      input
    );
    expect(result.success).toBe(true);
    // Inside range: lines NOT matching </section> are deleted → only </section> survives
    // Outside range: 'after' is kept
    expect(result.stdout).toBe('</section>\nafter');
  });

  it('group with substitution inside a range', async () => {
    const input = 'AAA\nstart\nBBB\nend\nCCC';
    const result = await exec(
      ['sed', '/start/,/end/{s/BBB/XXX/}'],
      input
    );
    expect(result.success).toBe(true);
    expect(result.stdout).toBe('AAA\nstart\nXXX\nend\nCCC');
  });

  it('single-address group applies to matching line', async () => {
    const result = await exec(
      ['sed', '/target/{s/old/new/}'],
      'target old\nother old'
    );
    expect(result.success).toBe(true);
    expect(result.stdout).toBe('target new\nother old');
  });
});

// ---------- sed substitution feedback ----------

describe('sed substitution feedback', () => {
  it('reports substitution count on -i success', async () => {
    mockVfs.readFile.mockResolvedValueOnce({ content: 'hello world\nhello there' });
    const result = await exec(['sed', '-i', 's/hello/hi/g', '/test.txt']);
    expect(result.success).toBe(true);
    expect(result.stdout).toContain('2 substitutions');
  });

  it('reports zero substitutions when pattern does not match', async () => {
    mockVfs.readFile.mockResolvedValueOnce({ content: 'no match here' });
    const result = await exec(['sed', '-i', 's/zzz/yyy/', '/test.txt']);
    expect(result.success).toBe(true);
    expect(result.stdout).toContain('0 substitutions');
    expect(result.stdout).toContain('did not match');
    // Should not write the file when nothing changed
    expect(mockVfs.updateFile).not.toHaveBeenCalled();
  });

});

// ---------- sed combined negate + group + in-place ----------

describe('sed negate + group integration', () => {
  it('real-world pattern: delete section content keeping closing tag', async () => {
    mockVfs.readFile.mockResolvedValueOnce({
      content: [
        '<html>',
        '<section id="hero">',
        '  <h1>Old Title</h1>',
        '  <p>Old text</p>',
        '</section>',
        '<footer>Keep</footer>',
      ].join('\n'),
    });

    const result = await exec([
      'sed', '-i',
      '/<section id="hero">/,/<\\/section>/{/<\\/section>/!d}',
      '/index.html',
    ]);

    expect(result.success).toBe(true);
    expect(writtenContent).toBe(
      '<html>\n</section>\n<footer>Keep</footer>'
    );
  });
});

// ---------- sed backreferences ----------

describe('sed backreferences', () => {
  it('translates \\1 \\2 to $1 $2 in replacement', async () => {
    mockVfs.readFile.mockResolvedValue({ content: 'hello world' });
    const result = await exec([
      'sed', '-i', 's/\\(hello\\) \\(world\\)/\\2 \\1/', '/test.txt'
    ]);
    expect(result.success).toBe(true);
    expect(writtenContent).toBe('world hello');
  });

  it('translates & to $& (whole match) in replacement', async () => {
    mockVfs.readFile.mockResolvedValue({ content: 'foo bar' });
    const result = await exec([
      'sed', '-i', 's/foo/[&]/', '/test.txt'
    ]);
    expect(result.success).toBe(true);
    expect(writtenContent).toBe('[foo] bar');
  });

  it('preserves literal \\& (escaped ampersand)', async () => {
    mockVfs.readFile.mockResolvedValue({ content: 'foo bar' });
    const result = await exec([
      'sed', '-i', 's/foo/a\\&b/', '/test.txt'
    ]);
    expect(result.success).toBe(true);
    expect(writtenContent).toBe('a&b bar');
  });
});

// ---------- sed error messages ----------

describe('sed multiline error message', () => {
  it('suggests ======= separator (not ===) when rejecting \\n patterns', async () => {
    mockVfs.readFile.mockResolvedValue({ content: 'test' });
    const result = await exec([
      'sed', '-i', 's/line1\\nline2/replaced/', '/test.txt'
    ]);
    expect(result.success).toBe(false);
    expect(result.stderr).toContain('=======');
    expect(result.stderr).not.toMatch(/[^=]===[^=]/);
  });
});

// ---------- ss separator and entity mode ----------

describe('ss separator format', () => {
  it('splits on ======= (7 equals)', async () => {
    mockVfs.readFile.mockResolvedValue({ content: 'old text here' });
    const stdin = 'old text\n=======\nnew text';
    const result = await exec(['ss', '/test.txt'], stdin);
    expect(result.success).toBe(true);
    expect(writtenContent).toBe('new text here');
  });

  it('rejects === (3 equals) as separator', async () => {
    mockVfs.readFile.mockResolvedValue({ content: 'old text here' });
    const stdin = 'old text\n===\nnew text';
    const result = await exec(['ss', '/test.txt'], stdin);
    expect(result.success).toBe(false);
  });

  it('handles JS code with === in content without collision', async () => {
    const fileContent = 'if (x === 5) { return true; }';
    mockVfs.readFile.mockResolvedValue({ content: fileContent });
    const stdin = 'if (x === 5) { return true; }\n=======\nif (x === 10) { return false; }';
    const result = await exec(['ss', '/test.txt'], stdin);
    expect(result.success).toBe(true);
    expect(writtenContent).toBe('if (x === 10) { return false; }');
  });
});

describe('ss --entity without separator', () => {
  it('auto-extracts selector from first line when no separator given', async () => {
    const fileContent = 'function foo() {\n  return 1;\n}\n\nfunction bar() {\n  return 2;\n}';
    mockVfs.readFile.mockResolvedValue({ content: fileContent });
    const stdin = 'function foo() {\n  return 42;\n}';
    const result = await exec(['ss', '--entity', '/test.txt'], stdin);
    expect(result.success).toBe(true);
    expect(writtenContent).toContain('return 42');
    expect(writtenContent).toContain('function bar');
  });
});