summaryrefslogtreecommitdiffstats
path: root/packages/gitbook-core/src/models/File.js
blob: 74db11e1e89f0116504442d7239ccebd7f16c76b (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
const path = require('path');
const { Record } = require('immutable');

const DEFAULTS = {
    type:  '',
    mtime: new Date(),
    path:  '',
    url:   ''
};

class File extends Record(DEFAULTS) {
    constructor(file = {}) {
        if (typeof file === 'string') {
            file = { path: file, url: file };
        }

        super({
            ...file,
            mtime: new Date(file.mtime)
        });
    }

    /**
     * Returns the relative path from this file to "to"
     * @param {String} to
     * @return {String}
     */
    relative(to) {
        return path.relative(
            path.dirname(this.path),
            to
        ) || './';
    }

    /**
     * Return true if file is an instance of File
     * @param {Mixed} file
     * @return {Boolean}
     */
    static is(file) {
        return (file instanceof File);
    }

    /**
     * Create a file instance
     * @param {Mixed|File} file
     * @return {File}
     */
    static create(file) {
        return File.is(file) ?
            file : new File(file);
    }
}

module.exports = File;