summaryrefslogtreecommitdiffstats
path: root/lib/fs/mock.js
blob: 784c5333a2668f11761d91cbf62d6bd9a6cd9b19 (plain)
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
var path = require('path');
var is = require('is');
var Buffer = require('buffer').Buffer;
var Immutable = require('immutable');

var FS = require('../models/fs');
var error = require('../utils/error');

/**
    Create a fake filesystem for unit testing GitBook.

    @param {Map<String:String|Map>}
*/
function createMockFS(files) {
    files = Immutable.fromJS(files);
    var mtime = new Date();

    function getFile(filePath) {
        var parts = path.normalize(filePath).split(path.sep);
        return parts.reduce(function(list, part, i) {
            if (!list) return null;

            var file;

            if (!part || part === '.') file = list;
            else file = list.get(part);

            if (!file) return null;

            if (is.string(file)) {
                if (i === (parts.length - 1)) return file;
                else return null;
            }

            return file;
        }, files);
    }

    function fsExists(filePath) {
        return Boolean(getFile(filePath) !== null);
    }

    function fsReadFile(filePath) {
        var file = getFile(filePath);
        if (!is.string(file)) {
            throw error.FileNotFoundError({
                filename: filePath
            });
        }

        return new Buffer(file, 'utf8');
    }

    function fsStatFile(filePath) {
        var file = getFile(filePath);
        if (!file) {
            throw error.FileNotFoundError({
                filename: filePath
            });
        }

        return {
            mtime: mtime
        };
    }

    function fsReadDir(filePath) {
        var dir = getFile(filePath);
        if (!dir || is.string(dir)) {
            throw error.FileNotFoundError({
                filename: filePath
            });
        }

        return dir
            .map(function(content, name) {
                if (!is.string(content)) {
                    name = name + '/';
                }

                return name;
            })
            .valueSeq();
    }

    return FS.create({
        root: '',
        fsExists: fsExists,
        fsReadFile: fsReadFile,
        fsStatFile: fsStatFile,
        fsReadDir: fsReadDir
    });
}

module.exports = createMockFS;