forked from phcode-dev/phcode.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindInFiles-replace-test.js
More file actions
1567 lines (1373 loc) · 78.9 KB
/
FindInFiles-replace-test.js
File metadata and controls
1567 lines (1373 loc) · 78.9 KB
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
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
* Original work Copyright (c) 2014 - 2021 Adobe Systems Incorporated. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
/*jslint regexp: true */
/*global describe, it, expect, beforeFirst, afterLast, beforeEach, afterEach, waits, waitsFor, waitsForDone, runs, spyOn */
define(function (require, exports, module) {
var Commands = require("command/Commands"),
KeyEvent = require("utils/KeyEvent"),
SpecRunnerUtils = require("spec/SpecRunnerUtils"),
FileSystemError = require("filesystem/FileSystemError"),
FileUtils = require("file/FileUtils"),
FindUtils = require("search/FindUtils"),
Async = require("utils/Async"),
LanguageManager = require("language/LanguageManager"),
StringUtils = require("utils/StringUtils"),
Strings = require("strings"),
_ = require("thirdparty/lodash");
var PreferencesManager;
var promisify = Async.promisify; // for convenience
describe("FindInFiles - replace", function () {
function waitms(timeout) {
let waitDone = false;
setTimeout(()=>{
waitDone = true;
}, timeout);
waitsFor(function () {
return waitDone;
}, timeout + 100, "wait done");
}
this.category = "integration";
var defaultSourcePath = SpecRunnerUtils.getTestPath("/spec/FindReplace-test-files"),
testPath,
nextFolderIndex = 1,
searchResults,
CommandManager,
DocumentManager,
MainViewManager,
EditorManager,
FileFilters,
FileSystem,
File,
FindInFiles,
FindUtilsWin,
FindInFilesUI,
ProjectManager,
SearchResultsView,
testWindow,
$,
indexingComplete = false;
beforeFirst(function () {
SpecRunnerUtils.createTempDirectory();
// Create a new window that will be shared by ALL tests in this spec.
SpecRunnerUtils.createTestWindowAndRun(this, function (w) {
testWindow = w;
// Load module instances from brackets.test
CommandManager = testWindow.brackets.test.CommandManager;
DocumentManager = testWindow.brackets.test.DocumentManager;
EditorManager = testWindow.brackets.test.EditorManager;
FileFilters = testWindow.brackets.test.FileFilters;
FileSystem = testWindow.brackets.test.FileSystem;
File = testWindow.brackets.test.File;
FindUtilsWin = testWindow.brackets.test.FindUtils;
FindInFiles = testWindow.brackets.test.FindInFiles;
FindInFilesUI = testWindow.brackets.test.FindInFilesUI;
ProjectManager = testWindow.brackets.test.ProjectManager;
MainViewManager = testWindow.brackets.test.MainViewManager;
SearchResultsView = testWindow.brackets.test.SearchResultsView;
$ = testWindow.$;
PreferencesManager = testWindow.brackets.test.PreferencesManager;
PreferencesManager.set("findInFiles.nodeSearch", false);
PreferencesManager.set("findInFiles.instantSearch", false);
PreferencesManager.set("maxSearchHistory", 5);
FindUtilsWin.on(FindUtils.SEARCH_INDEXING_STARTED, ()=>{
indexingComplete = false;
});
FindUtilsWin.on(FindUtils.SEARCH_INDEXING_FINISHED, ()=>{
indexingComplete = true;
});
});
});
afterLast(function () {
CommandManager = null;
DocumentManager = null;
EditorManager = null;
FileSystem = null;
File = null;
FindInFiles = null;
FindInFilesUI = null;
ProjectManager = null;
MainViewManager = null;
$ = null;
testWindow = null;
PreferencesManager = null;
SpecRunnerUtils.closeTestWindow();
SpecRunnerUtils.removeTempDirectory();
});
function openProject(sourcePath) {
testPath = sourcePath;
SpecRunnerUtils.loadProjectInTestWindow(testPath);
}
// Note: these utilities can be called without wrapping in a runs() block, because all their top-level
// statements are calls to runs() or waitsFor() (or other functions that make the same guarantee). But after
// calling one of these, calls to other Jasmine APIs (e.g. such as expects()) *must* be wrapped in runs().
function waitForSearchBarClose() {
// Make sure search bar from previous test has animated out fully
waitsFor(function () {
return $(".modal-bar").length === 0;
}, "search bar close");
}
function openSearchBar(scope, showReplace) {
runs(function () {
FindInFiles._searchDone = false;
FindInFilesUI._showFindBar(scope, showReplace);
});
waitsFor(function () {
return $(".modal-bar").length === 1;
}, "search bar open");
runs(function () {
// Reset the regexp and case-sensitivity toggles.
["#find-regexp", "#find-case-sensitive"].forEach(function (button) {
if ($(button).is(".active")) {
$(button).click();
expect($(button).is(".active")).toBe(false);
}
});
});
}
function closeSearchBar() {
runs(function () {
FindInFilesUI._closeFindBar();
});
waitForSearchBarClose();
}
function executeSearch(searchString) {
waitsFor(function () {
return indexingComplete;
}, "indexing complete");
runs(function () {
var $searchField = $("#find-what");
$searchField.val(searchString).trigger("input");
SpecRunnerUtils.simulateKeyEvent(KeyEvent.DOM_VK_RETURN, "keydown", $searchField[0]);
});
waitsFor(function () {
return FindInFiles._searchDone;
}, "Find in Files done");
}
function numMatches(results) {
return _.reduce(_.pluck(results, "matches"), function (sum, matches) {
return sum + matches.length;
}, 0);
}
function doSearch(options) {
waitsFor(function () {
return indexingComplete;
}, "indexing complete");
runs(function () {
FindInFiles.doSearchInScope(options.queryInfo, null, null, options.replaceText).done(function (results) {
searchResults = results;
});
});
waitsFor(function () { return searchResults; }, 1000, "search completed");
runs(function () {
expect(numMatches(searchResults)).toBe(options.numMatches);
});
waitsFor(function () {
return FindInFiles._searchDone;
}, "Find in Files done");
}
// The functions below are *not* safe to call without wrapping in runs(), if there were any async steps previously
// (including calls to any of the utilities above)
function doReplace(options) {
return FindInFiles.doReplace(searchResults, options.replaceText, {
forceFilesOpen: options.forceFilesOpen,
isRegexp: options.queryInfo.isRegexp
});
}
/**
* Helper function that calls the given asynchronous processor once on each file in the given subtree
* and returns a promise that's resolved when all files are processed.
* @param {string} rootPath The root of the subtree to search.
* @param {function(string, string): $.Promise} processor The function that processes each file. Args are:
* contents: the contents of the file
* fullPath: the full path to the file on disk
* @return {$.Promise} A promise that is resolved when all files are processed, or rejected if there was
* an error reading one of the files or one of the process steps was rejected.
*/
function visitAndProcessFiles(rootPath, processor) {
var rootEntry = FileSystem.getDirectoryForPath(rootPath),
files = [];
function visitor(file) {
if (!file.isDirectory) {
// Skip binary files, since we don't care about them for these purposes and we can't read them
// to get their contents.
if (!LanguageManager.getLanguageForPath(file.fullPath).isBinary()) {
files.push(file);
}
}
return true;
}
return promisify(rootEntry, "visit", visitor).then(function () {
return Async.doInParallel(files, function (file) {
return promisify(file, "read").then(function (contents) {
return processor(contents, file.fullPath);
});
});
});
}
function ensureParentExists(file) {
var parentDir = FileSystem.getDirectoryForPath(file.parentPath);
return promisify(parentDir, "exists").then(function (exists) {
if (!exists) {
return promisify(parentDir, "create");
}
return null;
});
}
function copyWithLineEndings(src, dest, lineEndings) {
function copyOneFileWithLineEndings(contents, srcPath) {
var destPath = dest + srcPath.slice(src.length),
destFile = FileSystem.getFileForPath(destPath),
newContents = FileUtils.translateLineEndings(contents, lineEndings);
return ensureParentExists(destFile).then(function () {
return promisify(destFile, "write", newContents);
});
}
return promisify(FileSystem.getDirectoryForPath(dest), "create").then(function () {
return visitAndProcessFiles(src, copyOneFileWithLineEndings);
});
}
// Creates a clean copy of the test project before each test. We don't delete the old
// folders as we go along (to avoid problems with deleting the project out from under the
// open test window); we just delete the whole temp folder at the end.
function openTestProjectCopy(sourcePath, lineEndings) {
testPath = SpecRunnerUtils.getTempDirectory() + "/find-in-files-test-" + (nextFolderIndex++);
runs(function () {
if (lineEndings) {
waitsForDone(copyWithLineEndings(sourcePath, testPath, lineEndings), "copy test files with line endings");
} else {
// Note that we don't skip image files in this case, but it doesn't matter since we'll
// only compare files that have an associated file in the known goods folder.
waitsForDone(SpecRunnerUtils.copy(sourcePath, testPath), "copy test files");
}
});
SpecRunnerUtils.loadProjectInTestWindow(testPath);
}
beforeEach(function () {
searchResults = null;
});
describe("Replace", function () {
function expectProjectToMatchKnownGood(kgFolder, lineEndings, filesToSkip) {
runs(function () {
var testRootPath = ProjectManager.getProjectRoot().fullPath,
kgRootPath = SpecRunnerUtils.getTestPath("/spec/FindReplace-known-goods/" + kgFolder + "/");
function compareKnownGoodToTestFile(kgContents, kgFilePath) {
var testFilePath = testRootPath + kgFilePath.slice(kgRootPath.length);
if (!filesToSkip || filesToSkip.indexOf(testFilePath) === -1) {
return promisify(FileSystem.getFileForPath(testFilePath), "read").then(function (testContents) {
if (lineEndings) {
kgContents = FileUtils.translateLineEndings(kgContents, lineEndings);
}
expect(testContents).toEqual(kgContents);
});
}
}
waitsForDone(visitAndProcessFiles(kgRootPath, compareKnownGoodToTestFile), "project comparison done");
});
}
// Does a standard test for files on disk: search, replace, and check that files on disk match.
// Options:
// knownGoodFolder: name of folder containing known goods to match to project files on disk
// lineEndings: optional, one of the FileUtils.LINE_ENDINGS_* constants
// - if specified, files on disk are expected to have these line endings
// uncheckMatches: optional array of {file: string, index: number} items to uncheck; if
// index unspecified, will uncheck all matches in file
function doBasicTest(options) {
doSearch(options);
runs(function () {
if (options.uncheckMatches) {
options.uncheckMatches.forEach(function (matchToUncheck) {
var matches = searchResults[testPath + matchToUncheck.file].matches;
if (matchToUncheck.index) {
matches[matchToUncheck.index].isChecked = false;
} else {
matches.forEach(function (match) {
match.isChecked = false;
});
}
});
}
waitsForDone(doReplace(options), "finish replacement");
});
expectProjectToMatchKnownGood(options.knownGoodFolder, options.lineEndings);
}
// Like doBasicTest, but expects some files to have specific errors.
// Options: same as doBasicTest, plus:
// test: optional function (which must contain one or more runs blocks) to run between
// search and replace
// errors: array of errors expected to occur (in the same format as performReplacement() returns)
function doTestWithErrors(options) {
var done = false;
doSearch(options);
if (options.test) {
// The test function *must* contain one or more runs blocks.
options.test();
}
runs(function () {
doReplace(options)
.then(function () {
expect("should fail due to error").toBe(true);
done = true;
}, function (errors) {
expect(errors).toEqual(options.errors);
done = true;
});
});
waitsFor(function () { return done; }, 1000, "finish replacement");
expectProjectToMatchKnownGood(options.knownGoodFolder, options.lineEndings);
}
function expectInMemoryFiles(options) {
runs(function () {
waitsForDone(Async.doInParallel(options.inMemoryFiles, function (filePath) {
var fullPath;
// If this is a full file path (as would be the case for an external file), handle it specially.
if (typeof filePath === "object" && filePath.fullPath) {
fullPath = filePath.fullPath;
filePath = "/" + FileUtils.getBaseName(fullPath);
} else {
fullPath = testPath + filePath;
}
// Check that the document open in memory was changed and matches the expected replaced version of that file.
var doc = DocumentManager.getOpenDocumentForPath(fullPath);
expect(doc).toBeTruthy();
expect(doc.isDirty).toBe(true);
var kgPath = SpecRunnerUtils.getTestPath("/spec/FindReplace-known-goods/" + options.inMemoryKGFolder + filePath),
kgFile = FileSystem.getFileForPath(kgPath);
return promisify(kgFile, "read").then(function (contents) {
expect(doc.getText(true)).toEqual(contents);
});
}), "check in memory file contents");
});
}
// Like doBasicTest, but expects one or more files to be open in memory and the replacements to happen there.
// Options: same as doBasicTest, plus:
// inMemoryFiles: array of project-relative paths (each starting with "/") to files that should be open in memory
// inMemoryKGFolder: folder containing known goods to compare each of the inMemoryFiles to
function doInMemoryTest(options) {
// Like the basic test, we expect everything on disk to match the kgFolder (which means the file open in memory
// should *not* have changed on disk yet).
doBasicTest(options);
expectInMemoryFiles(options);
}
afterEach(function () {
runs(function () {
waitsForDone(CommandManager.execute(Commands.FILE_CLOSE_ALL, { _forceClose: true }), "close all files");
});
waitms(2000);
});
describe("Engine", function () {
it("should replace all instances of a simple string in a project on disk case-insensitively", function () {
openTestProjectCopy(defaultSourcePath);
doBasicTest({
queryInfo: {query: "foo"},
numMatches: 14,
replaceText: "bar",
knownGoodFolder: "simple-case-insensitive"
});
});
it("should replace all instances of a simple string in a project on disk case-sensitively", function () {
openTestProjectCopy(defaultSourcePath);
doBasicTest({
queryInfo: {query: "foo", isCaseSensitive: true},
numMatches: 9,
replaceText: "bar",
knownGoodFolder: "simple-case-sensitive"
});
});
it("should replace all instances of a regexp in a project on disk case-insensitively with a simple replace string", function () {
openTestProjectCopy(defaultSourcePath);
doBasicTest({
queryInfo: {query: "\\b[a-z]{3}\\b", isRegexp: true},
numMatches: 33,
replaceText: "CHANGED",
knownGoodFolder: "regexp-case-insensitive"
});
});
it("should replace all instances of a regexp that spans multiple lines in a project on disk", function () {
openTestProjectCopy(defaultSourcePath);
// This query should find each rule in the CSS file (but not in the JS file since there's more than one line
// between each pair of braces).
doBasicTest({
queryInfo: {query: "\\{\\n[^\\n]*\\n\\}", isRegexp: true},
numMatches: 4,
replaceText: "CHANGED",
knownGoodFolder: "regexp-replace-multiline"
});
});
it("should replace all instances of a regexp that spans multiple lines in a project in memory", function () {
openTestProjectCopy(defaultSourcePath);
// This query should find each rule in the CSS file (but not in the JS file since there's more than one line
// between each pair of braces).
doInMemoryTest({
queryInfo: {query: "\\{\\n[^\\n]*\\n\\}", isRegexp: true},
numMatches: 4,
replaceText: "CHANGED",
knownGoodFolder: "unchanged",
forceFilesOpen: true,
inMemoryFiles: ["/css/foo.css"],
inMemoryKGFolder: "regexp-replace-multiline"
});
});
it("should replace all instances of a regexp that spans multiple lines in a project on disk when the last line is a partial match", function () {
openTestProjectCopy(defaultSourcePath);
// This query should match from the open brace through to (and including) the first colon of each rule in the
// CSS file.
doBasicTest({
queryInfo: {query: "\\{\\n[^:]+:", isRegexp: true},
numMatches: 4,
replaceText: "CHANGED",
knownGoodFolder: "regexp-replace-multiline-partial"
});
});
it("should replace all instances of a regexp that spans multiple lines in a project in memory when the last line is a partial match", function () {
openTestProjectCopy(defaultSourcePath);
// This query should match from the open brace through to (and including) the first colon of each rule in the
// CSS file.
doInMemoryTest({
queryInfo: {query: "\\{\\n[^:]+:", isRegexp: true},
numMatches: 4,
replaceText: "CHANGED",
knownGoodFolder: "unchanged",
forceFilesOpen: true,
inMemoryFiles: ["/css/foo.css"],
inMemoryKGFolder: "regexp-replace-multiline-partial"
});
});
it("should replace all instances of a regexp in a project on disk case-sensitively with a simple replace string", function () {
openTestProjectCopy(defaultSourcePath);
doBasicTest({
queryInfo: {query: "\\b[a-z]{3}\\b", isRegexp: true, isCaseSensitive: true},
numMatches: 25,
replaceText: "CHANGED",
knownGoodFolder: "regexp-case-sensitive"
});
});
it("should replace instances of a regexp with a $-substitution on disk", function () {
openTestProjectCopy(defaultSourcePath);
doBasicTest({
queryInfo: {query: "\\b([a-z]{3})\\b", isRegexp: true},
numMatches: 33,
replaceText: "[$1]",
knownGoodFolder: "regexp-dollar-replace"
});
});
it("should replace instances of a regexp with a $-substitution in in-memory files", function () {
// This test case is necessary because the in-memory case goes through a separate code path before it deals with
// the replace text.
openTestProjectCopy(defaultSourcePath);
doInMemoryTest({
queryInfo: {query: "\\b([a-z]{3})\\b", isRegexp: true},
numMatches: 33,
replaceText: "[$1]",
knownGoodFolder: "unchanged",
forceFilesOpen: true,
inMemoryFiles: ["/css/foo.css", "/foo.html", "/foo.js"],
inMemoryKGFolder: "regexp-dollar-replace"
});
});
it("should replace instances of regexp with 0-length matches on disk", function () {
openTestProjectCopy(defaultSourcePath);
doBasicTest({
queryInfo: {query: "^", isRegexp: true},
numMatches: 55,
replaceText: "CHANGED",
knownGoodFolder: "regexp-zero-length"
});
});
it("should replace instances of regexp with 0-length matches in memory", function () {
openTestProjectCopy(defaultSourcePath);
doInMemoryTest({
queryInfo: {query: "^", isRegexp: true},
numMatches: 55,
replaceText: "CHANGED",
knownGoodFolder: "unchanged",
forceFilesOpen: true,
inMemoryFiles: ["/css/foo.css", "/foo.html", "/foo.js"],
inMemoryKGFolder: "regexp-zero-length"
});
});
it("should replace instances of a string in a project respecting CRLF line endings", function () {
openTestProjectCopy(defaultSourcePath, FileUtils.LINE_ENDINGS_CRLF);
doBasicTest({
queryInfo: {query: "foo"},
numMatches: 14,
replaceText: "bar",
knownGoodFolder: "simple-case-insensitive",
lineEndings: FileUtils.LINE_ENDINGS_CRLF
});
});
it("should replace instances of a string in a project respecting LF line endings", function () {
openTestProjectCopy(defaultSourcePath, FileUtils.LINE_ENDINGS_LF);
doBasicTest({
queryInfo: {query: "foo"},
numMatches: 14,
replaceText: "bar",
knownGoodFolder: "simple-case-insensitive",
lineEndings: FileUtils.LINE_ENDINGS_LF
});
});
it("should not replace unchecked matches on disk", function () {
openTestProjectCopy(defaultSourcePath);
doBasicTest({
queryInfo: {query: "foo"},
numMatches: 14,
uncheckMatches: [{file: "/css/foo.css"}],
replaceText: "bar",
knownGoodFolder: "simple-case-insensitive-except-foo.css"
});
});
it("should do all in-memory replacements synchronously, so user can't accidentally edit document after start of replace process", function () {
openTestProjectCopy(defaultSourcePath);
// Open two of the documents we want to replace in memory.
runs(function () {
waitsForDone(CommandManager.execute(Commands.CMD_ADD_TO_WORKINGSET_AND_OPEN, { fullPath: testPath + "/css/foo.css" }), "opening document");
});
runs(function () {
waitsForDone(CommandManager.execute(Commands.CMD_ADD_TO_WORKINGSET_AND_OPEN, { fullPath: testPath + "/foo.js" }), "opening document");
});
// We can't use expectInMemoryFiles(), since this test requires everything to happen fully synchronously
// (no file reads) once the replace has started. So we read the files here.
var kgFileContents = {};
runs(function () {
var kgPath = SpecRunnerUtils.getTestPath("/spec/FindReplace-known-goods/simple-case-insensitive");
waitsForDone(visitAndProcessFiles(kgPath, function (contents, fullPath) {
// Translate line endings to in-memory document style (always LF)
kgFileContents[fullPath.slice(kgPath.length)] = FileUtils.translateLineEndings(contents, FileUtils.LINE_ENDINGS_LF);
}), "reading known good");
});
doSearch({
queryInfo: {query: "foo"},
numMatches: 14,
replaceText: "bar"
});
runs(function () {
// Start the replace, but don't wait for it to complete. Since the in-memory replacements should occur
// synchronously, the in-memory documents should have already been changed. This means we don't have to
// worry about detecting changes in documents once the replace starts. (If the user had changed
// the document after the search but before the replace started, we would have already closed the panel,
// preventing the user from doing a replace.)
var promise = FindInFiles.doReplace(searchResults, "bar");
// Check the in-memory contents against the known goods.
["/css/foo.css", "/foo.js"].forEach(function (filename) {
var fullPath = testPath + filename,
doc = DocumentManager.getOpenDocumentForPath(fullPath);
expect(doc).toBeTruthy();
expect(doc.isDirty).toBe(true);
expect(doc.getText()).toEqual(kgFileContents[filename]);
});
// Finish the replace operation, which should go ahead and do the file on disk.
waitsForDone(promise);
});
runs(function () {
// Now the file on disk should have been replaced too.
waitsForDone(promisify(FileSystem.getFileForPath(testPath + "/foo.html"), "read").then(function (contents) {
expect(FileUtils.translateLineEndings(contents, FileUtils.LINE_ENDINGS_LF)).toEqual(kgFileContents["/foo.html"]);
}), "checking known good");
});
});
it("should return an error and not do the replacement in files that have changed on disk since the search", function () {
openTestProjectCopy(defaultSourcePath);
doTestWithErrors({
queryInfo: {query: "foo"},
numMatches: 14,
replaceText: "bar",
knownGoodFolder: "changed-file",
test: function () {
// Wait for one second to make sure that the changed file gets an updated timestamp.
// TODO: this seems like a FileSystem issue - we don't get timestamp changes with a resolution
// of less than one second.
waits(1000);
runs(function () {
// Clone the results so we don't use the version that's auto-updated by FindInFiles when we modify the file
// on disk. This case might not usually come up in the real UI if we always guarantee that the results list will
// be auto-updated, but we want to make sure there's no edge case where we missed an update and still clobber the
// file on disk anyway.
searchResults = _.cloneDeep(searchResults);
waitsForDone(promisify(FileSystem.getFileForPath(testPath + "/css/foo.css"), "write", "/* changed content */"), "modify file");
});
},
errors: [{item: testPath + "/css/foo.css", error: FindUtils.ERROR_FILE_CHANGED}]
});
});
it("should return an error if a write fails", function () {
openTestProjectCopy(defaultSourcePath);
// Return a fake error when we try to write to the CSS file. (Note that this is spying on the test window's File module.)
var writeSpy = spyOn(File.prototype, "write").andCallFake(function (data, options, callback) {
if (typeof options === "function") {
callback = options;
} else {
callback = callback || function () {};
}
if (this.fullPath === testPath + "/css/foo.css") {
callback(FileSystemError.NOT_WRITABLE);
} else {
return writeSpy.originalValue.apply(this, arguments);
}
});
doTestWithErrors({
queryInfo: {query: "foo"},
numMatches: 14,
replaceText: "bar",
knownGoodFolder: "simple-case-insensitive-except-foo.css",
errors: [{item: testPath + "/css/foo.css", error: FileSystemError.NOT_WRITABLE}]
});
});
it("should return an error if a match timestamp doesn't match an in-memory document timestamp", function () {
openTestProjectCopy(defaultSourcePath);
runs(function () {
waitsForDone(CommandManager.execute(Commands.CMD_ADD_TO_WORKINGSET_AND_OPEN, { fullPath: testPath + "/css/foo.css" }), "opening document");
});
doTestWithErrors({
queryInfo: {query: "foo"},
numMatches: 14,
replaceText: "bar",
knownGoodFolder: "simple-case-insensitive-except-foo.css",
test: function () {
runs(function () {
// Clone the results so we don't use the version that's auto-updated by FindInFiles when we modify the file
// on disk. This case might not usually come up in the real UI if we always guarantee that the results list will
// be auto-updated, but we want to make sure there's no edge case where we missed an update and still clobber the
// file on disk anyway.
searchResults = _.cloneDeep(searchResults);
var oldTimestamp = searchResults[testPath + "/css/foo.css"].timestamp;
searchResults[testPath + "/css/foo.css"].timestamp = new Date(oldTimestamp.getTime() - 5000);
});
},
errors: [{item: testPath + "/css/foo.css", error: FindUtils.ERROR_FILE_CHANGED}]
});
});
it("should do the replacement in memory for a file open in an Editor in the working set", function () {
openTestProjectCopy(defaultSourcePath);
runs(function () {
waitsForDone(CommandManager.execute(Commands.CMD_ADD_TO_WORKINGSET_AND_OPEN, {fullPath: testPath + "/css/foo.css"}), "add file to working set");
});
doInMemoryTest({
queryInfo: {query: "foo"},
numMatches: 14,
replaceText: "bar",
knownGoodFolder: "simple-case-insensitive-except-foo.css",
inMemoryFiles: ["/css/foo.css"],
inMemoryKGFolder: "simple-case-insensitive"
});
});
it("should do the search/replace in the current document content for a dirty in-memory document", function () {
openTestProjectCopy(defaultSourcePath);
var options = {
queryInfo: {query: "foo"},
numMatches: 15,
replaceText: "bar",
inMemoryFiles: ["/css/foo.css"],
inMemoryKGFolder: "simple-case-insensitive-modified"
};
runs(function () {
waitsForDone(CommandManager.execute(Commands.CMD_ADD_TO_WORKINGSET_AND_OPEN, {fullPath: testPath + "/css/foo.css"}), "add file to working set");
});
runs(function () {
var doc = DocumentManager.getOpenDocumentForPath(testPath + "/css/foo.css");
expect(doc).toBeTruthy();
doc.replaceRange("/* added a foo line */\n", {line: 0, ch: 0});
});
doSearch(options);
runs(function () {
waitsForDone(doReplace(options), "replace done");
});
expectInMemoryFiles(options);
expectProjectToMatchKnownGood("simple-case-insensitive-modified", null, [testPath + "/css/foo.css"]);
});
it("should do the replacement in memory for a file open in an Editor that's not in the working set", function () {
openTestProjectCopy(defaultSourcePath);
runs(function () {
waitsForDone(CommandManager.execute(Commands.FILE_OPEN, {fullPath: testPath + "/css/foo.css"}), "open file");
});
doInMemoryTest({
queryInfo: {query: "foo"},
numMatches: 14,
replaceText: "bar",
knownGoodFolder: "simple-case-insensitive-except-foo.css",
inMemoryFiles: ["/css/foo.css"],
inMemoryKGFolder: "simple-case-insensitive"
});
});
it("should do the replacement in memory for a file that's in the working set but not yet open in an editor", function () {
openTestProjectCopy(defaultSourcePath);
runs(function () {
MainViewManager.addToWorkingSet(MainViewManager.ACTIVE_PANE, FileSystem.getFileForPath(testPath + "/css/foo.css"));
});
doInMemoryTest({
queryInfo: {query: "foo"},
numMatches: 14,
replaceText: "bar",
knownGoodFolder: "simple-case-insensitive-except-foo.css",
inMemoryFiles: ["/css/foo.css"],
inMemoryKGFolder: "simple-case-insensitive"
});
});
it("should open the document in an editor and do the replacement there if the document is open but not in an Editor", function () {
var doc, openFilePath;
openTestProjectCopy(defaultSourcePath);
runs(function () {
openFilePath = testPath + "/css/foo.css";
waitsForDone(DocumentManager.getDocumentForPath(openFilePath).done(function (d) {
doc = d;
doc.addRef();
}), "get document");
});
doInMemoryTest({
queryInfo: {query: "foo"},
numMatches: 14,
replaceText: "bar",
knownGoodFolder: "simple-case-insensitive-except-foo.css",
inMemoryFiles: ["/css/foo.css"],
inMemoryKGFolder: "simple-case-insensitive"
});
runs(function () {
var workingSet = MainViewManager.getWorkingSet(MainViewManager.ALL_PANES);
expect(workingSet.some(function (file) { return file.fullPath === openFilePath; })).toBe(true);
doc.releaseRef();
});
});
it("should open files and do all replacements in memory if forceFilesOpen is true", function () {
openTestProjectCopy(defaultSourcePath);
doInMemoryTest({
queryInfo: {query: "foo"},
numMatches: 14,
replaceText: "bar",
knownGoodFolder: "unchanged",
forceFilesOpen: true,
inMemoryFiles: ["/css/foo.css", "/foo.html", "/foo.js"],
inMemoryKGFolder: "simple-case-insensitive"
});
});
it("should not perform unchecked matches in memory", function () {
openTestProjectCopy(defaultSourcePath);
doInMemoryTest({
queryInfo: {query: "foo"},
numMatches: 14,
uncheckMatches: [{file: "/css/foo.css", index: 1}, {file: "/foo.html", index: 3}],
replaceText: "bar",
knownGoodFolder: "unchanged",
forceFilesOpen: true,
inMemoryFiles: ["/css/foo.css", "/foo.html", "/foo.js"],
inMemoryKGFolder: "simple-case-insensitive-unchecked"
});
});
it("should not perform unchecked matches on disk", function () {
openTestProjectCopy(defaultSourcePath);
doBasicTest({
queryInfo: {query: "foo"},
numMatches: 14,
uncheckMatches: [{file: "/css/foo.css", index: 1}, {file: "/foo.html", index: 3}],
replaceText: "bar",
knownGoodFolder: "simple-case-insensitive-unchecked"
});
});
it("should select the first modified file in the working set if replacements are done in memory and current editor wasn't affected", function () {
openTestProjectCopy(defaultSourcePath);
runs(function () {
waitsForDone(CommandManager.execute(Commands.CMD_ADD_TO_WORKINGSET_AND_OPEN, {fullPath: testPath + "/bar.txt"}), "open file");
});
doInMemoryTest({
queryInfo: {query: "foo"},
numMatches: 14,
replaceText: "bar",
knownGoodFolder: "unchanged",
forceFilesOpen: true,
inMemoryFiles: ["/css/foo.css", "/foo.html", "/foo.js"],
inMemoryKGFolder: "simple-case-insensitive"
});
runs(function () {
var expectedFile = testPath + "/foo.html";
expect(DocumentManager.getCurrentDocument().file.fullPath).toBe(expectedFile);
expect(MainViewManager.findInWorkingSet(MainViewManager.ACTIVE_PANE, expectedFile)).not.toBe(-1);
});
});
it("should select the first modified file in the working set if replacements are done in memory and no editor was open", function () {
openTestProjectCopy(defaultSourcePath);
var testFiles = ["/css/foo.css", "/foo.html", "/foo.js"];
doInMemoryTest({
queryInfo: {query: "foo"},
numMatches: 14,
replaceText: "bar",
knownGoodFolder: "unchanged",
forceFilesOpen: true,
inMemoryFiles: testFiles,
inMemoryKGFolder: "simple-case-insensitive"
});
runs(function () {
// since nothing was opened prior to doing the
// replacements then the first file modified will be opened.
// This may not be the first item in the array above
// since the files are sorted differently in performReplacements
// and the replace is performed asynchronously.
// So, just ensure that *something* was opened
expect(DocumentManager.getCurrentDocument().file.fullPath).toBeTruthy();
testFiles.forEach(function (relPath) {
expect(MainViewManager.findInWorkingSet(MainViewManager.ACTIVE_PANE, testPath + relPath)).not.toBe(-1);
});
});
});
it("should select the first modified file in the working set if replacements are done in memory and there were no matches checked for current editor", function () {
openTestProjectCopy(defaultSourcePath);
runs(function () {
waitsForDone(CommandManager.execute(Commands.CMD_ADD_TO_WORKINGSET_AND_OPEN, {fullPath: testPath + "/css/foo.css"}), "open file");
});
doInMemoryTest({
queryInfo: {query: "foo"},
numMatches: 14,
uncheckMatches: [{file: "/css/foo.css"}],
replaceText: "bar",
knownGoodFolder: "unchanged",
forceFilesOpen: true,
inMemoryFiles: ["/foo.html", "/foo.js"],
inMemoryKGFolder: "simple-case-insensitive-except-foo.css"
});
runs(function () {
expect(DocumentManager.getCurrentDocument().file.fullPath).toEqual(testPath + "/foo.html");
});
});
});
describe("UI", function () {
function executeReplace(findText, replaceText, fromKeyboard) {
runs(function () {
FindInFiles._searchDone = false;
FindInFiles._replaceDone = false;
$("#find-what").val(findText).trigger("input");
$("#replace-with").val(replaceText).trigger("input");
if (fromKeyboard) {
SpecRunnerUtils.simulateKeyEvent(KeyEvent.DOM_VK_RETURN, "keydown", $("#replace-with").get(0));
} else {
$("#replace-batch").click();
}
});
}
function showSearchResults(findText, replaceText, fromKeyboard) {
openTestProjectCopy(defaultSourcePath);
openSearchBar(null, true);
executeReplace(findText, replaceText, fromKeyboard);
waitsFor(function () {
return FindInFiles._searchDone;
}, "search finished");
}
afterEach(function () {
closeSearchBar();
});
describe("Replace in Files Bar", function () {
it("should only show a Replace All button", function () {
openTestProjectCopy(defaultSourcePath);
openSearchBar(null, true);
runs(function () {
expect($("#replace-yes").length).toBe(0);