-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(core): adding coolify.json for predefined configuration #5123
base: main
Are you sure you want to change the base?
Conversation
fix(core): Remove unnecessary things
@coderabbitai review |
📝 WalkthroughSummary by CodeRabbit
WalkthroughThe update removes the deprecated MagicController and its routes, adds a step in deployment to store the server’s private key, and enhances repository management with Coolify configuration support. Significant changes include updates in Livewire components for Git repositories, modifications in model methods to handle configuration and transactions, revisions in helper functions and configuration generation, introduction of a new JSON schema for Coolify, and adjustments in versioning and UI elements in Blade views. Minor database seeder modifications are also included. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Component as Livewire Component (Repo Form)
participant AppModel as Application Model
participant DB as Database
participant GithubAPI as GitHub API (via GithubApp)
User->>Component: Fill form & select options
Component->>Component: Trigger getCoolifyConfig() on update
alt Coolify config enabled
Component->>AppModel: Submit form with Coolify configuration
else
Component->>AppModel: Submit form using default settings
end
AppModel->>DB: Begin transaction & save configuration data
sequenceDiagram
participant Job as ApplicationDeploymentJob
participant Server as Server Instance
Job->>Server: Verify server functionality
Job->>Server: Execute privateKey->storeInFileSystem()
Job->>Job: Continue deployment with updated configuration
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 5
🧹 Nitpick comments (16)
app/Jobs/ApplicationDeploymentJob.php (2)
315-321
: Consider catchingThrowable
instead ofException
.The catch block only handles
Exception
, which might miss PHP errors and fatal errors. Consider usingThrowable
for more comprehensive error handling.- } catch (Exception $e) { + } catch (Throwable $e) {
2436-2459
: Enhance error logging in the failed method.Consider enhancing error logging to include stack traces for better debugging capabilities. This would help in troubleshooting deployment failures more effectively.
public function failed(Throwable $exception): void { $this->next(ApplicationDeploymentStatus::FAILED->value); $this->application_deployment_queue->addLogEntry('Oops something is not okay, are you okay? 😢', 'stderr'); if (str($exception->getMessage())->isNotEmpty()) { $this->application_deployment_queue->addLogEntry($exception->getMessage(), 'stderr'); + $this->application_deployment_queue->addLogEntry($exception->getTraceAsString(), 'stderr'); }
app/Livewire/Project/Shared/UploadConfig.php (2)
33-153
: Consider externalizing large JSON blocks for better maintainability.The multi-case switch includes large hardcoded JSON strings. Storing these configurations in separate template files—or using a dedicated helper—can simplify updates and reduce the risk of errors.
164-170
: Handle multiple-server scenarios more gracefully.Currently, if more than one server is owned by the current team, the code raises an exception instead of letting the user select the intended server. Consider providing a clearer fallback or user prompt for multi-server environments.
app/Livewire/Project/New/GithubPrivateRepository.php (1)
204-259
: Consider wrapping the non-Coolify application creation path in a transaction for consistency.The Coolify-based code path uses transactions and rolls back on failure, but the fallback code path creates and saves an application without a transaction. If partial failures occur, the resulting data might remain in an inconsistent state.
app/Livewire/Project/New/PublicGitRepository.php (3)
109-109
: Potential repeated config fetch
CallinggetCoolifyConfig()
whenever the base directory updates might trigger unnecessary fetches in some edge cases. Consider caching or debouncing calls if performance becomes an issue.
242-249
: Robust error handling for config fetch
WrappinggetCoolifyConfig()
in a try/catch is good. Consider logging or showing user-friendly alerts in case of missing or invalid config to improve debugging.
270-324
: Handling coolify config withinsubmit()
This block decodes, validates, and applies$this->coolify_config
under a transaction, which is comprehensive. For maintainability:
- Extract the code for processing
$config
into a dedicated method to reducesubmit()
complexity.- Confirm
configValidator()
gracefully handles all invalid or partial schemas.- If multiple users may update simultaneously, watch for potential concurrency conflicts.
app/Models/LocalPersistentVolume.php (1)
12-22
: Enhance name generation robustness.The name generation logic could be improved to handle edge cases and ensure uniqueness.
Consider this enhanced implementation:
public static function boot() { parent::boot(); static::creating(function ($model) { if (blank($model->name)) { - $name = $model->resource->uuid.str_replace('/', '-', $model->mount_path); + $name = str($model->resource->uuid) + ->append('-') + ->append(str($model->mount_path)->trim('/')->slug('-')) + ->limit(255) + ->toString(); $model->name = $name; } }); }resources/views/livewire/project/new/public-git-repository.blade.php (1)
83-84
: Add validation feedback for coolify.json editor.The Monaco editor for coolify.json should provide immediate feedback about JSON validity to prevent submission of invalid configurations.
Add validation attributes to the textarea:
-<x-forms.textarea id="coolify_config" wire:model="coolify_config" - monacoEditorLanguage="json" useMonacoEditor /> +<x-forms.textarea id="coolify_config" wire:model="coolify_config" + monacoEditorLanguage="json" useMonacoEditor + wire:model.live.debounce.500ms="coolify_config" + x-on:change="validateJson($event.target.value)" + :class="{'border-red-500': !isValidJson}" /> +<div x-show="!isValidJson" class="text-red-500 text-sm mt-1"> + Invalid JSON format +</div>bootstrap/helpers/applications.php (2)
136-191
: Consider using translation keys for error messages.The error messages are hardcoded strings. Consider moving them to language files for better internationalization support.
- $messages = [ - 'config.coolify.project_uuid.required' => 'Project UUID is required (coolify.project_uuid) in the coolify configuration.', + $messages = [ + 'config.coolify.project_uuid.required' => __('validation.coolify.project_uuid_required'),
193-340
: Consider splitting validation rules into smaller chunks.The validation rules are quite extensive. Consider splitting them into smaller, more manageable chunks by category (e.g., build, network, health check) to improve maintainability.
- $deepValidator = Validator::make(['config' => $config], [ + $buildRules = [ + 'config.build' => 'required|array', + // ... build related rules + ]; + $networkRules = [ + 'config.network' => 'array', + // ... network related rules + ]; + $deepValidator = Validator::make(['config' => $config], array_merge( + $buildRules, + $networkRules, + // ... other rule sets + ), $messages);coolify.schema.json (4)
1-7
: Consider using a more recent JSON Schema version.The schema uses draft-07, but newer versions (2019-09, 2020-12) offer additional features and improvements.
- "$schema": "http://json-schema.org/draft-07/schema#", + "$schema": "https://json-schema.org/draft/2020-12/schema",
8-121
: Add descriptions for better documentation.Consider adding descriptions to properties to improve schema documentation.
"properties": { "name": { - "type": "string" + "type": "string", + "description": "The name of the application" },
128-135
: Enhance domain validation pattern.The current pattern only checks for http/https prefix. Consider adding more comprehensive domain validation.
- "pattern": "^(http://|https://).+", + "pattern": "^(http://|https://)(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])(/.*)?$",
244-305
: Add format validation for environment variables.Consider adding format validation for common environment variable patterns.
"key": { - "type": "string" + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]*$", + "description": "Environment variable name in uppercase with underscores" },
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (21)
app/Http/Controllers/MagicController.php
(0 hunks)app/Jobs/ApplicationDeploymentJob.php
(1 hunks)app/Livewire/Project/New/GithubPrivateRepository.php
(7 hunks)app/Livewire/Project/New/PublicGitRepository.php
(8 hunks)app/Livewire/Project/Shared/UploadConfig.php
(1 hunks)app/Models/Application.php
(1 hunks)app/Models/GithubApp.php
(2 hunks)app/Models/LocalPersistentVolume.php
(1 hunks)app/Models/Server.php
(0 hunks)app/Services/ConfigurationGenerator.php
(4 hunks)bootstrap/helpers/applications.php
(2 hunks)config/constants.php
(1 hunks)coolify.schema.json
(1 hunks)database/seeders/ApplicationSeeder.php
(0 hunks)resources/views/livewire/project/application/general.blade.php
(1 hunks)resources/views/livewire/project/new/github-private-repository.blade.php
(1 hunks)resources/views/livewire/project/new/public-git-repository.blade.php
(2 hunks)resources/views/livewire/project/new/select.blade.php
(1 hunks)resources/views/livewire/project/shared/upload-config.blade.php
(1 hunks)routes/web.php
(0 hunks)versions.json
(1 hunks)
💤 Files with no reviewable changes (4)
- database/seeders/ApplicationSeeder.php
- app/Http/Controllers/MagicController.php
- routes/web.php
- app/Models/Server.php
✅ Files skipped from review due to trivial changes (3)
- resources/views/livewire/project/new/select.blade.php
- versions.json
- config/constants.php
🔇 Additional comments (15)
app/Jobs/ApplicationDeploymentJob.php (1)
256-258
: LGTM! Private key storage is properly handled.The addition ensures that the server's private key is available in the filesystem before proceeding with deployment operations, which is essential for secure SSH communications.
app/Livewire/Project/Shared/UploadConfig.php (1)
195-197
: Environment ownership validation is robust and straightforward.These lines correctly check if the environment belongs to the specified project, preventing cross-project misconfiguration.
app/Livewire/Project/New/GithubPrivateRepository.php (1)
161-165
: Branch fallback logic is clear and user-friendly.Properly checks for a 'main' then 'master' branch, and defaults to the first branch if neither is found. This covers common Git branching patterns neatly.
app/Services/ConfigurationGenerator.php (1)
23-133
: Configuration structure reorganization looks well-structured and easier to extend.Splitting the config into logical sections like
coolify
,source
,build
, anddeployment
provides clarity and facilitates future enhancements.app/Livewire/Project/New/PublicGitRepository.php (6)
13-14
: Additional imports look consistent
The usage ofDB
andCollection
is in line with the new transaction logic and possible coolify-related data handling.
17-17
: CUID integration
ImportingCuid2
for generating unique IDs is a suitable choice, enhancing uniqueness and preventing collisions.
33-33
: Review the new property
The$coolify_config
property stores a JSON-based configuration. Confirm that downstream code properly sanitizes and validates its contents to avoid malformed configuration issues.
41-41
: Boolean toggle
$use_coolify_config
defaults tofalse
, which is a safe default. Verify that user actions or UI flows correctly set this property totrue
only when appropriate.
132-132
: Ensuring correct build pack logic
Enabling$this->show_is_static
for non-'nixpacks' or non-'static' build packs aligns well with the existing approach.
176-176
: Reloading config on branch change
Fetching the config after changing the branch helps ensure the application creation process uses the correct data.app/Models/Application.php (1)
1670-1859
: RevisedsetConfig
method
The transaction-based approach to updating application data in bulk is cohesive. However, the current create-only logic for environment variables, storage, etc. could lead to duplicates ifsetConfig()
is called multiple times. Consider cleaning up or syncing existing records beforehand to avoid stale entries. Validate that repeated calls won’t generate unintended data growth.resources/views/livewire/project/shared/upload-config.blade.php (1)
2-11
: New config example buttons
Offering multiple example config buttons improves usability. Verify that user edits in the textarea aren’t overwritten unintentionally when choosing another example, ensuring clarity around how these presets interact with local changes.bootstrap/helpers/applications.php (2)
127-135
: LGTM! Initial JSON validation looks good.The function correctly validates that the input is a valid JSON string before proceeding with deeper validation.
347-370
: Add unit tests for custom validation logic.The custom validation logic for dockerfile content and domains is critical but lacks test coverage.
Let's verify if there are any existing tests:
❌ Verification inconclusive
🏁 Script executed:
#!/bin/bash # Search for test files related to configValidator rg -l "configValidator" tests/Length of output: 30
I'll now run an additional query to search for any test cases that reference the specific exception messages (e.g. “Validation failed:”) used in the custom validation logic. This should help confirm whether unit tests exist for these validations.
🏁 Script executed:
#!/bin/bash rg "Validation failed:" tests/Length of output: 32
Missing Unit Tests for Critical Custom Validation Logic
The custom validations in
bootstrap/helpers/applications.php
(lines 347-370) are not covered by any unit tests. Searches for test cases referencing terms like"configValidator"
and"Validation failed:"
produced no results. It's important to add tests that specifically verify:
- The exception is thrown when using the
'dockerfile'
build pack without the necessary Git repository/branch or Dockerfile content.- The proper handling of domain validations (checking for valid protocols and domain formats).
resources/views/livewire/project/application/general.blade.php (1)
9-11
: LGTM! Download Config button is properly enabled.The button is correctly uncommented and uses the appropriate wire:click directive.
case 'dockerfile': | ||
$this->config = '{ | ||
"name": "Example Application", | ||
"description": "This is an example application configuration", | ||
"coolify": { | ||
"project_uuid": "'.$this->project_uuid.'", | ||
"environment_uuid": "'.$this->environment_uuid.'", | ||
"destination_uuid": "'.$this->destination_uuid.'" | ||
}, | ||
"build": { | ||
"build_pack": "dockerfile", | ||
"dockerfile": { | ||
"content": "FROM nginx:latest" | ||
} | ||
}, | ||
"network": { | ||
"ports": { | ||
"expose": "80" | ||
} | ||
} | ||
}'; | ||
case 'dockerfile-without-coolify': |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add the missing break
to avoid unintended case fall-through.
Currently, the 'dockerfile'
case does not include a break
, causing the code to continue into the 'dockerfile-without-coolify'
case and overwrite $this->config
. Below is a suggested fix:
case 'dockerfile':
$this->config = '{
...
}';
+ break;
case 'dockerfile-without-coolify':
$this->config = '{
...
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
case 'dockerfile': | |
$this->config = '{ | |
"name": "Example Application", | |
"description": "This is an example application configuration", | |
"coolify": { | |
"project_uuid": "'.$this->project_uuid.'", | |
"environment_uuid": "'.$this->environment_uuid.'", | |
"destination_uuid": "'.$this->destination_uuid.'" | |
}, | |
"build": { | |
"build_pack": "dockerfile", | |
"dockerfile": { | |
"content": "FROM nginx:latest" | |
} | |
}, | |
"network": { | |
"ports": { | |
"expose": "80" | |
} | |
} | |
}'; | |
case 'dockerfile-without-coolify': | |
case 'dockerfile': | |
$this->config = '{ | |
"name": "Example Application", | |
"description": "This is an example application configuration", | |
"coolify": { | |
"project_uuid": "'.$this->project_uuid.'", | |
"environment_uuid": "'.$this->environment_uuid.'", | |
"destination_uuid": "'.$this->destination_uuid.'" | |
}, | |
"build": { | |
"build_pack": "dockerfile", | |
"dockerfile": { | |
"content": "FROM nginx:latest" | |
} | |
}, | |
"network": { | |
"ports": { | |
"expose": "80" | |
} | |
} | |
}'; | |
break; | |
case 'dockerfile-without-coolify': |
protected function cleanupNullEmptyValues(array $config): array | ||
{ | ||
return collect($config)->map(function ($value) { | ||
if (is_array($value)) { | ||
return $this->cleanupNullEmptyValues($value); | ||
} | ||
|
||
return $value; | ||
})->filter(function ($value) { | ||
return filled($value) && | ||
(! is_array($value) || ! empty($value)); | ||
})->toArray(); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Avoid removing valid boolean or numeric values in cleanupNullEmptyValues
.
Using filled($value)
discards false
, 0
, or "0"
, potentially removing legitimate settings from the config. Below is a suggested fix to preserve these values:
- })->filter(function ($value) {
- return filled($value) && (! is_array($value) || ! empty($value));
+ })->filter(function ($value) {
+ if (is_array($value)) {
+ return !empty($value);
+ }
+ // Keep boolean false or numeric zero
+ return !is_null($value) && $value !== '';
})
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
protected function cleanupNullEmptyValues(array $config): array | |
{ | |
return collect($config)->map(function ($value) { | |
if (is_array($value)) { | |
return $this->cleanupNullEmptyValues($value); | |
} | |
return $value; | |
})->filter(function ($value) { | |
return filled($value) && | |
(! is_array($value) || ! empty($value)); | |
})->toArray(); | |
} | |
protected function cleanupNullEmptyValues(array $config): array | |
{ | |
return collect($config)->map(function ($value) { | |
if (is_array($value)) { | |
return $this->cleanupNullEmptyValues($value); | |
} | |
return $value; | |
})->filter(function ($value) { | |
if (is_array($value)) { | |
return !empty($value); | |
} | |
// Keep boolean false or numeric zero | |
return !is_null($value) && $value !== ''; | |
})->toArray(); | |
} |
public function resource() | ||
{ | ||
return $this->morphTo('resource'); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Consider consolidating polymorphic relationships.
The file has multiple identical polymorphic relationships (resource
, application
, service
, database
, standalone_postgresql
) that all use the same morphTo configuration. This could lead to confusion about which relationship to use.
Consider consolidating these into a single relationship or documenting the specific use case for each:
- Add PHPDoc comments explaining when to use each relationship
- Or consolidate into a single relationship if they serve the same purpose
Example:
/**
* Get the owning resource model.
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function resource()
{
return $this->morphTo('resource');
}
Also applies to: 29-32, 34-37, 39-42, 44-47
public function getCoolifyConfig($baseDirectory, $git_repository, $git_branch) | ||
{ | ||
try { | ||
if ($baseDirectory !== '/') { | ||
$baseDirectory = $baseDirectory.'/'; | ||
} | ||
$githubApiPath = "/repos/{$git_repository}/contents{$baseDirectory}coolify.json?ref={$git_branch}"; | ||
['rate_limit_reset' => $rate_limit_reset, 'data' => $coolifyJson] = githubApi(source: $this, endpoint: $githubApiPath); | ||
$coolify_config = base64_decode(data_get($coolifyJson, 'content')); | ||
$rate_limit_reset = Carbon::parse((int) $rate_limit_reset)->format('Y-M-d H:i:s'); | ||
|
||
return [ | ||
'coolify_config' => $coolify_config, | ||
'rate_limit_reset' => $rate_limit_reset | ||
]; | ||
} catch (\Throwable $e) { | ||
return [ | ||
'coolify_config' => null, | ||
'rate_limit_reset' => null | ||
]; | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Enhance error handling and validation in getCoolifyConfig.
The method could benefit from improved validation and more specific error handling.
Consider these improvements:
public function getCoolifyConfig($baseDirectory, $git_repository, $git_branch)
{
try {
if ($baseDirectory !== '/') {
$baseDirectory = $baseDirectory.'/';
}
$githubApiPath = "/repos/{$git_repository}/contents{$baseDirectory}coolify.json?ref={$git_branch}";
['rate_limit_reset' => $rate_limit_reset, 'data' => $coolifyJson] = githubApi(source: $this, endpoint: $githubApiPath);
+ if (!isset($coolifyJson['content']) || !isset($coolifyJson['encoding']) || $coolifyJson['encoding'] !== 'base64') {
+ throw new \InvalidArgumentException('Invalid coolify.json format');
+ }
$coolify_config = base64_decode(data_get($coolifyJson, 'content'));
+ if ($coolify_config === false) {
+ throw new \RuntimeException('Failed to decode base64 content');
+ }
+ if (!json_decode($coolify_config)) {
+ throw new \JsonException('Invalid JSON content');
+ }
$rate_limit_reset = Carbon::parse((int) $rate_limit_reset)->format('Y-M-d H:i:s');
return [
'coolify_config' => $coolify_config,
'rate_limit_reset' => $rate_limit_reset
];
- } catch (\Throwable $e) {
+ } catch (\InvalidArgumentException $e) {
+ \Log::warning('Invalid coolify.json format: ' . $e->getMessage());
+ return ['coolify_config' => null, 'rate_limit_reset' => null];
+ } catch (\RuntimeException $e) {
+ \Log::error('Base64 decode failed: ' . $e->getMessage());
+ return ['coolify_config' => null, 'rate_limit_reset' => null];
+ } catch (\JsonException $e) {
+ \Log::error('JSON decode failed: ' . $e->getMessage());
+ return ['coolify_config' => null, 'rate_limit_reset' => null];
+ } catch (\Throwable $e) {
+ \Log::error('Unexpected error in getCoolifyConfig: ' . $e->getMessage());
return [
'coolify_config' => null,
'rate_limit_reset' => null
];
}
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
public function getCoolifyConfig($baseDirectory, $git_repository, $git_branch) | |
{ | |
try { | |
if ($baseDirectory !== '/') { | |
$baseDirectory = $baseDirectory.'/'; | |
} | |
$githubApiPath = "/repos/{$git_repository}/contents{$baseDirectory}coolify.json?ref={$git_branch}"; | |
['rate_limit_reset' => $rate_limit_reset, 'data' => $coolifyJson] = githubApi(source: $this, endpoint: $githubApiPath); | |
$coolify_config = base64_decode(data_get($coolifyJson, 'content')); | |
$rate_limit_reset = Carbon::parse((int) $rate_limit_reset)->format('Y-M-d H:i:s'); | |
return [ | |
'coolify_config' => $coolify_config, | |
'rate_limit_reset' => $rate_limit_reset | |
]; | |
} catch (\Throwable $e) { | |
return [ | |
'coolify_config' => null, | |
'rate_limit_reset' => null | |
]; | |
} | |
} | |
public function getCoolifyConfig($baseDirectory, $git_repository, $git_branch) | |
{ | |
try { | |
if ($baseDirectory !== '/') { | |
$baseDirectory = $baseDirectory.'/'; | |
} | |
$githubApiPath = "/repos/{$git_repository}/contents{$baseDirectory}coolify.json?ref={$git_branch}"; | |
['rate_limit_reset' => $rate_limit_reset, 'data' => $coolifyJson] = githubApi(source: $this, endpoint: $githubApiPath); | |
if (!isset($coolifyJson['content']) || !isset($coolifyJson['encoding']) || $coolifyJson['encoding'] !== 'base64') { | |
throw new \InvalidArgumentException('Invalid coolify.json format'); | |
} | |
$coolify_config = base64_decode(data_get($coolifyJson, 'content')); | |
if ($coolify_config === false) { | |
throw new \RuntimeException('Failed to decode base64 content'); | |
} | |
if (!json_decode($coolify_config)) { | |
throw new \JsonException('Invalid JSON content'); | |
} | |
$rate_limit_reset = Carbon::parse((int) $rate_limit_reset)->format('Y-M-d H:i:s'); | |
return [ | |
'coolify_config' => $coolify_config, | |
'rate_limit_reset' => $rate_limit_reset | |
]; | |
} catch (\InvalidArgumentException $e) { | |
\Log::warning('Invalid coolify.json format: ' . $e->getMessage()); | |
return ['coolify_config' => null, 'rate_limit_reset' => null]; | |
} catch (\RuntimeException $e) { | |
\Log::error('Base64 decode failed: ' . $e->getMessage()); | |
return ['coolify_config' => null, 'rate_limit_reset' => null]; | |
} catch (\JsonException $e) { | |
\Log::error('JSON decode failed: ' . $e->getMessage()); | |
return ['coolify_config' => null, 'rate_limit_reset' => null]; | |
} catch (\Throwable $e) { | |
\Log::error('Unexpected error in getCoolifyConfig: ' . $e->getMessage()); | |
return [ | |
'coolify_config' => null, | |
'rate_limit_reset' => null | |
]; | |
} | |
} |
<form class="flex flex-col space-y-4" wire:submit='submit'> | ||
<div class="flex flex-col gap-2"> | ||
@if ($use_coolify_config === false) | ||
<div class="flex gap-2"> | ||
<x-forms.select wire:model.live="selected_branch_name" label="Branch"> | ||
<option value="default" disabled selected>Select a branch</option> | ||
@foreach ($branches as $branch) | ||
@if ($loop->first) | ||
<option selected value="{{ data_get($branch, 'name') }}"> | ||
{{ data_get($branch, 'name') }} | ||
</option> | ||
@else | ||
<option value="{{ data_get($branch, 'name') }}"> | ||
{{ data_get($branch, 'name') }} | ||
</option> | ||
@endif | ||
@endforeach | ||
</x-forms.select> | ||
<x-forms.select wire:model.live="build_pack" label="Build Pack" required> | ||
<option value="nixpacks">Nixpacks</option> | ||
<option value="static">Static</option> | ||
<option value="dockerfile">Dockerfile</option> | ||
<option value="dockercompose">Docker Compose</option> | ||
</x-forms.select> | ||
@if ($is_static) | ||
<x-forms.input id="publish_directory" label="Publish Directory" | ||
helper="If there is a build process involved (like Svelte, React, Next, etc..), please specify the output directory for the build assets." /> | ||
@endif | ||
</div> | ||
@if ($build_pack === 'dockercompose') | ||
<x-forms.input placeholder="/" wire:model.live.debounce.500ms="base_directory" | ||
label="Base Directory" | ||
helper="Directory to use as root. Useful for monorepos." /> | ||
<x-forms.input placeholder="/docker-compose.yaml" id="docker_compose_location" | ||
label="Docker Compose Location" | ||
helper="It is calculated together with the Base Directory:<br><span class='dark:text-warning'>{{ Str::start($base_directory . $docker_compose_location, '/') }}</span>" /> | ||
Compose file location in your repository:<span | ||
class='dark:text-warning'>{{ Str::start($base_directory . $docker_compose_location, '/') }}</span> | ||
@else | ||
<x-forms.input wire:model.live.debounce.500ms="base_directory" | ||
label="Base Directory" | ||
helper="Directory to use as root. Useful for monorepos." /> | ||
@endif | ||
@if ($show_is_static) | ||
<x-forms.input type="number" id="port" label="Port" :readonly="$is_static || $build_pack === 'static'" | ||
helper="The port your application listens on." /> | ||
@if ($build_pack !== 'dockerfile') | ||
<div class="w-52"> | ||
<x-forms.checkbox instantSave id="is_static" | ||
label="Is it a static site?" | ||
helper="If your application is a static site or the final build assets should be served as a static site, enable this." /> | ||
</div> | ||
@endif | ||
@endif | ||
</div> | ||
@if ($build_pack === 'dockercompose') | ||
<x-forms.input placeholder="/" wire:model.blur="base_directory" | ||
label="Base Directory" | ||
helper="Directory to use as root. Useful for monorepos." /> | ||
<x-forms.input placeholder="/docker-compose.yaml" id="docker_compose_location" | ||
label="Docker Compose Location" | ||
helper="It is calculated together with the Base Directory:<br><span class='dark:text-warning'>{{ Str::start($base_directory . $docker_compose_location, '/') }}</span>" /> | ||
Compose file location in your repository:<span | ||
class='dark:text-warning'>{{ Str::start($base_directory . $docker_compose_location, '/') }}</span> | ||
@endif | ||
@if ($show_is_static) | ||
<x-forms.input type="number" id="port" label="Port" :readonly="$is_static || $build_pack === 'static'" | ||
helper="The port your application listens on." /> | ||
@if (filled($coolify_config)) | ||
<div class="w-52"> | ||
<x-forms.checkbox instantSave id="is_static" label="Is it a static site?" | ||
helper="If your application is a static site or the final build assets should be served as a static site, enable this." /> | ||
<x-forms.checkbox wire:model.live="use_coolify_config" | ||
label="Use coolify.json?" /> | ||
</div> | ||
@endif | ||
</div> | ||
@if (filled($coolify_config)) | ||
<div class="flex flex-col gap-2"> | ||
<div>coolify.json</div> | ||
<x-forms.textarea id="coolify_config" wire:model="coolify_config" | ||
monacoEditorLanguage="json" useMonacoEditor /> | ||
</div> | ||
@endif |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Extract shared repository configuration form into a component.
The configuration form logic is duplicated between public and private repository views. This could lead to maintenance issues.
Create a shared component to reduce duplication:
- Extract the form into
resources/views/components/repository-config-form.blade.php
- Use the component in both views:
<x-repository-config-form
:use-coolify-config="$use_coolify_config"
:build-pack="$build_pack"
:is-static="$is_static"
:base-directory="$base_directory"
:coolify-config="$coolify_config"
wire:submit="submit"
/>
No description provided.