import path from "path" ; import nunjucks from "nunjucks" ; import fs from "../utils/fs" ; import Git from "../utils/git" ; import LocationUtils from "../utils/location" ; import PathUtils from "../utils/path" ; param { string } rootFolder param { Function param { Logger } logger const ConrefsLoader = nunjucks . Loader . extend ( { async : true , init : function ( rootFolder , transformFn , logger ) { this . rootFolder = rootFolder ; this . transformFn = transformFn ; this . logger = logger ; this . git = new Git ( ) ; } , getSource : function ( sourceURL , callback ) { const that = this ; this . git . resolve ( sourceURL ) . then ( ( filepath ) => { if ( ! filepath ) { filepath = path . resolve ( sourceURL ) ; } else { if ( that . logger ) that . logger . debug . ln ( "resolve from git" , sourceURL , "to" , filepath ) ; } return fs . readFile ( filepath ) . then ( ( source ) => { source = source . toString ( "utf8" ) ; if ( that . transformFn ) { return that . transformFn ( filepath , source ) ; } return source ; } ) . then ( ( source ) => { return { src : source , path : filepath , } ; } ) ; } ) . nodeify ( callback ) ; } , resolve : function ( from , to ) { if ( PathUtils . isInRoot ( this . rootFolder , from ) ) { const fromRelative = path . relative ( this . rootFolder , from ) ; const href = LocationUtils . toAbsolute ( to , path . dirname ( fromRelative ) , "" ) ; return PathUtils . resolveInRoot ( this . rootFolder , href ) ; } const gitRoot = this . git . resolveRoot ( from ) ; if ( gitRoot ) { return PathUtils . resolveInRoot ( gitRoot , to ) ; } return path . resolve ( path . dirname ( from ) , to ) ; } , isRelative : function ( filename ) { return LocationUtils . isRelative ( filename ) ; } , } ) ; export default ConrefsLoader ;