Skip to content

Commit

Permalink
And and Not functions
Browse files Browse the repository at this point in the history
  • Loading branch information
t0yv0 committed Nov 19, 2024
1 parent 24ebf01 commit e62d720
Showing 1 changed file with 61 additions and 2 deletions.
63 changes: 61 additions & 2 deletions src/converters/intrinsics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,13 +160,72 @@ export const fnOr: Intrinsic = {
if (ok) {
return ctx.succeed(true);
} else {
return evaluateConditionOrExpression(ctx, expr);
return evaluateConditionSubExpression(ctx, expr);
}
})
return params.reduce(reducer, ctx.succeed(false));
}
}


/**
*
* From the docs: the minimum number of conditions that you can include is 2, and the maximum is 10.
*
* Example invocation:
*
* "MyAndCondition": {
* "Fn::And": [
* {"Fn::Equals": ["sg-mysggroup", {"Ref": "ASecurityGroup"}]},
* {"Condition": "SomeOtherCondition"}
* ]
* }
*
* See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-and
*/
export const fnAnd: Intrinsic = {
name: 'Fn::And',
evaluate: (ctx: IntrinsicContext, params: Expression[]): Result<any> => {
if (params.length < 2) {
return ctx.fail(`Fn::And expects at least 2 params, got ${params.length}`)
}
const reducer = (acc: Result<boolean>, expr: Expression) => ctx.apply(acc, ok => {
if (!ok) {
return ctx.succeed(false);
} else {
return evaluateConditionSubExpression(ctx, expr);
}
})
return params.reduce(reducer, ctx.succeed(true));
}
}


/**
* Boolean negation. Expects exactly one argument.
*
* Example invocation:
*
* "MyNotCondition" : {
* "Fn::Not" : [{
* "Fn::Equals" : [
* {"Ref" : "EnvironmentType"},
* "prod"
* ]
* }]
* }
*/
export const fnNot: Intrinsic = {
name: 'Fn::Not',
evaluate: (ctx: IntrinsicContext, params: Expression[]): Result<any> => {
if (params.length != 1) {
return ctx.fail(`Fn::Not expects exactly 1 param, got ${params.length}`)
}
return ctx.apply(mustBeBoolean(ctx, ctx.evaluate(params[0])), v => ctx.succeed(!v));
}
}


/**
* From the docs: Compares if two values are equal. Returns true if the two values are equal or false if they aren't.
*
Expand Down Expand Up @@ -209,7 +268,7 @@ function parseConditionExpr(raw: Expression): string|undefined {
/**
* Like `ctx.evaluate` but also recognizes Condition sub-expressions as required by `Fn::Or`.
*/
function evaluateConditionOrExpression(ctx: IntrinsicContext, expr: Expression): Result<boolean> {
function evaluateConditionSubExpression(ctx: IntrinsicContext, expr: Expression): Result<boolean> {
const firstExprConditonName = parseConditionExpr(expr);
if (firstExprConditonName !== undefined) {
return evaluateCondition(ctx, firstExprConditonName)
Expand Down

0 comments on commit e62d720

Please sign in to comment.