plugins.ts 1.5 KB
Newer Older
E
.  
Eugene Pankov 已提交
1 2
import * as fs from 'fs-promise'
import * as path from 'path'
E
.  
Eugene Pankov 已提交
3 4 5 6 7 8 9 10 11 12 13 14
const nodeModule = (<any>global).require('module')

function normalizePath (path: string): string {
    const cygwinPrefix = '/cygdrive/'
    if (path.startsWith(cygwinPrefix)) {
        path = path.substring(cygwinPrefix.length).replace('/', '\\')
        path = path[0] + ':' + path.substring(1)
    }
    return path
};

(<any>global).require.main.paths.map(x => nodeModule.globalPaths.push(normalizePath(x)))
E
.  
Eugene Pankov 已提交
15 16

if (process.env.TERMINUS_PLUGINS) {
E
.  
Eugene Pankov 已提交
17
    process.env.TERMINUS_PLUGINS.split(':').map(x => nodeModule.globalPaths.unshift(normalizePath(x)))
E
.  
Eugene Pankov 已提交
18 19 20
}

export async function loadPlugins (): Promise<any[]> {
E
.  
Eugene Pankov 已提交
21
    let paths = nodeModule.globalPaths
E
.  
Eugene Pankov 已提交
22 23
    let plugins: any[] = []
    for (let pluginDir of paths) {
E
.  
Eugene Pankov 已提交
24
        pluginDir = normalizePath(pluginDir)
E
.  
Eugene Pankov 已提交
25 26 27 28 29 30
        if (!await fs.exists(pluginDir)) {
            continue
        }
        for (let pluginName of await fs.readdir(pluginDir)) {
            if (/^terminus-/.exec(pluginName)) {
                let pluginPath = path.join(pluginDir, pluginName)
E
.  
Eugene Pankov 已提交
31
                console.info(`Loading ${pluginName}: ${(<any>global).require.resolve(pluginPath)}`)
E
.  
Eugene Pankov 已提交
32
                try {
E
.  
Eugene Pankov 已提交
33
                    let pluginModule = (<any>global).require(pluginPath)
E
.  
Eugene Pankov 已提交
34 35 36 37 38 39 40 41 42
                    plugins.push(pluginModule)
                } catch (error) {
                    console.error(`Could not load ${pluginName}:`, error)
                }
            }
        }
    }
    return plugins
}