import { Document } from "../models" ; import { logger } from "." ; import * as yaml from 'js-yaml' ; import * as fs from 'fs' ; import * as extend from 'extend' ; param { Document } document param { string [ ] } activeProfiles returns { boolean } export const shouldUseDocument = ( document , activeProfiles ? ) : boolean => { let useThisDoc = false ; if ( document && ! document . profiles ) { useThisDoc = true ; } else if ( document && activeProfiles ) { const documentProfiles = document . profiles . split ( "," ) ; for ( let i = 0 ; i < documentProfiles . length ; i ++ ) { if ( documentProfiles [ i ] [ 0 ] === "!" ) { const excludedProfile = documentProfiles [ i ] . substring ( 1 ) ; if ( activeProfiles . indexOf ( excludedProfile ) >= 0 ) { return false ; } } else if ( activeProfiles . indexOf ( documentProfiles [ i ] ) >= 0 ) { useThisDoc = true ; } } } return useThisDoc ; } ; param { string } relativePath param { string [ ] } activeProfiles returns { Document } export const readYaml = ( relativePath , activeProfiles ? ) : Document => { logger . debug ( 'loading config file from: ' + relativePath ) ; let doc = { } ; yaml . safeLoadAll ( fs . readFileSync ( relativePath , 'utf8' ) , ( thisDoc ) => { if ( shouldUseDocument ( thisDoc , activeProfiles ) ) { extend ( true , doc , thisDoc ) ; } } ) ; return doc ; } ; param { string [ ] } propertyKeys param { * } propertyValue returns { any } export const createObjectForProperty = ( propertyKeys , propertyValue ) : any => { const thisPropertyName = propertyKeys . shift ( ) ; if ( thisPropertyName === undefined ) { return propertyValue ; } const thisPropertyValue = createObjectForProperty ( propertyKeys , propertyValue ) ; var thisObject = { } ; thisObject [ thisPropertyName ] = thisPropertyValue ; return thisObject ; } ; param { object } propertiesObject returns { object } export const parsePropertiesToObjects = ( propertiesObject ) : object => { var object = { } ; if ( propertiesObject ) { for ( let thisPropertyName in propertiesObject ) { const thisPropertyObject = createObjectForProperty ( thisPropertyName . split ( '.' ) , propertiesObject [ thisPropertyName ] ) ; extend ( true , object , thisPropertyObject ) ; } } return object ; } ; param { string } relativePath param { string [ ] } activeProfiles returns { Document } export const readYamlAsDocument = ( relativePath , activeProfiles ) : Document => { return parsePropertiesToObjects ( readYaml ( relativePath , activeProfiles ) ) ; } ; param { object [ ] } objects returns { object } export const mergeProperties = ( objects ) : object => { var mergedConfig = { } ; for ( var i = 0 ; i < objects . length ; i ++ ) { extend ( true , mergedConfig , objects [ i ] ) ; } return mergedConfig ; } ;