Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a startup configuration file for flowr #651

Merged
merged 16 commits into from
Feb 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import type {MergeableRecord} from './util/objects'
import {deepMergeObject} from './util/objects'
import path from 'path'
import fs from 'fs'
import {log} from './util/log'
import {getParentDirectory} from './util/files'
import Joi from 'joi'

export interface FlowrConfigOptions extends MergeableRecord {
/**
* Whether source calls should be ignored, causing {@link processSourceCall}'s behavior to be skipped
*/
ignoreSourceCalls: boolean
Ellpeck marked this conversation as resolved.
Show resolved Hide resolved
}

export const defaultConfigOptions: FlowrConfigOptions = {
ignoreSourceCalls: false
}
export const defaultConfigFile = 'flowr.json'

const schema = Joi.object({
ignoreSourceCalls: Joi.boolean().optional()
})

let configWorkingDirectory = process.cwd()
let configFile = defaultConfigFile
let currentConfig: FlowrConfigOptions | undefined

export function setConfigFile(workingDirectory = process.cwd(), file = defaultConfigFile, forceLoad = false) {
configWorkingDirectory = workingDirectory
configFile = file

Check warning on line 31 in src/config.ts

View check run for this annotation

Codecov / codecov/patch

src/config.ts#L30-L31

Added lines #L30 - L31 were not covered by tests

// reset the config so it gets reloaded
currentConfig = undefined

Check warning on line 34 in src/config.ts

View check run for this annotation

Codecov / codecov/patch

src/config.ts#L34

Added line #L34 was not covered by tests
if(forceLoad) {
getConfig()

Check warning on line 36 in src/config.ts

View check run for this annotation

Codecov / codecov/patch

src/config.ts#L36

Added line #L36 was not covered by tests
}
}

export function setConfig(config: FlowrConfigOptions) {
currentConfig = config
}

export function getConfig(): FlowrConfigOptions {
Ellpeck marked this conversation as resolved.
Show resolved Hide resolved
// lazy-load the config based on the current settings
if(currentConfig === undefined) {
setConfig(parseConfigOptions(configWorkingDirectory, configFile))
}
return currentConfig as FlowrConfigOptions
}

function parseConfigOptions(workingDirectory: string, configFile: string): FlowrConfigOptions {
let searchPath = path.resolve(workingDirectory)
do{
const configPath = path.join(searchPath, configFile)
if(fs.existsSync(configPath)) {
try {
const text = fs.readFileSync(configPath,{encoding: 'utf-8'})
const parsed = JSON.parse(text) as FlowrConfigOptions
const validate = schema.validate(parsed)

Check warning on line 60 in src/config.ts

View check run for this annotation

Codecov / codecov/patch

src/config.ts#L57-L60

Added lines #L57 - L60 were not covered by tests
if(!validate.error) {
// assign default values to all config options except for the specified ones
const ret = deepMergeObject(defaultConfigOptions, parsed)
log.info(`Using config ${JSON.stringify(ret)} from ${configPath}`)
return ret

Check warning on line 65 in src/config.ts

View check run for this annotation

Codecov / codecov/patch

src/config.ts#L63-L65

Added lines #L63 - L65 were not covered by tests
} else {
log.error(`Failed to validate config file at ${configPath}: ${validate.error.message}`)

Check warning on line 67 in src/config.ts

View check run for this annotation

Codecov / codecov/patch

src/config.ts#L67

Added line #L67 was not covered by tests
}
} catch(e) {
log.error(`Failed to parse config file at ${configPath}: ${(e as Error).message}`)

Check warning on line 70 in src/config.ts

View check run for this annotation

Codecov / codecov/patch

src/config.ts#L70

Added line #L70 was not covered by tests
}
}
// move up to parent directory
searchPath = getParentDirectory(searchPath)
} while(fs.existsSync(searchPath))

log.info(`Using default config ${JSON.stringify(defaultConfigOptions)}`)
return defaultConfigOptions
}
7 changes: 7 additions & 0 deletions src/dataflow/internal/process/functions/source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import {type DataflowScopeName, type Identifier, overwriteEnvironments, type REnvironmentInformation, resolveByName} from '../../../environments'
import type {DataflowInformation} from '../../info'
import {dataflowLogger} from '../../../index'
import {getConfig} from '../../../../config'

