-
Notifications
You must be signed in to change notification settings - Fork 7
/
macro.js
executable file
·62 lines (51 loc) · 1.57 KB
/
macro.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
const path = require('path');
const fs = require('fs');
const findRoot = require('find-root');
const { createMacro } = require('babel-plugin-macros');
const { toUnix } = require('upath');
const getPaths = f => {
const _osDependentAbsolute = path.resolve(f);
const _fileAbsolute = toUnix(_osDependentAbsolute);
const _file = path.basename(_fileAbsolute);
const _extension = path.extname(_fileAbsolute);
const _filename = _file.replace(_extension, '');
const _npmRoot = toUnix(findRootAttempt(_osDependentAbsolute));
const _gitRoot = toUnix(
findRootAttempt(_osDependentAbsolute, dir =>
fs.existsSync(path.resolve(dir, '.git')),
),
);
const _wd = toUnix(process.cwd());
const _baseAbsolute = _fileAbsolute.replace(_file, '');
const _base = _baseAbsolute.replace(_npmRoot, '');
return {
npmRoot: _npmRoot,
gitRoot: _gitRoot,
wd: _wd,
fileAbsolute: _fileAbsolute,
file: _file,
extension: _extension,
filename: _filename,
baseAbsolute: _baseAbsolute,
base: _base,
default: _base,
};
};
const findRootAttempt = (...params) => {
try {
return path.resolve(findRoot(...params));
} catch (error) {
return '';
}
};
const macro = ({ references, state }) => {
const paths = getPaths(state.file.opts.filename);
Object.keys(paths).forEach(key => {
const value = (key === 'default' ? paths['base'] : paths[key]) || '';
const list = references[key] || [];
list.forEach(reference => {
reference.replaceWithSourceString(JSON.stringify(value));
});
});
};
module.exports = createMacro(macro);