summaryrefslogtreecommitdiffstats
path: root/lib/templating/conrefsLoader.js
blob: cdf0c304cbedbd9719e533733d4445075680507d (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
var path = require('path');
var nunjucks = require('nunjucks');

var fs = require('../utils/fs');
var Git = require('../utils/git');
var LocationUtils = require('../utils/location');
var PathUtils = require('../utils/path');


/**
    Template loader resolving both:
        - relative url ("./test.md")
        - absolute url ("/test.md")
        - git url ("")


    @param {String} rootFolder
    @param {Function(filePath, source)} transformFn (optional)
    @param {Logger} logger (optional)
*/
var ConrefsLoader = nunjucks.Loader.extend({
    async: true,

    init: function(rootFolder, transformFn, logger) {
        this.rootFolder = rootFolder;
        this.transformFn = transformFn;
        this.logger = logger;
        this.git = new Git();
    },

    getSource: function(sourceURL, callback) {
        var that = this;

        this.git.resolve(sourceURL)
        .then(function(filepath) {
            // Is local file
            if (!filepath) {
                filepath = path.resolve(sourceURL);
            } else {
                if (that.logger) that.logger.debug.ln('resolve from git', sourceURL, 'to', filepath);
            }

            // Read file from absolute path
            return fs.readFile(filepath)
            .then(function(source) {
                if (that.transformFn) {
                    return that.transformFn(filepath, source);
                }

                return source;
            })
            .then(function(source) {
                return {
                    src: source.toString('utf8'),
                    path: filepath
                };
            });
        })
        .nodeify(callback);
    },

    resolve: function(from, to) {
        // If origin is in the book, we enforce result file to be in the book
        if (PathUtils.isInRoot(this.rootFolder, from)) {
            var href = LocationUtils.toAbsolute(to, path.dirname(from), '');
            return PathUtils.resolveInRoot(this.rootFolder, href);
        }

        // If origin is in a git repository, we resolve file in the git repository
        var gitRoot = this.git.resolveRoot(from);
        if (gitRoot) {
            return PathUtils.resolveInRoot(gitRoot, to);
        }

        // If origin is not in the book (include from a git content ref)
        return path.resolve(path.dirname(from), to);
    },

    // Handle all files as relative, so that nunjucks pass responsability to 'resolve'
    isRelative: function(filename) {
        return LocationUtils.isRelative(filename);
    }
});

module.exports = ConrefsLoader;