-
Notifications
You must be signed in to change notification settings - Fork 355
Expand file tree
/
Copy pathNewCommand.php
More file actions
429 lines (357 loc) · 14.2 KB
/
NewCommand.php
File metadata and controls
429 lines (357 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
<?php
namespace Laravel\Installer\Console;
use RuntimeException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Process\Process;
class NewCommand extends Command
{
/**
* Configure the command options.
*
* @return void
*/
protected function configure()
{
$this
->setName('new')
->setDescription('Create a new Laravel application')
->addArgument('name', InputArgument::REQUIRED)
->addOption('dev', null, InputOption::VALUE_NONE, 'Installs the latest "development" release')
->addOption('git', null, InputOption::VALUE_NONE, 'Initialize a Git repository')
->addOption('branch', null, InputOption::VALUE_REQUIRED, 'The branch that should be created for a new repository', $this->defaultBranch())
->addOption('github', null, InputOption::VALUE_OPTIONAL, 'Create a new repository on GitHub', false)
->addOption('organization', null, InputOption::VALUE_REQUIRED, 'The GitHub organization to create the new repository for')
->addOption('jet', null, InputOption::VALUE_NONE, 'Installs the Laravel Jetstream scaffolding')
->addOption('stack', null, InputOption::VALUE_OPTIONAL, 'The Jetstream stack that should be installed')
->addOption('teams', null, InputOption::VALUE_NONE, 'Indicates whether Jetstream should be scaffolded with team support')
->addOption('prompt-jetstream', null, InputOption::VALUE_NONE, 'Issues a prompt to determine if Jetstream should be installed')
->addOption('force', 'f', InputOption::VALUE_NONE, 'Forces install even if the directory already exists');
}
/**
* Execute the command.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return int
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$installJetstream = $input->getOption('jet') ||
($input->getOption('prompt-jetstream') && (new SymfonyStyle($input, $output))->confirm('Would you like to install the Laravel Jetstream application scaffolding?', false));
if ($installJetstream) {
$output->write(PHP_EOL." <fg=magenta>
| | |
|,---.|--- ,---.|--- ,---.,---.,---.,-.-.
||---'| `---.| | |---',---|| | |
`---'`---'`---'`---'`---'` `---'`---^` ' '</>".PHP_EOL.PHP_EOL);
$stack = $this->jetstreamStack($input, $output);
$teams = $input->getOption('teams') === true
? (bool) $input->getOption('teams')
: (new SymfonyStyle($input, $output))->confirm('Will your application use teams?', false);
} else {
$output->write(PHP_EOL.' <fg=red> _ _
| | | |
| | __ _ _ __ __ ___ _____| |
| | / _` | \'__/ _` \ \ / / _ \ |
| |___| (_| | | | (_| |\ V / __/ |
|______\__,_|_| \__,_| \_/ \___|_|</>'.PHP_EOL.PHP_EOL);
}
sleep(1);
$name = $input->getArgument('name');
$directory = $name !== '.' ? getcwd().'/'.$name : '.';
$version = $this->getVersion($input);
if (! $input->getOption('force')) {
$this->verifyApplicationDoesntExist($directory);
}
if ($input->getOption('force') && $directory === '.') {
throw new RuntimeException('Cannot use --force option when using current directory for installation!');
}
$composer = $this->findComposer();
$commands = [
$composer." create-project laravel/laravel \"$directory\" $version --remove-vcs --prefer-dist",
];
if ($directory != '.' && $input->getOption('force')) {
if (PHP_OS_FAMILY == 'Windows') {
array_unshift($commands, "(if exist \"$directory\" rd /s /q \"$directory\")");
} else {
array_unshift($commands, "rm -rf \"$directory\"");
}
}
if (PHP_OS_FAMILY != 'Windows') {
$commands[] = "chmod 755 \"$directory/artisan\"";
}
if (($process = $this->runCommands($commands, $input, $output))->isSuccessful()) {
if ($name !== '.') {
$this->replaceInFile(
'APP_URL=http://localhost',
'APP_URL='.$this->generateAppUrl($name),
$directory.'/.env'
);
$this->replaceInFile(
'DB_DATABASE=laravel',
'DB_DATABASE='.str_replace('-', '_', strtolower($name)),
$directory.'/.env'
);
$this->replaceInFile(
'DB_DATABASE=laravel',
'DB_DATABASE='.str_replace('-', '_', strtolower($name)),
$directory.'/.env.example'
);
}
if ($input->getOption('git') || $input->getOption('github') !== false) {
$this->createRepository($directory, $input, $output);
}
if ($installJetstream) {
$this->installJetstream($directory, $stack, $teams, $input, $output);
}
if ($input->getOption('github') !== false) {
$this->pushToGitHub($name, $directory, $input, $output);
$output->writeln('');
}
$output->writeln(' <bg=blue;fg=white> INFO </> Application ready! <options=bold>Build something amazing.</>'.PHP_EOL);
}
return $process->getExitCode();
}
/**
* Return the local machine's default Git branch if set or default to `main`.
*
* @return string
*/
protected function defaultBranch()
{
$process = new Process(['git', 'config', '--global', 'init.defaultBranch']);
$process->run();
$output = trim($process->getOutput());
return $process->isSuccessful() && $output ? $output : 'main';
}
/**
* Install Laravel Jetstream into the application.
*
* @param string $directory
* @param string $stack
* @param bool $teams
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return void
*/
protected function installJetstream(string $directory, string $stack, bool $teams, InputInterface $input, OutputInterface $output)
{
chdir($directory);
$commands = array_filter([
$this->findComposer().' require laravel/jetstream',
trim(sprintf(PHP_BINARY.' artisan jetstream:install %s %s', $stack, $teams ? '--teams' : '')),
'npm install && npm run build',
PHP_BINARY.' artisan storage:link',
]);
$this->runCommands($commands, $input, $output);
$this->commitChanges('Install Jetstream', $directory, $input, $output);
}
/**
* Determine the stack for Jetstream.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return string
*/
protected function jetstreamStack(InputInterface $input, OutputInterface $output)
{
$stacks = [
'livewire',
'inertia',
];
if ($input->getOption('stack') && in_array($input->getOption('stack'), $stacks)) {
return $input->getOption('stack');
}
$helper = $this->getHelper('question');
$question = new ChoiceQuestion('Which Jetstream stack do you prefer?', $stacks);
$output->write(PHP_EOL);
return $helper->ask($input, new SymfonyStyle($input, $output), $question);
}
/**
* Create a Git repository and commit the base Laravel skeleton.
*
* @param string $directory
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return void
*/
protected function createRepository(string $directory, InputInterface $input, OutputInterface $output)
{
chdir($directory);
$branch = $input->getOption('branch') ?: $this->defaultBranch();
$commands = [
'git init -q',
'git add .',
'git commit -q -m "Set up a fresh Laravel app"',
"git branch -M {$branch}",
];
$this->runCommands($commands, $input, $output);
}
/**
* Commit any changes in the current working directory.
*
* @param string $message
* @param string $directory
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return void
*/
protected function commitChanges(string $message, string $directory, InputInterface $input, OutputInterface $output)
{
if (! $input->getOption('git') && $input->getOption('github') === false) {
return;
}
chdir($directory);
$commands = [
'git add .',
"git commit -q -m \"$message\"",
];
$this->runCommands($commands, $input, $output);
}
/**
* Create a GitHub repository and push the git log to it.
*
* @param string $name
* @param string $directory
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return void
*/
protected function pushToGitHub(string $name, string $directory, InputInterface $input, OutputInterface $output)
{
$process = new Process(['gh', 'auth', 'status']);
$process->run();
if (! $process->isSuccessful()) {
$output->writeln(' <bg=yellow;fg=black> WARN </> Make sure the "gh" CLI tool is installed and that you\'re authenticated to GitHub. Skipping...'.PHP_EOL);
return;
}
chdir($directory);
$name = $input->getOption('organization') ? $input->getOption('organization')."/$name" : $name;
$flags = $input->getOption('github') ?: '--private';
$branch = $input->getOption('branch') ?: $this->defaultBranch();
$commands = [
"gh repo create {$name} --source=. --push {$flags}",
];
$this->runCommands($commands, $input, $output, ['GIT_TERMINAL_PROMPT' => 0]);
}
/**
* Verify that the application does not already exist.
*
* @param string $directory
* @return void
*/
protected function verifyApplicationDoesntExist($directory)
{
if ((is_dir($directory) || is_file($directory)) && $directory != getcwd()) {
throw new RuntimeException('Application already exists!');
}
}
/**
* Generate a valid APP_URL for the given application name.
*
* @param string $name
* @return string
*/
protected function generateAppUrl($name)
{
$hostname = mb_strtolower($name).'.test';
return $this->canResolveHostname($hostname) ? 'http://'.$hostname : 'http://localhost';
}
/**
* Determine whether the given hostname is resolvable.
*
* @param string $hostname
* @return bool
*/
protected function canResolveHostname($hostname)
{
return gethostbyname($hostname.'.') !== $hostname.'.';
}
/**
* Get the version that should be downloaded.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @return string
*/
protected function getVersion(InputInterface $input)
{
if ($input->getOption('dev')) {
return 'dev-master';
}
return '';
}
/**
* Get the composer command for the environment.
*
* @return string
*/
protected function findComposer()
{
$composerPath = getcwd().'/composer.phar';
if (file_exists($composerPath)) {
return '"'.PHP_BINARY.'" '.$composerPath;
}
return 'composer';
}
/**
* Run the given commands.
*
* @param array $commands
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param array $env
* @return \Symfony\Component\Process\Process
*/
protected function runCommands($commands, InputInterface $input, OutputInterface $output, array $env = [])
{
if (! $output->isDecorated()) {
$commands = array_map(function ($value) {
if (substr($value, 0, 5) === 'chmod') {
return $value;
}
return $value.' --no-ansi';
}, $commands);
}
if ($input->getOption('quiet')) {
$commands = array_map(function ($value) {
if (substr($value, 0, 5) === 'chmod') {
return $value;
}
return $value.' --quiet';
}, $commands);
}
$process = Process::fromShellCommandline(implode(' && ', $commands), null, $env, null, null);
if ('\\' !== DIRECTORY_SEPARATOR && file_exists('/dev/tty') && is_readable('/dev/tty')) {
try {
$process->setTty(true);
} catch (RuntimeException $e) {
$output->writeln(' <bg=yellow;fg=black> WARN </> '.$e->getMessage().PHP_EOL);
}
}
$process->run(function ($type, $line) use ($output) {
$output->write(' '.$line);
});
return $process;
}
/**
* Replace the given string in the given file.
*
* @param string $search
* @param string $replace
* @param string $file
* @return void
*/
protected function replaceInFile(string $search, string $replace, string $file)
{
file_put_contents(
$file,
str_replace($search, $replace, file_get_contents($file))
);
}
}