Debian Codegraph @

closure-library/closure/goog/testing/fs/entry.js

raw
1 // Copyright 2011 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Mock filesystem objects. These are all in the same file to
17 * avoid circular dependency issues.
18 *
19 */
20
21 goog.setTestOnly('goog.testing.fs.DirectoryEntry');
22 goog.provide('goog.testing.fs.DirectoryEntry');
23 goog.provide('goog.testing.fs.Entry');
24 goog.provide('goog.testing.fs.FileEntry');
25
26 goog.require('goog.Timer');
27 goog.require('goog.array');
28 goog.require('goog.asserts');
29 goog.require('goog.async.Deferred');
30 goog.require('goog.fs.DirectoryEntry');
31 goog.require('goog.fs.DirectoryEntryImpl');
32 goog.require('goog.fs.Entry');
33 goog.require('goog.fs.Error');
34 goog.require('goog.fs.FileEntry');
35 goog.require('goog.functions');
36 goog.require('goog.object');
37 goog.require('goog.string');
38 goog.require('goog.testing.fs.File');
39 goog.require('goog.testing.fs.FileWriter');
40
41
42
43 /**
44 * A mock filesystem entry object.
45 *
46 * @param {!goog.testing.fs.FileSystem} fs The filesystem containing this entry.
47 * @param {!goog.testing.fs.DirectoryEntry} parent The directory entry directly
48 * containing this entry.
49 * @param {string} name The name of this entry.
50 * @constructor
51 * @implements {goog.fs.Entry}
52 */
53 goog.testing.fs.Entry = function(fs, parent, name) {
54 /**
55 * This entry's filesystem.
56 * @type {!goog.testing.fs.FileSystem}
57 * @private
58 */
59 this.fs_ = fs;
60
61 /**
62 * The name of this entry.
63 * @type {string}
64 * @private
65 */
66 this.name_ = name;
67
68 /**
69 * The parent of this entry.
70 * @type {!goog.testing.fs.DirectoryEntry}
71 */
72 this.parent = parent;
73 };
74
75
76 /**
77 * Whether or not this entry has been deleted.
78 * @type {boolean}
79 */
80 goog.testing.fs.Entry.prototype.deleted = false;
81
82
83 /** @override */
84 goog.testing.fs.Entry.prototype.isFile = goog.abstractMethod;
85
86
87 /** @override */
88 goog.testing.fs.Entry.prototype.isDirectory = goog.abstractMethod;
89
90
91 /** @override */
92 goog.testing.fs.Entry.prototype.getName = function() {
93 return this.name_;
94 };
95
96
97 /** @override */
98 goog.testing.fs.Entry.prototype.getFullPath = function() {
99 if (this.getName() == '' || this.parent.getName() == '') {
100 // The root directory has an empty name
101 return '/' + this.name_;
102 } else {
103 return this.parent.getFullPath() + '/' + this.name_;
104 }
105 };
106
107
108 /**
109 * @return {!goog.testing.fs.FileSystem}
110 * @override
111 */
112 goog.testing.fs.Entry.prototype.getFileSystem = function() {
113 return this.fs_;
114 };
115
116
117 /** @override */
118 goog.testing.fs.Entry.prototype.getLastModified = goog.abstractMethod;
119
120
121 /** @override */
122 goog.testing.fs.Entry.prototype.getMetadata = goog.abstractMethod;
123
124
125 /** @override */
126 goog.testing.fs.Entry.prototype.moveTo = function(parent, opt_newName) {
127 var msg = 'moving ' + this.getFullPath() + ' into ' + parent.getFullPath() +
128 (opt_newName ? ', renaming to ' + opt_newName : '');
129 var newFile;
130 return this.checkNotDeleted(msg)
131 .addCallback(function() { return this.copyTo(parent, opt_newName); })
132 .addCallback(function(file) {
133 newFile = file;
134 return this.remove();
135 })
136 .addCallback(function() { return newFile; });
137 };
138
139
140 /** @override */
141 goog.testing.fs.Entry.prototype.copyTo = function(parent, opt_newName) {
142 goog.asserts.assert(parent instanceof goog.testing.fs.DirectoryEntry);
143 var msg = 'copying ' + this.getFullPath() + ' into ' + parent.getFullPath() +
144 (opt_newName ? ', renaming to ' + opt_newName : '');
145 var self = this;
146 return this.checkNotDeleted(msg).addCallback(function() {
147 var name = opt_newName || self.getName();
148 var entry = self.clone();
149 /** @type {!goog.testing.fs.DirectoryEntry} */ (parent).children[name] =
150 entry;
151 parent.lastModifiedTimestamp_ = goog.now();
152 entry.name_ = name;
153 entry.parent = /** @type {!goog.testing.fs.DirectoryEntry} */ (parent);
154 return entry;
155 });
156 };
157
158
159 /**
160 * @return {!goog.testing.fs.Entry} A shallow copy of this entry object.
161 */
162 goog.testing.fs.Entry.prototype.clone = goog.abstractMethod;
163
164
165 /** @override */
166 goog.testing.fs.Entry.prototype.toUrl = function(opt_mimetype) {
167 return 'fakefilesystem:' + this.getFullPath();
168 };
169
170
171 /** @override */
172 goog.testing.fs.Entry.prototype.toUri = goog.testing.fs.Entry.prototype.toUrl;
173
174
175 /** @override */
176 goog.testing.fs.Entry.prototype.wrapEntry = goog.abstractMethod;
177
178
179 /** @override */
180 goog.testing.fs.Entry.prototype.remove = function() {
181 var msg = 'removing ' + this.getFullPath();
182 var self = this;
183 return this.checkNotDeleted(msg).addCallback(function() {
184 delete this.parent.children[self.getName()];
185 self.parent.lastModifiedTimestamp_ = goog.now();
186 self.deleted = true;
187 return;
188 });
189 };
190
191
192 /** @override */
193 goog.testing.fs.Entry.prototype.getParent = function() {
194 var msg = 'getting parent of ' + this.getFullPath();
195 return this.checkNotDeleted(msg).addCallback(function() {
196 return this.parent;
197 });
198 };
199
200
201 /**
202 * Return a deferred that will call its errback if this entry has been deleted.
203 * In addition, the deferred will only run after a timeout of 0, and all its
204 * callbacks will run with the entry as "this".
205 *
206 * @param {string} action The name of the action being performed. For error
207 * reporting.
208 * @return {!goog.async.Deferred} The deferred that will be called after a
209 * timeout of 0.
210 * @protected
211 */
212 goog.testing.fs.Entry.prototype.checkNotDeleted = function(action) {
213 var d = new goog.async.Deferred(undefined, this);
214 goog.Timer.callOnce(function() {
215 if (this.deleted) {
216 var err = new goog.fs.Error({'name': 'NotFoundError'}, action);
217 d.errback(err);
218 } else {
219 d.callback();
220 }
221 }, 0, this);
222 return d;
223 };
224
225
226
227 /**
228 * A mock directory entry object.
229 *
230 * @param {!goog.testing.fs.FileSystem} fs The filesystem containing this entry.
231 * @param {goog.testing.fs.DirectoryEntry} parent The directory entry directly
232 * containing this entry. If this is null, that means this is the root
233 * directory and so is its own parent.
234 * @param {string} name The name of this entry.
235 * @param {!Object<!goog.testing.fs.Entry>} children The map of child names to
236 * entry objects.
237 * @constructor
238 * @extends {goog.testing.fs.Entry}
239 * @implements {goog.fs.DirectoryEntry}
240 * @final
241 */
242 goog.testing.fs.DirectoryEntry = function(fs, parent, name, children) {
243 goog.testing.fs.DirectoryEntry.base(
244 this, 'constructor', fs, parent || this, name);
245
246 /**
247 * The map of child names to entry objects.
248 * @type {!Object<!goog.testing.fs.Entry>}
249 */
250 this.children = children;
251
252 /**
253 * The modification time of the directory. Measured using goog.now, which may
254 * be overridden with mock time providers.
255 * @type {number}
256 * @private
257 */
258 this.lastModifiedTimestamp_ = goog.now();
259 };
260 goog.inherits(goog.testing.fs.DirectoryEntry, goog.testing.fs.Entry);
261
262
263 /**
264 * Constructs and returns the metadata object for this entry.
265 * @return {{modificationTime: Date}} The metadata object.
266 * @private
267 */
268 goog.testing.fs.DirectoryEntry.prototype.getMetadata_ = function() {
269 return {'modificationTime': new Date(this.lastModifiedTimestamp_)};
270 };
271
272
273 /** @override */
274 goog.testing.fs.DirectoryEntry.prototype.isFile = function() {
275 return false;
276 };
277
278
279 /** @override */
280 goog.testing.fs.DirectoryEntry.prototype.isDirectory = function() {
281 return true;
282 };
283
284
285 /** @override */
286 goog.testing.fs.DirectoryEntry.prototype.getLastModified = function() {
287 var msg = 'reading last modified date for ' + this.getFullPath();
288 return this.checkNotDeleted(msg).addCallback(function() {
289 return new Date(this.lastModifiedTimestamp_)
290 });
291 };
292
293
294 /** @override */
295 goog.testing.fs.DirectoryEntry.prototype.getMetadata = function() {
296 var msg = 'reading metadata for ' + this.getFullPath();
297 return this.checkNotDeleted(msg).addCallback(function() {
298 return this.getMetadata_()
299 });
300 };
301
302
303 /** @override */
304 goog.testing.fs.DirectoryEntry.prototype.clone = function() {
305 return new goog.testing.fs.DirectoryEntry(
306 this.getFileSystem(), this.parent, this.getName(), this.children);
307 };
308
309
310 /** @override */
311 goog.testing.fs.DirectoryEntry.prototype.remove = function() {
312 if (!goog.object.isEmpty(this.children)) {
313 var d = new goog.async.Deferred();
314 goog.Timer.callOnce(function() {
315 d.errback(new goog.fs.Error(
316 {'name': 'InvalidModificationError'},
317 'removing ' + this.getFullPath()));
318 }, 0, this);
319 return d;
320 } else if (this != this.getFileSystem().getRoot()) {
321 return goog.testing.fs.DirectoryEntry.base(this, 'remove');
322 } else {
323 // Root directory, do nothing.
324 return goog.async.Deferred.succeed();
325 }
326 };
327
328
329 /** @override */
330 goog.testing.fs.DirectoryEntry.prototype.getFile = function(
331 path, opt_behavior) {
332 var msg = 'loading file ' + path + ' from ' + this.getFullPath();
333 opt_behavior = opt_behavior || goog.fs.DirectoryEntry.Behavior.DEFAULT;
334 return this.checkNotDeleted(msg).addCallback(function() {
335 try {
336 return goog.async.Deferred.succeed(this.getFileSync(path, opt_behavior));
337 } catch (e) {
338 return goog.async.Deferred.fail(e);
339 }
340 });
341 };
342
343
344 /** @override */
345 goog.testing.fs.DirectoryEntry.prototype.getDirectory = function(
346 path, opt_behavior) {
347 var msg = 'loading directory ' + path + ' from ' + this.getFullPath();
348 opt_behavior = opt_behavior || goog.fs.DirectoryEntry.Behavior.DEFAULT;
349 return this.checkNotDeleted(msg).addCallback(function() {
350 try {
351 return goog.async.Deferred.succeed(
352 this.getDirectorySync(path, opt_behavior));
353 } catch (e) {
354 return goog.async.Deferred.fail(e);
355 }
356 });
357 };
358
359
360 /**
361 * Get a file entry synchronously, without waiting for a Deferred to resolve.
362 *
363 * @param {string} path The path to the file, relative to this directory.
364 * @param {goog.fs.DirectoryEntry.Behavior=} opt_behavior The behavior for
365 * loading the file.
366 * @param {string=} opt_data The string data encapsulated by the blob.
367 * @param {string=} opt_type The mime type of the blob.
368 * @return {!goog.testing.fs.FileEntry} The loaded file.
369 */
370 goog.testing.fs.DirectoryEntry.prototype.getFileSync = function(
371 path, opt_behavior, opt_data, opt_type) {
372 opt_behavior = opt_behavior || goog.fs.DirectoryEntry.Behavior.DEFAULT;
373 return (
374 /** @type {!goog.testing.fs.FileEntry} */ (
375 this.getEntry_(
376 path, opt_behavior, true /* isFile */,
377 goog.bind(function(parent, name) {
378 return new goog.testing.fs.FileEntry(
379 this.getFileSystem(), parent, name,
380 goog.isDef(opt_data) ? opt_data : '', opt_type);
381 }, this))));
382 };
383
384
385 /**
386 * Creates a file synchronously. This is a shorthand for getFileSync, useful for
387 * setting up tests.
388 *
389 * @param {string} path The path to the file, relative to this directory.
390 * @return {!goog.testing.fs.FileEntry} The created file.
391 */
392 goog.testing.fs.DirectoryEntry.prototype.createFileSync = function(path) {
393 return this.getFileSync(path, goog.fs.DirectoryEntry.Behavior.CREATE);
394 };
395
396
397 /**
398 * Get a directory synchronously, without waiting for a Deferred to resolve.
399 *
400 * @param {string} path The path to the directory, relative to this one.
401 * @param {goog.fs.DirectoryEntry.Behavior=} opt_behavior The behavior for
402 * loading the directory.
403 * @return {!goog.testing.fs.DirectoryEntry} The loaded directory.
404 */
405 goog.testing.fs.DirectoryEntry.prototype.getDirectorySync = function(
406 path, opt_behavior) {
407 opt_behavior = opt_behavior || goog.fs.DirectoryEntry.Behavior.DEFAULT;
408 return (
409 /** @type {!goog.testing.fs.DirectoryEntry} */ (
410 this.getEntry_(
411 path, opt_behavior, false /* isFile */,
412 goog.bind(function(parent, name) {
413 return new goog.testing.fs.DirectoryEntry(
414 this.getFileSystem(), parent, name, {});
415 }, this))));
416 };
417
418
419 /**
420 * Creates a directory synchronously. This is a shorthand for getFileSync,
421 * useful for setting up tests.
422 *
423 * @param {string} path The path to the directory, relative to this directory.
424 * @return {!goog.testing.fs.DirectoryEntry} The created directory.
425 */
426 goog.testing.fs.DirectoryEntry.prototype.createDirectorySync = function(path) {
427 return this.getDirectorySync(path, goog.fs.DirectoryEntry.Behavior.CREATE);
428 };
429
430
431 /**
432 * Get a file or directory entry from a path. This handles parsing the path for
433 * subdirectories and throwing appropriate errors should something go wrong.
434 *
435 * @param {string} path The path to the entry, relative to this directory.
436 * @param {goog.fs.DirectoryEntry.Behavior} behavior The behavior for loading
437 * the entry.
438 * @param {boolean} isFile Whether a file or directory is being loaded.
439 * @param {function(!goog.testing.fs.DirectoryEntry, string) :
440 * !goog.testing.fs.Entry} createFn
441 * The function for creating the entry if it doesn't yet exist. This is
442 * passed the parent entry and the name of the new entry.
443 * @return {!goog.testing.fs.Entry} The loaded entry.
444 * @private
445 */
446 goog.testing.fs.DirectoryEntry.prototype.getEntry_ = function(
447 path, behavior, isFile, createFn) {
448 // Filter out leading, trailing, and duplicate slashes.
449 var components = goog.array.filter(path.split('/'), goog.functions.identity);
450
451 var basename = /** @type {string} */ (goog.array.peek(components)) || '';
452 var dir =
453 goog.string.startsWith(path, '/') ? this.getFileSystem().getRoot() : this;
454
455 goog.array.forEach(components.slice(0, -1), function(p) {
456 var subdir = dir.children[p];
457 if (!subdir) {
458 throw new goog.fs.Error(
459 {'name': 'NotFoundError'},
460 'loading ' + path + ' from ' + this.getFullPath() + ' (directory ' +
461 dir.getFullPath() + '/' + p + ')');
462 }
463 dir = subdir;
464 }, this);
465
466 // If there is no basename, the path must resolve to the root directory.
467 var entry = basename ? dir.children[basename] : dir;
468
469 if (!entry) {
470 if (behavior == goog.fs.DirectoryEntry.Behavior.DEFAULT) {
471 throw new goog.fs.Error(
472 {'name': 'NotFoundError'},
473 'loading ' + path + ' from ' + this.getFullPath());
474 } else {
475 goog.asserts.assert(
476 behavior == goog.fs.DirectoryEntry.Behavior.CREATE ||
477 behavior == goog.fs.DirectoryEntry.Behavior.CREATE_EXCLUSIVE);
478 entry = createFn(dir, basename);
479 dir.children[basename] = entry;
480 this.lastModifiedTimestamp_ = goog.now();
481 return entry;
482 }
483 } else if (behavior == goog.fs.DirectoryEntry.Behavior.CREATE_EXCLUSIVE) {
484 throw new goog.fs.Error(
485 {'name': 'InvalidModificationError'},
486 'loading ' + path + ' from ' + this.getFullPath());
487 } else if (entry.isFile() != isFile) {
488 throw new goog.fs.Error(
489 {'name': 'TypeMismatchError'},
490 'loading ' + path + ' from ' + this.getFullPath());
491 } else {
492 if (behavior == goog.fs.DirectoryEntry.Behavior.CREATE) {
493 this.lastModifiedTimestamp_ = goog.now();
494 }
495 return entry;
496 }
497 };
498
499
500 /**
501 * Returns whether this directory has a child with the given name.
502 *
503 * @param {string} name The name of the entry to check for.
504 * @return {boolean} Whether or not this has a child with the given name.
505 */
506 goog.testing.fs.DirectoryEntry.prototype.hasChild = function(name) {
507 return name in this.children;
508 };
509
510
511 /** @override */
512 goog.testing.fs.DirectoryEntry.prototype.removeRecursively = function() {
513 var msg = 'removing ' + this.getFullPath() + ' recursively';
514 return this.checkNotDeleted(msg).addCallback(function() {
515 var d = goog.async.Deferred.succeed(null);
516 goog.object.forEach(this.children, function(child) {
517 d.awaitDeferred(
518 child.isDirectory() ? child.removeRecursively() : child.remove());
519 });
520 d.addCallback(function() { return this.remove(); }, this);
521 return d;
522 });
523 };
524
525
526 /** @override */
527 goog.testing.fs.DirectoryEntry.prototype.listDirectory = function() {
528 var msg = 'listing ' + this.getFullPath();
529 return this.checkNotDeleted(msg).addCallback(function() {
530 return goog.object.getValues(this.children);
531 });
532 };
533
534
535 /** @override */
536 goog.testing.fs.DirectoryEntry.prototype.createPath =
537 // This isn't really type-safe.
538 /** @type {!Function} */ (goog.fs.DirectoryEntryImpl.prototype.createPath);
539
540
541
542 /**
543 * A mock file entry object.
544 *
545 * @param {!goog.testing.fs.FileSystem} fs The filesystem containing this entry.
546 * @param {!goog.testing.fs.DirectoryEntry} parent The directory entry directly
547 * containing this entry.
548 * @param {string} name The name of this entry.
549 * @param {string} data The data initially contained in the file.
550 * @param {string=} opt_type The mime type of the blob.
551 * @constructor
552 * @extends {goog.testing.fs.Entry}
553 * @implements {goog.fs.FileEntry}
554 * @final
555 */
556 goog.testing.fs.FileEntry = function(fs, parent, name, data, opt_type) {
557 goog.testing.fs.FileEntry.base(this, 'constructor', fs, parent, name);
558
559 /**
560 * The internal file blob referenced by this file entry.
561 * @type {!goog.testing.fs.File}
562 * @private
563 */
564 this.file_ =
565 new goog.testing.fs.File(name, new Date(goog.now()), data, opt_type);
566
567 /**
568 * The metadata for file.
569 * @type {{modificationTime: Date}}
570 * @private
571 */
572 this.metadata_ = {'modificationTime': this.file_.lastModifiedDate};
573 };
574 goog.inherits(goog.testing.fs.FileEntry, goog.testing.fs.Entry);
575
576
577 /** @override */
578 goog.testing.fs.FileEntry.prototype.isFile = function() {
579 return true;
580 };
581
582
583 /** @override */
584 goog.testing.fs.FileEntry.prototype.isDirectory = function() {
585 return false;
586 };
587
588
589 /** @override */
590 goog.testing.fs.FileEntry.prototype.clone = function() {
591 return new goog.testing.fs.FileEntry(
592 this.getFileSystem(), this.parent, this.getName(),
593 this.fileSync().toString());
594 };
595
596
597 /** @override */
598 goog.testing.fs.FileEntry.prototype.getLastModified = function() {
599 return this.file().addCallback(function(file) {
600 return file.lastModifiedDate;
601 });
602 };
603
604
605 /** @override */
606 goog.testing.fs.FileEntry.prototype.getMetadata = function() {
607 var msg = 'getting metadata for ' + this.getFullPath();
608 return this.checkNotDeleted(msg).addCallback(function() {
609 return this.metadata_;
610 });
611 };
612
613
614 /** @override */
615 goog.testing.fs.FileEntry.prototype.createWriter = function() {
616 var d = new goog.async.Deferred();
617 goog.Timer.callOnce(
618 goog.bind(d.callback, d, new goog.testing.fs.FileWriter(this)));
619 return d;
620 };
621
622
623 /** @override */
624 goog.testing.fs.FileEntry.prototype.file = function() {
625 var msg = 'getting file for ' + this.getFullPath();
626 return this.checkNotDeleted(msg).addCallback(function() {
627 return this.fileSync();
628 });
629 };
630
631
632 /**
633 * Get the internal file representation synchronously, without waiting for a
634 * Deferred to resolve.
635 *
636 * @return {!goog.testing.fs.File} The internal file blob referenced by this
637 * FileEntry.
638 */
639 goog.testing.fs.FileEntry.prototype.fileSync = function() {
640 return this.file_;
641 };