forked from fex-team/fis-kernel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuri.js
110 lines (102 loc) · 3.08 KB
/
uri.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
* fis
* http://fis.baidu.com/
*/
'use strict';
function replaceDefine(value, escape){
return value.replace(/\$\{([^\}]+)\}/g, function(all, $1){
var val = fis.config.get($1);
if(typeof val === 'undefined'){
fis.log.error('undefined property [' + $1 + '].');
} else {
return escape ? fis.util.escapeReg(val) : val;
}
return all;
});
}
function replaceMatches(value, matches){
return value.replace(/\$(\d+|&)/g, function(all, $1){
return matches[$1 === '&' ? '0' : $1] || all;
});
}
function replaceProperties(source, matches, target){
var type = typeof source;
if(type === 'object'){
if(fis.util.is(source, 'Array')){
target = target || [];
} else {
target = target || {};
}
fis.util.map(source, function(key, value){
target[key] = replaceProperties(value, matches);
});
return target;
} else if(type === 'string'){
return replaceDefine(replaceMatches(source, matches));
// TODO support function type
// } else if(type === 'function'){
// return source(subpath || target.subpath, matches);
} else {
return source;
}
}
function roadmap(subpath, path, obj){
var map = fis.config.get('roadmap.' + path, []);
for(var i = 0, len = map.length; i < len; i++){
var opt = map[i], reg = opt.reg;
if(reg){
if(typeof reg === 'string'){
reg = fis.util.glob(replaceDefine(reg, true));
} else if(!fis.util.is(reg, 'RegExp')){
fis.log.error('invalid regexp [' + reg + '] of [roadmap.' + path + '.' + i + ']');
}
var matches = subpath.match(reg);
if(matches){
obj = obj || {};
replaceProperties(opt, matches, obj);
delete obj.reg;
return obj;
}
} else {
fis.log.error('[roadmap.' + path + '.' + i + '] missing property [reg].');
}
}
return false;
}
var uri = module.exports = function(path, dirname){
var info = fis.util.stringQuote(path),
qInfo = fis.util.query(info.rest);
info.query = qInfo.query;
info.hash = qInfo.hash;
info.rest = qInfo.rest;
if(info.rest){
path = info.rest;
if(path.indexOf(':') === -1){
var file;
if(path[0] === '/'){
file = fis.project.getProjectPath(path);
} else if(dirname) {
file = fis.util(dirname, path);
} else {
fis.log.error('invalid dirname.');
}
if(file && fis.util.isFile(file)){
info.file = fis.file(file);
}
}
}
return info;
};
uri.getId = function(path, dirname){
var info = uri(path, dirname);
if(info.file){
info.id = info.file.getId();
} else {
info.id = info.rest;
}
return info;
};
uri.replaceDefine = replaceDefine;
uri.replaceMatches = replaceMatches;
uri.replaceProperties = replaceProperties;
uri.roadmap = roadmap;