| 41 | } |
| 42 | |
| 43 | export class Literal implements PythonCode { |
| 44 | public readonly value: unknown; |
| 45 | public readonly opts: LiteralOptions; |
| 46 | constructor(value: unknown, opts: LiteralOptions = {}) { |
| 47 | this.value = value; |
| 48 | this.opts = opts; |
| 49 | } |
| 50 | |
| 51 | static from(value: unknown, opts: LiteralOptions = {}): Literal { |
| 52 | return new Literal(value, opts); |
| 53 | } |
| 54 | |
| 55 | toCode(): string { |
| 56 | const EMPTY_VALUE = ""; |
| 57 | const { removeNull = false, removeUndefined = true } = this.opts; |
| 58 | |
| 59 | if (this.value === undefined) { |
| 60 | if (removeUndefined) { |
| 61 | return EMPTY_VALUE; |
| 62 | } |
| 63 | return "None"; |
| 64 | } |
| 65 | if (this.value === null) { |
| 66 | if (removeNull) { |
| 67 | return EMPTY_VALUE; |
| 68 | } |
| 69 | return "None"; |
| 70 | } |
| 71 | if (typeof this.value === "string") { |
| 72 | return `'${this.value}'`; |
| 73 | } |
| 74 | if (typeof this.value === "boolean") { |
| 75 | return this.value ? "True" : "False"; |
| 76 | } |
| 77 | |
| 78 | // If a PythonCode object |
| 79 | if (typeof this.value === "object" && "toCode" in this.value) { |
| 80 | return (this.value as PythonCode).toCode(); |
| 81 | } |
| 82 | |
| 83 | if (Array.isArray(this.value)) { |
| 84 | if (this.value.length === 0) { |
| 85 | return "[]"; |
| 86 | } |
| 87 | return `[\n${indent( |
| 88 | this.value |
| 89 | .map((item) => new Literal(item, this.opts).toCode()) |
| 90 | .filter((item) => item !== EMPTY_VALUE) |
| 91 | .join(",\n"), |
| 92 | )}\n]`; |
| 93 | } |
| 94 | |
| 95 | if (typeof this.value === "object") { |
| 96 | const entries = Object.entries(this.value as Record<string, unknown>); |
| 97 | if (entries.length === 0) { |
| 98 | return "{}"; |
| 99 | } |
| 100 |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…