Skip to content

Commit 90ee57a

Browse files
committed
fix(stdin): improve error handling and prevent file collisions
1 parent a474a4e commit 90ee57a

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

app/Actions/FixCode.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,11 +133,16 @@ private function handleStdinOutput()
133133
{
134134
$tempFile = Project::getStdinTempFile();
135135

136-
if ($tempFile && file_exists($tempFile)) {
136+
if (! empty($tempFile) && file_exists($tempFile)) {
137137
if (($formattedContent = file_get_contents($tempFile)) !== false) {
138-
fwrite(STDOUT, $formattedContent);
138+
$bytesWritten = fwrite(STDOUT, $formattedContent);
139+
if ($bytesWritten === false) {
140+
error_log('Failed to write formatted content to STDOUT');
141+
}
139142
}
140143

144+
Project::cleanupStdinTempFile();
145+
} elseif (! empty($tempFile)) {
141146
Project::cleanupStdinTempFile();
142147
}
143148
}

app/Project.php

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,10 +101,12 @@ public static function resolveStdinPath($filepath = null)
101101

102102
// If a filepath is provided, use it for better config resolution
103103
if ($filepath) {
104-
// Create temp file with same name in temp directory
105104
$tempDir = sys_get_temp_dir();
106105
$fileName = basename($filepath);
107-
static::$stdinTempFile = $tempDir.DIRECTORY_SEPARATOR.$fileName;
106+
$uniqueSuffix = '_'.uniqid().'_'.getmypid();
107+
$pathInfo = pathinfo($fileName);
108+
$uniqueFileName = $pathInfo['filename'].$uniqueSuffix.(isset($pathInfo['extension']) ? '.'.$pathInfo['extension'] : '');
109+
static::$stdinTempFile = $tempDir.DIRECTORY_SEPARATOR.$uniqueFileName;
108110

109111
if (file_put_contents(static::$stdinTempFile, $content) === false) {
110112
abort(1, "Failed to create temporary file for stdin content: {$filepath}");
@@ -132,6 +134,11 @@ public static function resolveStdinPath($filepath = null)
132134
protected static function isStdinAvailable()
133135
{
134136
$stdin = fopen('php://stdin', 'r');
137+
138+
if ($stdin === false) {
139+
return false;
140+
}
141+
135142
$status = stream_get_meta_data($stdin);
136143
fclose($stdin);
137144

@@ -145,7 +152,13 @@ protected static function isStdinAvailable()
145152
*/
146153
protected static function readStdinContent()
147154
{
148-
return stream_get_contents(STDIN);
155+
$content = stream_get_contents(STDIN);
156+
157+
if ($content === false) {
158+
abort(1, 'Failed to read content from stdin.');
159+
}
160+
161+
return $content;
149162
}
150163

151164
/**

0 commit comments

Comments
 (0)