summaryrefslogtreecommitdiffstats
path: root/bin/utils.js
blob: 45bc7d57a939d7ddac4410f1d37bd8327452f532 (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
96
var Q = require('q');
var _ = require('lodash');

var http = require('http');
var send = require('send');

var cp = require('child_process');
var path = require('path');
var url = require('url');

var Gaze = require('gaze').Gaze;


// Get the remote of a given repo
function gitURL(path) {
    var d = Q.defer();

    cp.exec("git config --get remote.origin.url", {
        cwd: path,
        env: process.env,
    }, function(err, stdout, stderr) {
        if(err) {
            return d.reject(err);
        }

        return d.resolve(stdout);
    });

    return d.promise
    .then(function(output) {
        return output.replace(/(\r\n|\n|\r)/gm, "");
    });
}

// Poorman's parsing
// Parse a git URL to a github ID : username/reponame
function githubID(_url) {
    // Remove .git if it's in _url
    var sliceEnd = _url.slice(-4) === '.git' ? -4 : _url.length;

    // Detect HTTPS repos
    var parsed = url.parse(_url);
    if(parsed.protocol === 'https:' && parsed.host === 'github.com') {
        return parsed.path.slice(1, sliceEnd);
    }

    // Detect SSH repos
    if(_url.indexOf('git@') === 0) {
        return _url.split(':', 2)[1].slice(0, sliceEnd);
    }

    // None found
    return null;
}

function titleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

function watch(dir) {
    var d = Q.defer();
    dir = path.resolve(dir);

    var gaze = new Gaze("**/*.md", {
        cwd: dir
    });

    gaze.once("all", function(e, filepath) {
        gaze.close();

        d.resolve(filepath);
    });
    gaze.once("error", function(err) {
        gaze.close();

        d.reject(err);
    });

    return d.promise;
}

function logError(err) {
    console.log(err.stack || err.message || err);
    return Q.reject(err);
};


// Exports
module.exports = {
    gitURL: gitURL,
    githubID: githubID,
    titleCase: titleCase,
    watch: watch,
    logError: logError
};