AutoRest Core provides a sophisticated configuration system with hierarchical merging, extension support, and context-aware configuration scoping for complex code generation scenarios.
Central configuration management class that provides access to settings, logging, and pipeline utilities.
/**
* AutoRest execution context providing configuration and utilities
* Manages hierarchical configuration, logging, and pipeline coordination
*/
class AutorestContext {
constructor(
config: AutorestConfiguration,
fileSystem: CachingFileSystem,
messageEmitter: MessageEmitter,
logger: AutorestLogger,
stats: StatsCollector,
plugin?: PipelinePluginDefinition
);
/** Get configuration value at specified path */
GetEntry(key: string): any;
/** Check if specific output artifact is requested */
IsOutputArtifactRequested(artifact: string): boolean;
/** Get nested configuration for specific scope */
getNestedConfiguration(
scope: string,
plugin?: PipelinePluginDefinition
): Iterable<AutorestContext>;
/** Create new context with additional configuration */
extendWith(...overrides: AutorestNormalizedConfiguration[]): AutorestContext;
/** Update or create configuration file */
updateConfigurationFile(filename: string, content: string): void;
/** Resolve configuration directives */
resolveDirectives(predicate?: (each: ResolvedDirective) => boolean): void;
/** Start a progress tracking session */
startProgress(initialName?: string): any;
/** Mark files for protection from deletion during clear operations */
protectFiles(filename: string): void;
/** Create a new context instance for a specific plugin */
getContextForPlugin(plugin: PipelinePluginDefinition): AutorestContext;
/** Current configuration object */
readonly config: AutorestConfiguration;
/** File system interface */
readonly fileSystem: CachingFileSystem;
/** Logger instance */
readonly logger: AutorestLogger;
/** Statistics collection */
readonly stats: StatsCollector;
/** Current plugin name */
readonly pluginName: string;
}Usage Examples:
import { AutoRest } from "@autorest/core";
const autorest = new AutoRest(console.log);
// Add base configuration
autorest.AddConfiguration({
"input-file": "swagger.json",
"output-folder": "./generated",
"clear-output-folder": true
});
// Get context and inspect configuration
const context = await autorest.view;
// Access configuration values
const inputFile = context.GetEntry("input-file");
console.log("Input file:", inputFile); // "swagger.json"
const outputFolder = context.GetEntry("output-folder");
console.log("Output folder:", outputFolder); // "./generated"
// Check if specific artifacts are requested
const wantsCSharp = context.IsOutputArtifactRequested("source-file-csharp");
console.log("C# generation requested:", wantsCSharp);Methods for retrieving and working with configuration values.
/**
* Get configuration value using dot notation path
* Supports nested object access and array indexing
* @param key - Configuration key path (e.g., "csharp.namespace")
* @returns Configuration value or undefined if not found
*/
GetEntry(key: string): any;
/**
* Check if specific output artifact type is requested
* Used by plugins to determine if they should execute
* @param artifact - Artifact type identifier
* @returns True if artifact should be generated
*/
IsOutputArtifactRequested(artifact: string): boolean;Configuration Access Examples:
// Complex configuration setup
autorest.AddConfiguration({
"input-file": ["swagger1.json", "swagger2.json"],
"csharp": {
"namespace": "MyClient",
"client-name": "ApiClient",
"generate": ["models", "operations"],
"model-namespace": "MyClient.Models"
},
"python": {
"package-name": "my_client",
"package-version": "1.0.0"
}
});
const context = await autorest.view;
// Access nested configuration
const csharpNamespace = context.GetEntry("csharp.namespace");
console.log(csharpNamespace); // "MyClient"
const generateList = context.GetEntry("csharp.generate");
console.log(generateList); // ["models", "operations"]
// Access array elements
const firstInputFile = context.GetEntry("input-file.0");
console.log(firstInputFile); // "swagger1.json"
// Check for undefined values
const javaConfig = context.GetEntry("java.namespace");
console.log(javaConfig); // undefined
// Check artifact requests
const needsCSharpModels = context.IsOutputArtifactRequested("source-file-csharp");
const needsPythonClient = context.IsOutputArtifactRequested("source-file-python");
console.log("Generate C#:", needsCSharpModels);
console.log("Generate Python:", needsPythonClient);Support for scoped configuration contexts for different plugins and extensions.
/**
* Get nested configuration contexts for specific scope
* Enables plugin-specific configuration isolation
* @param scope - Configuration scope (e.g., "csharp", "python")
* @param plugin - Optional plugin definition for context
* @returns Iterable of scoped AutorestContext instances
*/
getNestedConfiguration(
scope: string,
plugin?: PipelinePluginDefinition
): Iterable<AutorestContext>;Nested Configuration Example:
// Multi-language configuration
autorest.AddConfiguration({
"input-file": "swagger.json",
"csharp": {
"namespace": "CSharpClient",
"output-folder": "./csharp-client"
},
"python": {
"package-name": "python_client",
"output-folder": "./python-client"
}
});
const context = await autorest.view;
// Get C# specific contexts
for (const csharpContext of context.getNestedConfiguration("csharp")) {
const namespace = csharpContext.GetEntry("namespace");
const outputFolder = csharpContext.GetEntry("output-folder");
console.log(`C# Config - Namespace: ${namespace}, Output: ${outputFolder}`);
// C# Config - Namespace: CSharpClient, Output: ./csharp-client
}
// Get Python specific contexts
for (const pythonContext of context.getNestedConfiguration("python")) {
const packageName = pythonContext.GetEntry("package-name");
const outputFolder = pythonContext.GetEntry("output-folder");
console.log(`Python Config - Package: ${packageName}, Output: ${outputFolder}`);
// Python Config - Package: python_client, Output: ./python-client
}Methods for creating extended configuration contexts with additional settings.
/**
* Create new context with additional configuration overlays
* Merges provided configurations with current context
* @param overrides - Additional configuration objects to merge
* @returns New AutorestContext with merged configuration
*/
extendWith(...overrides: AutorestNormalizedConfiguration[]): AutorestContext;
/**
* Update or create configuration file with specified content
* @param filename - Configuration file name
* @param content - File content to write
*/
updateConfigurationFile(filename: string, content: string): void;Configuration Extension Example:
const baseContext = await autorest.view;
// Create extended context with additional settings
const extendedContext = baseContext.extendWith(
{
"generate-metadata": true,
"add-credentials": true
},
{
"csharp": {
"sync-methods": "all",
"use-datetimeoffset": true
}
}
);
// Original context unchanged
console.log(baseContext.GetEntry("generate-metadata")); // undefined
// Extended context has new settings
console.log(extendedContext.GetEntry("generate-metadata")); // true
console.log(extendedContext.GetEntry("csharp.sync-methods")); // "all"
// Update configuration file
extendedContext.updateConfigurationFile("autorest.md", `
# AutoRest Configuration
\`\`\`yaml
input-file: swagger.json
output-folder: ./generated
generate-metadata: true
\`\`\`
`);Built-in logging capabilities integrated with the configuration system.
interface AutorestLogger {
/** Log debug information */
debug(message: string): void;
/** Log verbose information */
verbose(message: string): void;
/** Log informational messages */
info(message: string): void;
/** Log fatal errors */
fatal(message: string): void;
/** Track and log errors */
trackError(error: AutorestError): void;
/** Track and log warnings */
trackWarning(error: AutorestWarning): void;
}Logging Usage:
const context = await autorest.view;
// Log at different levels
context.logger.info("Starting code generation");
context.logger.debug("Processing input file: swagger.json");
context.logger.verbose("Loaded 15 schema definitions");
// Track structured errors
try {
// Some operation that might fail
processSchema(schema);
} catch (error) {
context.logger.trackError({
message: "Schema processing failed",
source: "swagger.json:25:10",
details: error
});
}
// Track warnings
context.logger.trackWarning({
message: "Deprecated property found",
source: "swagger.json:42:5",
details: { property: "x-deprecated-field" }
});Advanced configuration processing for complex scenarios.
/**
* Resolve configuration directives with optional filtering
* Processes configuration rules and transformations
* @param predicate - Optional filter function for directives
*/
resolveDirectives(predicate?: (each: ResolvedDirective) => boolean): void;
interface ResolvedDirective {
/** Directive identifier */
name: string;
/** Directive configuration */
config: any;
/** Source of the directive */
source: string;
}Complete Configuration Example:
import { AutoRest } from "@autorest/core";
async function setupComplexConfiguration() {
const autorest = new AutoRest((message) => {
console.log(`[${message.Channel}] ${message.Text}`);
});
// Base configuration
autorest.AddConfiguration({
"input-file": [
"https://petstore.swagger.io/v2/swagger.json",
"./additional-endpoints.json"
],
"output-folder": "./generated",
"clear-output-folder": true,
"generate-metadata": true
});
// Language-specific configurations
autorest.AddConfiguration({
"csharp": {
"namespace": "PetStore.Client",
"client-name": "PetStoreClient",
"output-folder": "./generated/csharp",
"sync-methods": "essential",
"use-datetimeoffset": true
},
"python": {
"package-name": "petstore_client",
"package-version": "1.0.0",
"output-folder": "./generated/python"
}
});
const context = await autorest.view;
// Work with nested configurations
for (const csharpCtx of context.getNestedConfiguration("csharp")) {
const clientName = csharpCtx.GetEntry("client-name");
const namespace = csharpCtx.GetEntry("namespace");
csharpCtx.logger.info(`Configuring C# client: ${clientName} (${namespace})`);
// Create extended context for specific scenarios
const testContext = csharpCtx.extendWith({
"generate-tests": true,
"test-framework": "xunit"
});
if (testContext.GetEntry("generate-tests")) {
testContext.logger.info("Test generation enabled");
}
}
return context;
}