-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (68 loc) · 1.87 KB
/
index.js
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
/*!
* parse-github-url <https://github.com/jonschlinkert/parse-github-url>
*
* Copyright (c) 2015-2017, Jon Schlinkert.
* Released under the MIT License.
*/
'use strict';
var url = require('url');
var cache = {};
module.exports = function parseGithubUrl(str) {
return cache[str] || (cache[str] = parse(str));
};
function parse(str) {
if (typeof str !== 'string' || !str.length) {
return null;
}
if (str.indexOf('git@gist') !== -1 || str.indexOf('//gist') !== -1) {
return null;
}
// parse the URL
var obj = url.parse(str);
if (typeof obj.path !== 'string' || !obj.path.length || typeof obj.pathname !== 'string' || !obj.pathname.length) {
return null;
}
if (!obj.host && /^git@/.test(str) === true) {
// return the correct host for git@ URLs
obj.host = url.parse('http://' + str).host;
}
obj.path = trimSlash(obj.path);
obj.pathname = trimSlash(obj.pathname);
obj.filepath = null;
if (obj.path.indexOf('repos') === 0) {
obj.path = obj.path.slice(6);
}
var seg = obj.path.split('/').filter(Boolean);
obj.owner = owner(seg[0]);
obj.name = name(seg[1]);
if (!obj.owner || !obj.name) {
return null;
}
if (seg[2] === 'tree') {
// with branch
obj.branchAndDirectory = seg.slice(3)
} else if (seg[2]) {
// fallback to url without /tree/
// todo: do we need it?
obj.branchAndDirectory = seg.slice(2)
} else if (obj.hash) {
// older format, allows proto://host/owner/repo#branch
obj.branchAndDirectory = obj.hash.slice(1).split('/')
}
obj.host = obj.host || 'github.com';
return obj;
}
function trimSlash(path) {
return path.charAt(0) === '/' ? path.slice(1) : path;
}
function name(str) {
return str ? str.replace(/^\W+|\.git$/g, '') : null;
}
function owner(str) {
if (!str) return null;
var idx = str.indexOf(':');
if (idx > -1) {
return str.slice(idx + 1);
}
return str;
}