forked from Aider-AI/aider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_commands.py
1753 lines (1368 loc) · 67 KB
/
test_commands.py
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import codecs
import os
import re
import shutil
import sys
import tempfile
from io import StringIO
from pathlib import Path
from unittest import TestCase, mock
import git
import pyperclip
from aider.coders import Coder
from aider.commands import Commands, SwitchCoder
from aider.dump import dump # noqa: F401
from aider.io import InputOutput
from aider.models import Model
from aider.repo import GitRepo
from aider.utils import ChdirTemporaryDirectory, GitTemporaryDirectory, make_repo
class TestCommands(TestCase):
def setUp(self):
self.original_cwd = os.getcwd()
self.tempdir = tempfile.mkdtemp()
os.chdir(self.tempdir)
self.GPT35 = Model("gpt-3.5-turbo")
def tearDown(self):
os.chdir(self.original_cwd)
shutil.rmtree(self.tempdir, ignore_errors=True)
def test_cmd_add(self):
# Initialize the Commands and InputOutput objects
io = InputOutput(pretty=False, fancy_input=False, yes=True)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Call the cmd_add method with 'foo.txt' and 'bar.txt' as a single string
commands.cmd_add("foo.txt bar.txt")
# Check if both files have been created in the temporary directory
self.assertTrue(os.path.exists("foo.txt"))
self.assertTrue(os.path.exists("bar.txt"))
def test_cmd_copy(self):
# Initialize InputOutput and Coder instances
io = InputOutput(pretty=False, fancy_input=False, yes=True)
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Add some assistant messages to the chat history
coder.done_messages = [
{"role": "assistant", "content": "First assistant message"},
{"role": "user", "content": "User message"},
{"role": "assistant", "content": "Second assistant message"},
]
# Mock pyperclip.copy and io.tool_output
with (
mock.patch("pyperclip.copy") as mock_copy,
mock.patch.object(io, "tool_output") as mock_tool_output,
):
# Invoke the /copy command
commands.cmd_copy("")
# Assert pyperclip.copy was called with the last assistant message
mock_copy.assert_called_once_with("Second assistant message")
# Assert that tool_output was called with the expected preview
expected_preview = (
"Copied last assistant message to clipboard. Preview: Second assistant message"
)
mock_tool_output.assert_any_call(expected_preview)
def test_cmd_copy_with_cur_messages(self):
# Initialize InputOutput and Coder instances
io = InputOutput(pretty=False, fancy_input=False, yes=True)
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Add messages to done_messages and cur_messages
coder.done_messages = [
{"role": "assistant", "content": "First assistant message in done_messages"},
{"role": "user", "content": "User message in done_messages"},
]
coder.cur_messages = [
{"role": "assistant", "content": "Latest assistant message in cur_messages"},
]
# Mock pyperclip.copy and io.tool_output
with (
mock.patch("pyperclip.copy") as mock_copy,
mock.patch.object(io, "tool_output") as mock_tool_output,
):
# Invoke the /copy command
commands.cmd_copy("")
# Assert pyperclip.copy was called with the last assistant message in cur_messages
mock_copy.assert_called_once_with("Latest assistant message in cur_messages")
# Assert that tool_output was called with the expected preview
expected_preview = (
"Copied last assistant message to clipboard. Preview: Latest assistant message in"
" cur_messages"
)
mock_tool_output.assert_any_call(expected_preview)
io = InputOutput(pretty=False, fancy_input=False, yes=True)
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Add only user messages
coder.done_messages = [
{"role": "user", "content": "User message"},
]
# Mock io.tool_error
with mock.patch.object(io, "tool_error") as mock_tool_error:
commands.cmd_copy("")
# Assert tool_error was called indicating no assistant messages
mock_tool_error.assert_called_once_with("No assistant messages found to copy.")
def test_cmd_copy_pyperclip_exception(self):
io = InputOutput(pretty=False, fancy_input=False, yes=True)
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
coder.done_messages = [
{"role": "assistant", "content": "Assistant message"},
]
# Mock pyperclip.copy to raise an exception
with (
mock.patch(
"pyperclip.copy", side_effect=pyperclip.PyperclipException("Clipboard error")
),
mock.patch.object(io, "tool_error") as mock_tool_error,
):
commands.cmd_copy("")
# Assert that tool_error was called with the clipboard error message
mock_tool_error.assert_called_once_with("Failed to copy to clipboard: Clipboard error")
def test_cmd_add_bad_glob(self):
# https://github.com/Aider-AI/aider/issues/293
io = InputOutput(pretty=False, fancy_input=False, yes=False)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
commands.cmd_add("**.txt")
def test_cmd_add_with_glob_patterns(self):
# Initialize the Commands and InputOutput objects
io = InputOutput(pretty=False, fancy_input=False, yes=True)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Create some test files
with open("test1.py", "w") as f:
f.write("print('test1')")
with open("test2.py", "w") as f:
f.write("print('test2')")
with open("test.txt", "w") as f:
f.write("test")
# Call the cmd_add method with a glob pattern
commands.cmd_add("*.py")
# Check if the Python files have been added to the chat session
self.assertIn(str(Path("test1.py").resolve()), coder.abs_fnames)
self.assertIn(str(Path("test2.py").resolve()), coder.abs_fnames)
# Check if the text file has not been added to the chat session
self.assertNotIn(str(Path("test.txt").resolve()), coder.abs_fnames)
def test_cmd_add_no_match(self):
# yes=False means we will *not* create the file when it is not found
io = InputOutput(pretty=False, fancy_input=False, yes=False)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Call the cmd_add method with a non-existent file pattern
commands.cmd_add("*.nonexistent")
# Check if no files have been added to the chat session
self.assertEqual(len(coder.abs_fnames), 0)
def test_cmd_add_no_match_but_make_it(self):
# yes=True means we *will* create the file when it is not found
io = InputOutput(pretty=False, fancy_input=False, yes=True)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
fname = Path("[abc].nonexistent")
# Call the cmd_add method with a non-existent file pattern
commands.cmd_add(str(fname))
# Check if no files have been added to the chat session
self.assertEqual(len(coder.abs_fnames), 1)
self.assertTrue(fname.exists())
def test_cmd_add_drop_directory(self):
# Initialize the Commands and InputOutput objects
io = InputOutput(pretty=False, fancy_input=False, yes=False)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Create a directory and add files to it using pathlib
Path("test_dir").mkdir()
Path("test_dir/another_dir").mkdir()
Path("test_dir/test_file1.txt").write_text("Test file 1")
Path("test_dir/test_file2.txt").write_text("Test file 2")
Path("test_dir/another_dir/test_file.txt").write_text("Test file 3")
# Call the cmd_add method with a directory
commands.cmd_add("test_dir test_dir/test_file2.txt")
# Check if the files have been added to the chat session
self.assertIn(str(Path("test_dir/test_file1.txt").resolve()), coder.abs_fnames)
self.assertIn(str(Path("test_dir/test_file2.txt").resolve()), coder.abs_fnames)
self.assertIn(str(Path("test_dir/another_dir/test_file.txt").resolve()), coder.abs_fnames)
commands.cmd_drop(str(Path("test_dir/another_dir")))
self.assertIn(str(Path("test_dir/test_file1.txt").resolve()), coder.abs_fnames)
self.assertIn(str(Path("test_dir/test_file2.txt").resolve()), coder.abs_fnames)
self.assertNotIn(
str(Path("test_dir/another_dir/test_file.txt").resolve()), coder.abs_fnames
)
# Issue #139 /add problems when cwd != git_root
# remember the proper abs path to this file
abs_fname = str(Path("test_dir/another_dir/test_file.txt").resolve())
# chdir to someplace other than git_root
Path("side_dir").mkdir()
os.chdir("side_dir")
# add it via it's git_root referenced name
commands.cmd_add("test_dir/another_dir/test_file.txt")
# it should be there, but was not in v0.10.0
self.assertIn(abs_fname, coder.abs_fnames)
# drop it via it's git_root referenced name
commands.cmd_drop("test_dir/another_dir/test_file.txt")
# it should be there, but was not in v0.10.0
self.assertNotIn(abs_fname, coder.abs_fnames)
def test_cmd_drop_with_glob_patterns(self):
# Initialize the Commands and InputOutput objects
io = InputOutput(pretty=False, fancy_input=False, yes=True)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Create test files in root and subdirectory
subdir = Path("subdir")
subdir.mkdir()
(subdir / "subtest1.py").touch()
(subdir / "subtest2.py").touch()
Path("test1.py").touch()
Path("test2.py").touch()
Path("test3.txt").touch()
# Add all Python files to the chat session
commands.cmd_add("*.py")
initial_count = len(coder.abs_fnames)
self.assertEqual(initial_count, 2) # Only root .py files should be added
# Test dropping with glob pattern
commands.cmd_drop("*2.py")
self.assertIn(str(Path("test1.py").resolve()), coder.abs_fnames)
self.assertNotIn(str(Path("test2.py").resolve()), coder.abs_fnames)
self.assertEqual(len(coder.abs_fnames), initial_count - 1)
def test_cmd_drop_without_glob(self):
# Initialize the Commands and InputOutput objects
io = InputOutput(pretty=False, fancy_input=False, yes=True)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Create test files
test_files = ["file1.txt", "file2.txt", "file3.py"]
for fname in test_files:
Path(fname).touch()
# Add all files to the chat session
for fname in test_files:
commands.cmd_add(fname)
initial_count = len(coder.abs_fnames)
self.assertEqual(initial_count, 3)
# Test dropping individual files without glob
commands.cmd_drop("file1.txt")
self.assertNotIn(str(Path("file1.txt").resolve()), coder.abs_fnames)
self.assertIn(str(Path("file2.txt").resolve()), coder.abs_fnames)
self.assertEqual(len(coder.abs_fnames), initial_count - 1)
# Test dropping multiple files without glob
commands.cmd_drop("file2.txt file3.py")
self.assertNotIn(str(Path("file2.txt").resolve()), coder.abs_fnames)
self.assertNotIn(str(Path("file3.py").resolve()), coder.abs_fnames)
self.assertEqual(len(coder.abs_fnames), 0)
def test_cmd_add_bad_encoding(self):
# Initialize the Commands and InputOutput objects
io = InputOutput(pretty=False, fancy_input=False, yes=True)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Create a new file foo.bad which will fail to decode as utf-8
with codecs.open("foo.bad", "w", encoding="iso-8859-15") as f:
f.write("ÆØÅ") # Characters not present in utf-8
commands.cmd_add("foo.bad")
self.assertEqual(coder.abs_fnames, set())
def test_cmd_git(self):
# Initialize the Commands and InputOutput objects
io = InputOutput(pretty=False, fancy_input=False, yes=True)
with GitTemporaryDirectory() as tempdir:
# Create a file in the temporary directory
with open(f"{tempdir}/test.txt", "w") as f:
f.write("test")
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Run the cmd_git method with the arguments "commit -a -m msg"
commands.cmd_git("add test.txt")
commands.cmd_git("commit -a -m msg")
# Check if the file has been committed to the repository
repo = git.Repo(tempdir)
files_in_repo = repo.git.ls_files()
self.assertIn("test.txt", files_in_repo)
def test_cmd_tokens(self):
# Initialize the Commands and InputOutput objects
io = InputOutput(pretty=False, fancy_input=False, yes=True)
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
commands.cmd_add("foo.txt bar.txt")
# Redirect the standard output to an instance of io.StringIO
stdout = StringIO()
sys.stdout = stdout
commands.cmd_tokens("")
# Reset the standard output
sys.stdout = sys.__stdout__
# Get the console output
console_output = stdout.getvalue()
self.assertIn("foo.txt", console_output)
self.assertIn("bar.txt", console_output)
def test_cmd_add_from_subdir(self):
repo = git.Repo.init()
repo.config_writer().set_value("user", "name", "Test User").release()
repo.config_writer().set_value("user", "email", "testuser@example.com").release()
# Create three empty files and add them to the git repository
filenames = ["one.py", Path("subdir") / "two.py", Path("anotherdir") / "three.py"]
for filename in filenames:
file_path = Path(filename)
file_path.parent.mkdir(parents=True, exist_ok=True)
file_path.touch()
repo.git.add(str(file_path))
repo.git.commit("-m", "added")
filenames = [str(Path(fn).resolve()) for fn in filenames]
###
os.chdir("subdir")
io = InputOutput(pretty=False, fancy_input=False, yes=True)
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# this should get added
commands.cmd_add(str(Path("anotherdir") / "three.py"))
# this should add one.py
commands.cmd_add("*.py")
self.assertIn(filenames[0], coder.abs_fnames)
self.assertNotIn(filenames[1], coder.abs_fnames)
self.assertIn(filenames[2], coder.abs_fnames)
def test_cmd_add_from_subdir_again(self):
with GitTemporaryDirectory():
io = InputOutput(pretty=False, fancy_input=False, yes=False)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
Path("side_dir").mkdir()
os.chdir("side_dir")
# add a file that is in the side_dir
with open("temp.txt", "w"):
pass
# this was blowing up with GitCommandError, per:
# https://github.com/Aider-AI/aider/issues/201
commands.cmd_add("temp.txt")
def test_cmd_commit(self):
with GitTemporaryDirectory():
fname = "test.txt"
with open(fname, "w") as f:
f.write("test")
repo = git.Repo()
repo.git.add(fname)
repo.git.commit("-m", "initial")
io = InputOutput(pretty=False, fancy_input=False, yes=True)
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
self.assertFalse(repo.is_dirty())
with open(fname, "w") as f:
f.write("new")
self.assertTrue(repo.is_dirty())
commit_message = "Test commit message"
commands.cmd_commit(commit_message)
self.assertFalse(repo.is_dirty())
def test_cmd_add_from_outside_root(self):
with ChdirTemporaryDirectory() as tmp_dname:
root = Path("root")
root.mkdir()
os.chdir(str(root))
io = InputOutput(pretty=False, fancy_input=False, yes=False)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
outside_file = Path(tmp_dname) / "outside.txt"
outside_file.touch()
# This should not be allowed!
# https://github.com/Aider-AI/aider/issues/178
commands.cmd_add("../outside.txt")
self.assertEqual(len(coder.abs_fnames), 0)
def test_cmd_add_from_outside_git(self):
with ChdirTemporaryDirectory() as tmp_dname:
root = Path("root")
root.mkdir()
os.chdir(str(root))
make_repo()
io = InputOutput(pretty=False, fancy_input=False, yes=False)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
outside_file = Path(tmp_dname) / "outside.txt"
outside_file.touch()
# This should not be allowed!
# It was blowing up with GitCommandError, per:
# https://github.com/Aider-AI/aider/issues/178
commands.cmd_add("../outside.txt")
self.assertEqual(len(coder.abs_fnames), 0)
def test_cmd_add_filename_with_special_chars(self):
with ChdirTemporaryDirectory():
io = InputOutput(pretty=False, fancy_input=False, yes=False)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
fname = Path("with[brackets].txt")
fname.touch()
commands.cmd_add(str(fname))
self.assertIn(str(fname.resolve()), coder.abs_fnames)
def test_cmd_tokens_output(self):
with GitTemporaryDirectory() as repo_dir:
# Create a small repository with a few files
(Path(repo_dir) / "file1.txt").write_text("Content of file 1")
(Path(repo_dir) / "file2.py").write_text("print('Content of file 2')")
(Path(repo_dir) / "subdir").mkdir()
(Path(repo_dir) / "subdir" / "file3.md").write_text("# Content of file 3")
repo = git.Repo.init(repo_dir)
repo.git.add(A=True)
repo.git.commit("-m", "Initial commit")
io = InputOutput(pretty=False, fancy_input=False, yes=False)
from aider.coders import Coder
coder = Coder.create(Model("claude-3-5-sonnet-20240620"), None, io)
print(coder.get_announcements())
commands = Commands(io, coder)
commands.cmd_add("*.txt")
# Capture the output of cmd_tokens
original_tool_output = io.tool_output
output_lines = []
def capture_output(*args, **kwargs):
output_lines.extend(args)
original_tool_output(*args, **kwargs)
io.tool_output = capture_output
# Run cmd_tokens
commands.cmd_tokens("")
# Restore original tool_output
io.tool_output = original_tool_output
# Check if the output includes repository map information
repo_map_line = next((line for line in output_lines if "repository map" in line), None)
self.assertIsNotNone(
repo_map_line, "Repository map information not found in the output"
)
# Check if the output includes information about all added files
self.assertTrue(any("file1.txt" in line for line in output_lines))
# Check if the total tokens and remaining tokens are reported
self.assertTrue(any("tokens total" in line for line in output_lines))
self.assertTrue(any("tokens remaining" in line for line in output_lines))
def test_cmd_add_dirname_with_special_chars(self):
with ChdirTemporaryDirectory():
io = InputOutput(pretty=False, fancy_input=False, yes=False)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
dname = Path("with[brackets]")
dname.mkdir()
fname = dname / "filename.txt"
fname.touch()
commands.cmd_add(str(dname))
dump(coder.abs_fnames)
self.assertIn(str(fname.resolve()), coder.abs_fnames)
def test_cmd_add_dirname_with_special_chars_git(self):
with GitTemporaryDirectory():
io = InputOutput(pretty=False, fancy_input=False, yes=False)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
dname = Path("with[brackets]")
dname.mkdir()
fname = dname / "filename.txt"
fname.touch()
repo = git.Repo()
repo.git.add(str(fname))
repo.git.commit("-m", "init")
commands.cmd_add(str(dname))
dump(coder.abs_fnames)
self.assertIn(str(fname.resolve()), coder.abs_fnames)
def test_cmd_add_abs_filename(self):
with ChdirTemporaryDirectory():
io = InputOutput(pretty=False, fancy_input=False, yes=False)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
fname = Path("file.txt")
fname.touch()
commands.cmd_add(str(fname.resolve()))
self.assertIn(str(fname.resolve()), coder.abs_fnames)
def test_cmd_add_quoted_filename(self):
with ChdirTemporaryDirectory():
io = InputOutput(pretty=False, fancy_input=False, yes=False)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
fname = Path("file with spaces.txt")
fname.touch()
commands.cmd_add(f'"{fname}"')
self.assertIn(str(fname.resolve()), coder.abs_fnames)
def test_cmd_add_existing_with_dirty_repo(self):
with GitTemporaryDirectory():
repo = git.Repo()
files = ["one.txt", "two.txt"]
for fname in files:
Path(fname).touch()
repo.git.add(fname)
repo.git.commit("-m", "initial")
commit = repo.head.commit.hexsha
# leave a dirty `git rm`
repo.git.rm("one.txt")
io = InputOutput(pretty=False, fancy_input=False, yes=True)
from aider.coders import Coder
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# There's no reason this /add should trigger a commit
commands.cmd_add("two.txt")
self.assertEqual(commit, repo.head.commit.hexsha)
# Windows is throwing:
# PermissionError: [WinError 32] The process cannot access
# the file because it is being used by another process
repo.git.commit("-m", "cleanup")
del coder
del commands
del repo
def test_cmd_save_and_load(self):
with GitTemporaryDirectory() as repo_dir:
io = InputOutput(pretty=False, fancy_input=False, yes=True)
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Create some test files
test_files = {
"file1.txt": "Content of file 1",
"file2.py": "print('Content of file 2')",
"subdir/file3.md": "# Content of file 3",
}
for file_path, content in test_files.items():
full_path = Path(repo_dir) / file_path
full_path.parent.mkdir(parents=True, exist_ok=True)
full_path.write_text(content)
# Add some files as editable and some as read-only
commands.cmd_add("file1.txt file2.py")
commands.cmd_read_only("subdir/file3.md")
# Save the session to a file
session_file = "test_session.txt"
commands.cmd_save(session_file)
# Verify the session file was created and contains the expected commands
self.assertTrue(Path(session_file).exists())
with open(session_file, encoding=io.encoding) as f:
commands_text = f.read().splitlines()
# Convert paths to absolute for comparison
abs_file1 = str(Path("file1.txt").resolve())
abs_file2 = str(Path("file2.py").resolve())
abs_file3 = str(Path("subdir/file3.md").resolve())
# Check each line for matching paths using os.path.samefile
found_file1 = found_file2 = found_file3 = False
for line in commands_text:
if line.startswith("/add "):
path = Path(line[5:].strip()).resolve()
if os.path.samefile(str(path), abs_file1):
found_file1 = True
elif os.path.samefile(str(path), abs_file2):
found_file2 = True
elif line.startswith("/read-only "):
path = Path(line[11:]).resolve()
if os.path.samefile(str(path), abs_file3):
found_file3 = True
self.assertTrue(found_file1, "file1.txt not found in commands")
self.assertTrue(found_file2, "file2.py not found in commands")
self.assertTrue(found_file3, "file3.md not found in commands")
# Clear the current session
commands.cmd_reset("")
self.assertEqual(len(coder.abs_fnames), 0)
self.assertEqual(len(coder.abs_read_only_fnames), 0)
# Load the session back
commands.cmd_load(session_file)
# Verify files were restored correctly
added_files = {Path(coder.get_rel_fname(f)).as_posix() for f in coder.abs_fnames}
read_only_files = {
Path(coder.get_rel_fname(f)).as_posix() for f in coder.abs_read_only_fnames
}
self.assertEqual(added_files, {"file1.txt", "file2.py"})
self.assertEqual(read_only_files, {"subdir/file3.md"})
# Clean up
Path(session_file).unlink()
def test_cmd_save_and_load_with_external_file(self):
with tempfile.NamedTemporaryFile(mode="w", delete=False) as external_file:
external_file.write("External file content")
external_file_path = external_file.name
try:
with GitTemporaryDirectory() as repo_dir:
io = InputOutput(pretty=False, fancy_input=False, yes=True)
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Create some test files in the repo
test_files = {
"file1.txt": "Content of file 1",
"file2.py": "print('Content of file 2')",
}
for file_path, content in test_files.items():
full_path = Path(repo_dir) / file_path
full_path.parent.mkdir(parents=True, exist_ok=True)
full_path.write_text(content)
# Add some files as editable and some as read-only
commands.cmd_add(str(Path("file1.txt")))
commands.cmd_read_only(external_file_path)
# Save the session to a file
session_file = str(Path("test_session.txt"))
commands.cmd_save(session_file)
# Verify the session file was created and contains the expected commands
self.assertTrue(Path(session_file).exists())
with open(session_file, encoding=io.encoding) as f:
commands_text = f.read()
commands_text = re.sub(
r"/add +", "/add ", commands_text
) # Normalize add command spaces
self.assertIn("/add file1.txt", commands_text)
# Split commands and check each one
for line in commands_text.splitlines():
if line.startswith("/read-only "):
saved_path = line.split(" ", 1)[1]
if os.path.samefile(saved_path, external_file_path):
break
else:
self.fail(f"No matching read-only command found for {external_file_path}")
# Clear the current session
commands.cmd_reset("")
self.assertEqual(len(coder.abs_fnames), 0)
self.assertEqual(len(coder.abs_read_only_fnames), 0)
# Load the session back
commands.cmd_load(session_file)
# Verify files were restored correctly
added_files = {coder.get_rel_fname(f) for f in coder.abs_fnames}
read_only_files = {coder.get_rel_fname(f) for f in coder.abs_read_only_fnames}
self.assertEqual(added_files, {str(Path("file1.txt"))})
self.assertTrue(
any(os.path.samefile(external_file_path, f) for f in read_only_files)
)
# Clean up
Path(session_file).unlink()
finally:
os.unlink(external_file_path)
def test_cmd_save_and_load_with_multiple_external_files(self):
with (
tempfile.NamedTemporaryFile(mode="w", delete=False) as external_file1,
tempfile.NamedTemporaryFile(mode="w", delete=False) as external_file2,
):
external_file1.write("External file 1 content")
external_file2.write("External file 2 content")
external_file1_path = external_file1.name
external_file2_path = external_file2.name
try:
with GitTemporaryDirectory() as repo_dir:
io = InputOutput(pretty=False, fancy_input=False, yes=True)
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Create some test files in the repo
test_files = {
"internal1.txt": "Content of internal file 1",
"internal2.txt": "Content of internal file 2",
}
for file_path, content in test_files.items():
full_path = Path(repo_dir) / file_path
full_path.parent.mkdir(parents=True, exist_ok=True)
full_path.write_text(content)
# Add files as editable and read-only
commands.cmd_add(str(Path("internal1.txt")))
commands.cmd_read_only(external_file1_path)
commands.cmd_read_only(external_file2_path)
# Save the session to a file
session_file = str(Path("test_session.txt"))
commands.cmd_save(session_file)
# Verify the session file was created and contains the expected commands
self.assertTrue(Path(session_file).exists())
with open(session_file, encoding=io.encoding) as f:
commands_text = f.read()
commands_text = re.sub(
r"/add +", "/add ", commands_text
) # Normalize add command spaces
self.assertIn("/add internal1.txt", commands_text)
# Split commands and check each one
for line in commands_text.splitlines():
if line.startswith("/read-only "):
saved_path = line.split(" ", 1)[1]
if os.path.samefile(saved_path, external_file1_path):
break
else:
self.fail(f"No matching read-only command found for {external_file1_path}")
# Split commands and check each one
for line in commands_text.splitlines():
if line.startswith("/read-only "):
saved_path = line.split(" ", 1)[1]
if os.path.samefile(saved_path, external_file2_path):
break
else:
self.fail(f"No matching read-only command found for {external_file2_path}")
# Clear the current session
commands.cmd_reset("")
self.assertEqual(len(coder.abs_fnames), 0)
self.assertEqual(len(coder.abs_read_only_fnames), 0)
# Load the session back
commands.cmd_load(session_file)
# Verify files were restored correctly
added_files = {coder.get_rel_fname(f) for f in coder.abs_fnames}
read_only_files = {coder.get_rel_fname(f) for f in coder.abs_read_only_fnames}
self.assertEqual(added_files, {str(Path("internal1.txt"))})
self.assertTrue(
all(
any(os.path.samefile(external_path, fname) for fname in read_only_files)
for external_path in [external_file1_path, external_file2_path]
)
)
# Clean up
Path(session_file).unlink()
finally:
os.unlink(external_file1_path)
os.unlink(external_file2_path)
def test_cmd_read_only_with_image_file(self):
with GitTemporaryDirectory() as repo_dir:
io = InputOutput(pretty=False, fancy_input=False, yes=False)
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Create a test image file
test_file = Path(repo_dir) / "test_image.jpg"
test_file.write_text("Mock image content")
# Test with non-vision model
commands.cmd_read_only(str(test_file))
self.assertEqual(len(coder.abs_read_only_fnames), 0)
# Test with vision model
vision_model = Model("gpt-4-vision-preview")
vision_coder = Coder.create(vision_model, None, io)
vision_commands = Commands(io, vision_coder)
vision_commands.cmd_read_only(str(test_file))
self.assertEqual(len(vision_coder.abs_read_only_fnames), 1)
self.assertTrue(
any(
os.path.samefile(str(test_file), fname)
for fname in vision_coder.abs_read_only_fnames
)
)
# Add a dummy message to ensure format_messages() works
vision_coder.cur_messages = [{"role": "user", "content": "Check the image"}]
# Check that the image file appears in the messages
messages = vision_coder.format_messages().all_messages()
found_image = False
for msg in messages:
if msg.get("role") == "user" and "content" in msg:
content = msg["content"]
if isinstance(content, list):
for item in content:
if isinstance(item, dict) and item.get("type") == "text":
if "test_image.jpg" in item.get("text", ""):
found_image = True
break
self.assertTrue(found_image, "Image file not found in messages to LLM")
def test_cmd_read_only_with_glob_pattern(self):
with GitTemporaryDirectory() as repo_dir:
io = InputOutput(pretty=False, fancy_input=False, yes=False)
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Create multiple test files
test_files = ["test_file1.txt", "test_file2.txt", "other_file.txt"]
for file_name in test_files:
file_path = Path(repo_dir) / file_name
file_path.write_text(f"Content of {file_name}")
# Test the /read-only command with a glob pattern
commands.cmd_read_only("test_*.txt")
# Check if only the matching files were added to abs_read_only_fnames
self.assertEqual(len(coder.abs_read_only_fnames), 2)
for file_name in ["test_file1.txt", "test_file2.txt"]:
file_path = Path(repo_dir) / file_name
self.assertTrue(
any(
os.path.samefile(str(file_path), fname)
for fname in coder.abs_read_only_fnames
)
)
# Check that other_file.txt was not added
other_file_path = Path(repo_dir) / "other_file.txt"
self.assertFalse(
any(
os.path.samefile(str(other_file_path), fname)
for fname in coder.abs_read_only_fnames
)
)
def test_cmd_read_only_with_recursive_glob(self):
with GitTemporaryDirectory() as repo_dir:
io = InputOutput(pretty=False, fancy_input=False, yes=False)
coder = Coder.create(self.GPT35, None, io)
commands = Commands(io, coder)
# Create a directory structure with files
(Path(repo_dir) / "subdir").mkdir()
test_files = ["test_file1.txt", "subdir/test_file2.txt", "subdir/other_file.txt"]