-
-
Save pikdum/46ddcc20b73072f1aa873844b2595b3f to your computer and use it in GitHub Desktop.
feature flag redaction poc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as recast from "recast"; | |
// consequent to omit code | |
const redactedConsequent = recast.parse`\ | |
if (false) { | |
// REDACTED | |
} | |
`.program.body[0].consequent; | |
// a source code file | |
const code = `\ | |
if (FOO) { | |
console.log("FOO"); | |
} else { | |
console.log("NOT FOO"); | |
} | |
if (BAR) { | |
console.log("BAR"); | |
} else { | |
console.log("NOT BAR"); | |
} | |
if (BAZ) { | |
console.log("BAZ"); | |
} else { | |
console.log("NOT BAZ"); | |
} | |
if (UNKNOWN) { | |
console.log("UNKNOWN"); | |
}`; | |
// which flags are on or off | |
const FEATURE_FLAGS = { | |
FOO: false, | |
BAR: true, | |
BAZ: false, | |
}; | |
// get ast | |
const ast = recast.parse(code); | |
// loop through ast body, redact consequents where the flag is disabled | |
ast.program.body = ast.program.body.map((node) => { | |
// redact consequents where the flag is disabled | |
if (node.type === "IfStatement") { | |
if (FEATURE_FLAGS[node.test.name] === false) { | |
node.consequent = redactedConsequent; | |
} | |
} | |
return node; | |
}); | |
console.log(FEATURE_FLAGS); | |
console.log(recast.print(ast).code); | |
/* Output: | |
{ FOO: false, BAR: true, BAZ: false } | |
if (FOO) { | |
// REDACTED | |
} else { | |
console.log("NOT FOO"); | |
} | |
if (BAR) { | |
console.log("BAR"); | |
} else { | |
console.log("NOT BAR"); | |
} | |
if (BAZ) { | |
// REDACTED | |
} else { | |
console.log("NOT BAZ"); | |
} | |
if (UNKNOWN) { | |
console.log("UNKNOWN"); | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment