| 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 | |
| 101 | const formatEntry = (entry: [string, unknown]) => { |
| 102 | const [key, value] = entry; |
| 103 | const code = new Literal(value, this.opts).toCode(); |
| 104 | if (code === "") { |
| 105 | return ""; |
| 106 | } |
| 107 | return `'${key}': ${code}`; |
| 108 | }; |
| 109 | |
| 110 | const formattedEntries = entries |
| 111 | .map(formatEntry) |
| 112 | .filter(Boolean) |