let sourceProvider = requestProviderFromFile()

Expand All @@ -31,6 +32,12 @@

export function processSourceCall<OtherInfo>(functionCall: RFunctionCall<OtherInfo & ParentInformation>, data: DataflowProcessorInformation<OtherInfo & ParentInformation>, information: DataflowInformation): DataflowInformation {
const sourceFile = functionCall.arguments[0] as RArgument<ParentInformation> | undefined

if(getConfig().ignoreSourceCalls) {
dataflowLogger.info(`Skipping source call ${JSON.stringify(sourceFile)} (disabled in config file)`)
return information

Check warning on line 38 in src/dataflow/internal/process/functions/source.ts

View check run for this annotation

Codecov / codecov/patch

src/dataflow/internal/process/functions/source.ts#L37-L38

Added lines #L37 - L38 were not covered by tests
}

if(sourceFile?.value?.type == RType.String) {
const path = removeTokenMapQuotationMarks(sourceFile.lexeme)
const request = sourceProvider.createRequest(path)
Expand Down
22 changes: 13 additions & 9 deletions src/flowr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { FlowRServer } from './cli/repl/server/server'
import { standardReplOutput } from './cli/repl/commands'
import type { Server} from './cli/repl/server/net'
import {NetServer, WebSocketServerWrapper} from './cli/repl/server/net'
import {defaultConfigFile, setConfigFile} from './config'

const scriptsText = Array.from(Object.entries(scripts).filter(([, {type}]) => type === 'master script'), ([k,]) => k).join(', ')

Expand All @@ -36,18 +37,20 @@ export const optionDefinitions: OptionDefinition[] = [
{ name: 'execute', alias: 'e', type: String, description: 'Execute the given command and exit. Use a semicolon ";" to separate multiple commands.', typeLabel: '{underline command}', multiple: false },
{ name: 'no-ansi', type: Boolean, description: 'Disable ansi-escape-sequences in the output. Useful, if you want to redirect the output to a file.'},
{ name: 'script', alias: 's', type: String, description: `The sub-script to run (${scriptsText})`, multiple: false, defaultOption: true, typeLabel: '{underline files}', defaultValue: undefined },
{ name: 'config-file', type: String, description: 'The name of the configuration file to use', multiple: false}
]

export interface FlowrCliOptions {
verbose: boolean
version: boolean
help: boolean
server: boolean
ws: boolean
port: number
'no-ansi': boolean
execute: string | undefined
script: string | undefined
verbose: boolean
version: boolean
help: boolean
server: boolean
ws: boolean
port: number
'no-ansi': boolean
execute: string | undefined
script: string | undefined
'config-file': string
}

export const optionHelp = [
Expand Down Expand Up @@ -81,6 +84,7 @@ if(options['no-ansi']) {
setFormatter(voidFormatter)
}

setConfigFile(undefined, options['config-file'] ?? defaultConfigFile, true)

async function retrieveShell(): Promise<RShell> {
// we keep an active shell session to allow other parse investigations :)
Expand Down
9 changes: 9 additions & 0 deletions src/util/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,12 @@ export function readLineByLineSync(filePath: string, onLine: (line: Buffer, line
}
}

/**
* Chops off the last part of the given directory path after a path separator, essentially returning the path's parent directory.
* If an absolute path is passed, the returned path is also absolute.
* @param directory - The directory whose parent to return
*/
export function getParentDirectory(directory: string): string{
// apparently this is somehow the best way to do it in node, what
return directory.split(path.sep).slice(0, -1).join(path.sep)
}
Loading