diff --git a/lib/App.js b/lib/App.js index eb50eab3..db529b08 100644 --- a/lib/App.js +++ b/lib/App.js @@ -3150,7 +3150,11 @@ ${content}`, }], }); - await fs.promises.writeFile(file, JSON.stringify(JSON.parse(chatResult.choices[0].message.content), false, 2)); + if (!await this._validateTranslateResponse(file, chatResult)) { + return; + } + + await this._writeResult(file, chatResult, true); Log(`✅ Translated ${file}`); } catch (err) { @@ -3192,7 +3196,13 @@ ${content}`, ${enLocale}`, }], }); - await fs.promises.writeFile(translatedLocalePath, JSON.stringify(JSON.parse(chatResult.choices[0].message.content), false, 2)); + + if (!await this._validateTranslateResponse(translatedLocalePath, chatResult)) { + return; + } + + await this._writeResult(translatedLocalePath, chatResult, true); + Log(`✅ Translated ${translatedLocalePath}`); } catch (err) { Log(`❌ Error translating ${translatedLocalePath}`); @@ -3228,7 +3238,12 @@ ${readme}`, }], }); - await fs.promises.writeFile(translatedReadmePath, chatResult.choices[0].message.content); + if (!await this._validateTranslateResponse(translatedReadmePath, chatResult)) { + return; + } + + await this._writeResult(translatedReadmePath, chatResult, false); + Log(`✅ Translated ${translatedReadmePath}`); } catch (err) { Log(`❌ Error translating ${translatedReadmePath}`); @@ -3238,6 +3253,35 @@ ${readme}`, })); } + async _validateTranslateResponse(file, chatResult) { + if (chatResult.choices[0].finish_reason === 'stop') { + return true; + } + + // Write the result to a file, so it can still be used instead of being tossed away + await fs.promises.writeFile(`${file}.fail`, chatResult.choices[0].message.content); + + Log(`❌ File ${file} could not be fully translated (finish reason '${chatResult.choices[0].finish_reason}').`); + Log(`The (partial) response has been stored in ${file}.fail`); + + return false; + } + + async _writeResult(file, chatResult, asJson) { + try { + let content = chatResult.choices[0].message.content; + if (asJson) { + content = JSON.stringify(JSON.parse(content), false, 2); + } + + await fs.promises.writeFile(file, content); + } catch (e) { + Log(`❌ File ${file} could not be translated. The (partial) response has been stored in ${file}.fail`); + + throw e; + } + } + static async addTypes({ appPath, useTs }) { if (useTs) { await NpmCommands.installDev([