-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathNewCommand.php
1283 lines (1050 loc) · 37.8 KB
/
NewCommand.php
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Statamic\Cli;
use GuzzleHttp\Client;
use Laravel\Prompts\ConfirmPrompt;
use Laravel\Prompts\Prompt;
use Laravel\Prompts\SelectPrompt;
use Laravel\Prompts\SuggestPrompt;
use Laravel\Prompts\TextPrompt;
use RuntimeException;
use Statamic\Cli\Theme\ConfirmPromptRenderer;
use Statamic\Cli\Theme\SelectPromptRenderer;
use Statamic\Cli\Theme\SuggestPromptRenderer;
use Statamic\Cli\Theme\TextPromptRenderer;
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\Question;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Process\Process;
use function Laravel\Prompts\confirm;
use function Laravel\Prompts\intro;
use function Laravel\Prompts\select;
use function Laravel\Prompts\suggest;
use function Laravel\Prompts\text;
class NewCommand extends Command
{
use Concerns\ConfiguresDatabase, Concerns\ConfiguresPrompts, Concerns\RunsCommands;
const BASE_REPO = 'statamic/statamic';
const OUTPOST_ENDPOINT = 'https://outpost.statamic.com/v3/starter-kits/';
const GITHUB_LATEST_RELEASE_ENDPOINT = 'https://api.github.com/repos/statamic/cli/releases/latest';
const STATAMIC_API_URL = 'https://statamic.com/api/v1/';
/** @var InputInterface */
public $input;
/** @var OutputInterface */
public $output;
public $relativePath;
public $absolutePath;
public $name;
public $version;
public $starterKit;
public $starterKits;
public $starterKitLicense;
public $local;
public $withConfig;
public $withoutDependencies;
public $shouldConfigureDatabase = false;
public $ssg;
public $force;
public $baseInstallSuccessful;
public $shouldUpdateCliToVersion = false;
public $makeUser = false;
public $initializeGitRepository = false;
public $shouldPushToGithub = false;
public $githubRepository;
public $repositoryVisibility;
public $pro = true;
/**
* Configure the command options.
*
* @return void
*/
protected function configure()
{
$this
->setName('new')
->setDescription('Create a new Statamic application')
->addArgument('name', InputArgument::REQUIRED, 'Statamic application directory name')
->addOption('dev', null, InputOption::VALUE_NONE, 'Installs the latest "development" release')
->addArgument('starter-kit', InputArgument::OPTIONAL, 'Optionally install specific starter kit')
->addOption('license', null, InputOption::VALUE_OPTIONAL, 'Optionally provide explicit starter kit license')
->addOption('local', null, InputOption::VALUE_NONE, 'Optionally install from local repo configured in composer config.json')
->addOption('with-config', null, InputOption::VALUE_NONE, 'Optionally copy starter-kit.yaml config for local development')
->addOption('without-dependencies', null, InputOption::VALUE_NONE, 'Optionally install starter kit without dependencies')
->addOption('pro', null, InputOption::VALUE_NONE, 'Enable Statamic Pro for additional features')
->addOption('ssg', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Optionally install the Static Site Generator addon', [])
->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')
->addOption('github', null, InputOption::VALUE_OPTIONAL, 'Create a new repository on GitHub', false)
->addOption('repo', null, InputOption::VALUE_REQUIRED, 'Optionally specify the name of the GitHub repository')
->addOption('force', 'f', InputOption::VALUE_NONE, 'Force install even if the directory already exists')
->addOption('email', null, InputOption::VALUE_OPTIONAL, 'Creates a super user with this email address')
->addOption('password', null, InputOption::VALUE_OPTIONAL, 'Password for the super user');
}
protected function initialize(InputInterface $input, OutputInterface $output)
{
$this->input = $input;
$this->output = $output;
$this->configurePrompts($input, $output);
$this
->setupTheme()
->checkCliVersion()
->notifyIfOldCliVersion()
->showStatamicTitleArt();
}
protected function interact(InputInterface $input, OutputInterface $output)
{
if (! $this->input->getArgument('name')) {
$this->input->setArgument('name', text(
label: 'What is the name of your project?',
placeholder: 'E.g. example-app',
required: 'The project name is required.',
validate: fn ($value) => preg_match('/[^\pL\pN\-_.]/', $value) !== 0
? 'The name may only contain letters, numbers, dashes, underscores, and periods.'
: null,
));
}
}
/**
* Execute the command.
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
try {
$this
->processArguments()
->validateArguments()
->askForRepo()
->validateStarterKitLicense()
->askToInstallEloquentDriver()
->askToEnableStatamicPro()
->askToInstallSsg()
->askToMakeSuperUser()
->askToInitializeGitRepository()
->askToPushToGithub()
->askToSpreadJoy()
->installBaseProject()
->installStarterKit()
->enableStatamicPro()
->makeSuperUser()
->configureDatabaseConnection()
->installEloquentDriver()
->installSsg()
->initializeGitRepository()
->pushToGithub()
->notifyIfOldCliVersion()
->showSuccessMessage()
->showPostInstallInstructions();
} catch (RuntimeException $e) {
$this->showError($e->getMessage());
return 1;
}
return 0;
}
protected function promptUntilValid($prompt, $required, $validate, $output)
{
while (true) {
$result = $prompt();
if ($required && ($result === '' || $result === [] || $result === false)) {
$output->writeln('<error>'.(is_string($required) ? $required : 'Required.').'</error>');
continue;
}
if ($validate) {
$error = $validate($result);
if (is_string($error) && strlen($error) > 0) {
$output->writeln("<error>{$error}</error>");
continue;
}
}
return $result;
}
}
protected function setupTheme()
{
Prompt::addTheme('statamic', [
SelectPrompt::class => SelectPromptRenderer::class,
SuggestPrompt::class => SuggestPromptRenderer::class,
ConfirmPrompt::class => ConfirmPromptRenderer::class,
TextPrompt::class => TextPromptRenderer::class,
]);
Prompt::theme('statamic');
return $this;
}
/**
* Check cli version.
*
* @return $this
*/
protected function checkCliVersion()
{
$request = new Client;
if (! $currentVersion = Version::get()) {
return $this;
}
try {
$response = $request->get(self::GITHUB_LATEST_RELEASE_ENDPOINT);
$latestVersion = json_decode($response->getBody(), true)['tag_name'];
} catch (\Throwable $exception) {
return $this;
}
if (version_compare($currentVersion, $latestVersion, '<')) {
$this->shouldUpdateCliToVersion = $latestVersion;
}
return $this;
}
/**
* Notify user if a statamic/cli upgrade exists.
*
* @return $this
*/
protected function notifyIfOldCliVersion()
{
if (! $this->shouldUpdateCliToVersion) {
return $this;
}
$this->output->write(PHP_EOL);
$this->output->write(" <comment>This is an old version of the Statamic CLI Tool, please upgrade to {$this->shouldUpdateCliToVersion}!</comment>".PHP_EOL);
$this->output->write(' <comment>If you have a global composer installation, you may upgrade by running the following command:</comment>'.PHP_EOL);
$this->output->write(' <comment>composer global update statamic/cli</comment>'.PHP_EOL);
return $this;
}
/**
* Process arguments and options.
*
* @return $this
*/
protected function processArguments()
{
$this->relativePath = $this->input->getArgument('name');
$this->absolutePath = $this->relativePath && $this->relativePath !== '.'
? getcwd().'/'.$this->relativePath
: getcwd();
$this->name = pathinfo($this->absolutePath)['basename'];
$this->version = $this->input->getOption('dev')
? 'dev-master'
: '';
$this->starterKit = $this->input->getArgument('starter-kit');
$this->starterKitLicense = $this->input->getOption('license');
$this->local = $this->input->getOption('local');
$this->withConfig = $this->input->getOption('with-config');
$this->withoutDependencies = $this->input->getOption('without-dependencies');
$this->pro = $this->input->getOption('pro') ?? true;
$this->ssg = $this->input->getOption('ssg');
$this->force = $this->input->getOption('force');
$this->initializeGitRepository = $this->input->getOption('git') !== false || $this->input->getOption('github') !== false;
$this->shouldPushToGithub = $this->input->getOption('github') !== false;
$this->githubRepository = $this->input->getOption('repo');
$this->repositoryVisibility = $this->input->getOption('github');
return $this;
}
/**
* Validate arguments and options.
*
* @return $this
*
* @throws RuntimeException
*/
protected function validateArguments()
{
if (! $this->force && $this->applicationExists()) {
throw new RuntimeException('Application already exists!');
}
if ($this->force && $this->pathIsCwd()) {
throw new RuntimeException('Cannot use --force option when using current directory for installation!');
}
if ($this->starterKit && $this->isInvalidStarterKit()) {
throw new RuntimeException('Please enter a valid composer package name (eg. hasselhoff/kung-fury)!');
}
if (! $this->starterKit && $this->starterKitLicense) {
throw new RuntimeException('Starter kit is required when using `--license` option!');
}
if (! $this->starterKit && $this->local) {
throw new RuntimeException('Starter kit is required when using `--local` option!');
}
if (! $this->starterKit && $this->withConfig) {
throw new RuntimeException('Starter kit is required when using `--with-config` option!');
}
if (! $this->starterKit && $this->withoutDependencies) {
throw new RuntimeException('Starter kit is required when using `--without-dependencies` option!');
}
return $this;
}
/**
* Show Statamic title art.
*
* @return $this
*/
protected function showStatamicTitleArt()
{
$this->output->write(PHP_EOL.'<fg=#D4FF4C>
█▀ ▀█▀ ▄▀█ ▀█▀ ▄▀█ █▀▄▀█ █ █▀▀
▄█ ░█░ █▀█ ░█░ █▀█ █░▀░█ █ █▄▄</>'.PHP_EOL.PHP_EOL);
return $this;
}
/**
* Ask which starter kit repo to install.
*
* @return $this
*/
protected function askForRepo()
{
if ($this->starterKit || ! $this->input->isInteractive()) {
return $this;
}
$choice = select(
'Would you like to install a starter kit?',
options: [
$blankSiteOption = 'No, start with a blank site.',
'Yes, let me pick a Starter Kit.',
],
default: $blankSiteOption
);
if ($choice === $blankSiteOption) {
return $this;
}
$this->output->write(' You can find starter kits at <info>https://statamic.com/starter-kits</info> 🏄'.PHP_EOL.PHP_EOL);
$this->starterKit = $this->normalizeStarterKitSelection(suggest(
'Which starter kit would you like to install?',
fn ($value) => $this->searchStarterKits($value)
));
if ($this->isInvalidStarterKit()) {
throw new RuntimeException('Please enter a valid composer package name (eg. hasselhoff/kung-fury)!');
}
return $this;
}
/**
* Validate starter kit license.
*
* @return $this
*/
protected function validateStarterKitLicense()
{
if (! $this->starterKit) {
return $this;
}
$request = new Client;
try {
$response = $request->get(self::OUTPOST_ENDPOINT."{$this->starterKit}");
} catch (\Exception $exception) {
$this->throwConnectionException();
}
$details = json_decode($response->getBody(), true);
// If $details === `false`, then no product was returned and we'll consider it a free starter kit.
if ($details['data'] === false) {
return $this->confirmUnlistedKit();
}
// If the returned product doesn't have a price, then we'll consider it a free starter kit.
if (! $details['data']['price']) {
return $this;
}
$sellerSlug = $details['data']['seller']['slug'];
$kitSlug = $details['data']['slug'];
$marketplaceUrl = "https://statamic.com/starter-kits/{$sellerSlug}/{$kitSlug}";
if ($this->input->isInteractive()) {
$this->output->write(' <comment>This is a paid starter kit. If you haven\'t already, you may purchase a license at:</comment>'.PHP_EOL);
$this->output->write(" <comment>{$marketplaceUrl}</comment>".PHP_EOL);
$this->output->write(PHP_EOL);
}
$license = $this->getStarterKitLicense();
try {
$response = $request->post(self::OUTPOST_ENDPOINT.'validate', ['json' => [
'license' => $license,
'package' => $this->starterKit,
]]);
} catch (\Exception $exception) {
$this->throwConnectionException();
}
$validation = json_decode($response->getBody(), true);
if (! $validation['data']['valid']) {
throw new RuntimeException("Invalid license for [{$this->starterKit}]!");
}
$this->output->write('<info>Starter kit license valid!</info>'.PHP_EOL);
$this->starterKitLicense = $license;
return $this->confirmSingleSiteLicense();
}
/**
* Confirm unlisted kit.
*
* @return $this
*/
protected function confirmUnlistedKit()
{
if (! confirm('Starter kit not found on Statamic Marketplace. Install unlisted starter kit?')) {
return $this->exitInstallation();
}
return $this;
}
/**
* Confirm single-site license.
*
* @return $this
*/
protected function confirmSingleSiteLicense()
{
$this->output->write(PHP_EOL);
$this->output->write('<comment>Once successfully installed, this Starter Kit license will be marked as used</comment>'.PHP_EOL);
$this->output->write('<comment>and cannot be applied to future installations!</comment>');
if (! $this->input->isInteractive()) {
return $this;
}
$this->output->write(PHP_EOL.PHP_EOL);
if (! confirm('Would you like to continue the installation?', false, 'I understand. Install now and mark used.', "No, I'll install it later.")) {
return $this->exitInstallation();
}
return $this;
}
/**
* Install base project.
*
* @return $this
*
* @throws RuntimeException
*/
protected function installBaseProject()
{
$commands = [];
if ($this->force && ! $this->pathIsCwd()) {
if (PHP_OS_FAMILY == 'Windows') {
$commands[] = "rd /s /q \"$this->absolutePath\"";
} else {
$commands[] = "rm -rf \"$this->absolutePath\"";
}
}
$commands[] = $this->createProjectCommand();
if (PHP_OS_FAMILY != 'Windows') {
$commands[] = "chmod 755 \"$this->absolutePath/artisan\"";
$commands[] = "chmod 755 \"$this->absolutePath/please\"";
}
$this->runCommands($commands);
if (! $this->wasBaseInstallSuccessful()) {
throw new RuntimeException('There was a problem installing Statamic!');
}
$this->replaceInFile(
'APP_URL=http://localhost',
'APP_URL=http://'.$this->name.'.test',
$this->absolutePath.'/.env'
);
$this->baseInstallSuccessful = true;
return $this;
}
/**
* Install starter kit.
*
* @return $this
*
* @throws RuntimeException
*/
protected function installStarterKit()
{
if (! $this->baseInstallSuccessful || ! $this->starterKit) {
return $this;
}
$options = [
'--cli-install',
'--clear-site',
];
if (! $this->input->isInteractive()) {
$options[] = '--no-interaction';
}
if ($this->local) {
$options[] = '--local';
}
if ($this->withConfig) {
$options[] = '--with-config';
}
if ($this->starterKitLicense) {
$options[] = '--license';
$options[] = $this->starterKitLicense;
}
if ($this->withoutDependencies) {
$options[] = '--without-dependencies';
}
$statusCode = (new Please($this->output))
->cwd($this->absolutePath)
->run('starter-kit:install', $this->starterKit, ...$options);
if ($statusCode !== 0) {
throw new RuntimeException('There was a problem installing Statamic with the chosen starter kit!');
}
return $this;
}
protected function askToInstallEloquentDriver()
{
if (! $this->input->isInteractive()) {
return $this;
}
$choice = select(
label: 'Where do you want to store your content and data?',
options: [
'flat-file' => 'Flat Files',
'database' => 'Database',
],
default : 'flat-file',
hint: 'When in doubt, choose Flat Files. You can always change this later.'
);
$this->shouldConfigureDatabase = $choice === 'database';
return $this;
}
protected function configureDatabaseConnection()
{
if (! $this->shouldConfigureDatabase) {
return $this;
}
$database = $this->promptForDatabaseOptions();
$this->configureDefaultDatabaseConnection($database, $this->name);
if ($database === 'sqlite') {
touch($this->absolutePath.'/database/database.sqlite');
}
$command = ['migrate'];
if (! $this->input->isInteractive()) {
$command[] = '--no-interaction';
}
$migrate = (new Please($this->output))
->cwd($this->absolutePath)
->run(...$command);
// When there's an issue running the migrations, it's likely because of connection issues.
// Let's let the user know and continue with the install process.
if ($migrate !== 0) {
$this->shouldConfigureDatabase = false;
$this->output->write(' <bg=red;options=bold> There was a problem connecting to the database. </>'.PHP_EOL);
$this->output->write(PHP_EOL);
$this->output->write(' Once the install process is complete, please run <info>php please install:eloquent-driver</info> to finish setting up the database.'.PHP_EOL);
}
return $this;
}
protected function installEloquentDriver()
{
if (! $this->shouldConfigureDatabase) {
return $this;
}
$options = [
'--import',
'--without-messages',
];
$whichRepositories = select(
label: 'Do you want to store everything in the database, or just some things?',
options: [
'everything' => 'Everything',
'custom' => 'Let me choose',
],
default: 'everything'
);
if ($whichRepositories === 'everything') {
$options[] = '--all';
}
(new Please($this->output))
->cwd($this->absolutePath)
->run('install:eloquent-driver', ...$options);
$this->output->write(' <info>[✔] Database setup complete!</info>', PHP_EOL);
return $this;
}
protected function askToInstallSsg()
{
if ($this->ssg || ! $this->input->isInteractive()) {
return $this;
}
if (confirm('Do you plan to generate a static site?', default: false)) {
$this->ssg = true;
}
return $this;
}
protected function installSsg()
{
if (! $this->ssg) {
return $this;
}
$this->output->write(PHP_EOL);
intro('Installing the Static Site Generator addon...');
$statusCode = (new Please($this->output))
->cwd($this->absolutePath)
->run('install:ssg');
if ($statusCode !== 0) {
throw new RuntimeException('There was a problem installing the Static Site Generator addon!');
}
return $this;
}
protected function askToMakeSuperUser()
{
if ($this->input->getOption('email')) {
$this->makeUser = true;
return $this;
}
if (! $this->input->isInteractive()) {
return $this;
}
$this->makeUser = confirm('Create a super user?', false);
$this->output->write(
$this->makeUser
? " Great. You'll be prompted for details after installation."
: ' No problem. You can create one later with <comment>php please make:user</comment>.'
);
$this->output->write(PHP_EOL.PHP_EOL);
return $this;
}
/**
* Make super user.
*
* @return $this
*/
protected function makeSuperUser()
{
if (! $this->makeUser) {
return $this;
}
$email = $this->input->getOption('email');
$password = $this->input->getOption('password') ?? 'password';
if (! $email) {
$this->output->write(PHP_EOL.PHP_EOL);
intro("Let's create your super user account.");
}
// Since Windows cannot TTY, we'll capture their input here and make a user.
if ($this->input->isInteractive() && ! $email && PHP_OS_FAMILY === 'Windows') {
return $this->makeSuperUserInWindows();
}
$command = ['make:user'];
if ($email) {
$command = [...$command, $email, '--password='.$password];
}
$command[] = '--super';
if (! $this->input->isInteractive()) {
$command[] = '--no-interaction';
}
// Otherwise, delegate to the `make:user` command and let core handle the finer details.
(new Please($this->output))
->cwd($this->absolutePath)
->run(...$command);
return $this;
}
/**
* Make super user in Windows.
*
* @return $this
*/
protected function makeSuperUserInWindows()
{
$please = (new Please($this->output))->cwd($this->absolutePath);
// Ask for email
while (! isset($email) || ! $this->validateEmail($email)) {
$email = $this->askForBasicInput('Email');
}
// Ask for password
while (! isset($password) || ! $this->validatePassword($password)) {
$password = $this->askForBasicInput('Password (Your input will be hidden)', true);
}
// Create super user and update with captured input.
$please->run('make:user', $email, '--password='.$password, '--super');
return $this;
}
/**
* Ask to initialize a Git repository.
*
* @return $this
*/
protected function askToInitializeGitRepository()
{
if (
$this->initializeGitRepository
|| ! $this->isGitInstalled()
|| ! $this->input->isInteractive()
) {
return $this;
}
$this->initializeGitRepository = confirm(
label: 'Would you like to initialize a Git repository?',
default: false
);
return $this;
}
/**
* Initialize a Git repository.
*
* @return $this
*/
protected function initializeGitRepository()
{
if (! $this->initializeGitRepository || ! $this->isGitInstalled()) {
return $this;
}
$branch = $this->input->getOption('branch') ?: $this->defaultBranch();
$commands = [
'git init -q',
'git add .',
'git commit -q -m "Set up a fresh Statamic site"',
"git branch -M {$branch}",
];
$this->runCommands($commands, workingPath: $this->absolutePath);
return $this;
}
/**
* Check if Git is installed.
*/
protected function isGitInstalled(): bool
{
$process = new Process(['git', '--version']);
$process->run();
return $process->isSuccessful();
}
/**
* Return the local machine's default Git branch if set or default to `main`.
*/
protected function defaultBranch(): string
{
$process = new Process(['git', 'config', '--global', 'init.defaultBranch']);
$process->run();
$output = trim($process->getOutput());
return $process->isSuccessful() && $output ? $output : 'main';
}
/**
* Ask if the user wants to push the repository to GitHub.
*
* @return $this
*/
protected function askToPushToGithub()
{
if (
! $this->initializeGitRepository
|| ! $this->isGitInstalled()
|| ! $this->isGhInstalled()
|| ! $this->input->isInteractive()
) {
return $this;
}
if (! $this->shouldPushToGithub) {
$this->shouldPushToGithub = confirm(
label: 'Would you like to create a new repository on GitHub?',
default: false
);
if ($this->shouldPushToGithub && ! $this->githubRepository) {
$this->githubRepository = text(
label: 'What should be your full repository name?',
default: $this->name,
hint: "Use `yourorg/$this->name` to create a repo in your organization.",
required: true,
);
}
if ($this->shouldPushToGithub && ! $this->repositoryVisibility) {
$this->repositoryVisibility = select(
label: 'Should the repository be public or private?',
options: [
'public' => 'Public',
'private' => 'Private',
],
default: 'private',
);
}
}
return $this;
}
/**
* Create a GitHub repository and push the git log to it.
*
* @return $this
*/
protected function pushToGithub()
{
if (! $this->shouldPushToGithub) {
return $this;
}
$name = $this->githubRepository ?? $this->name;
$visibility = $this->repositoryVisibility ?? 'private';
$commands = [
"gh repo create {$name} --source=. --push --{$visibility}",
];
$this->runCommands($commands, $this->absolutePath, disableOutput: true);
return $this;
}
/**
* Check if GitHub's GH CLI tool is installed.
*/
protected function isGhInstalled(): bool
{
$process = new Process(['gh', 'auth', 'status']);
$process->run();
return $process->isSuccessful();
}
/**
* Ask for basic input.
*
* @param string $label
* @param bool $hiddenInput
* @return mixed
*/
protected function askForBasicInput($label, $hiddenInput = false)
{
return $this->getHelper('question')->ask(
$this->input,
new SymfonyStyle($this->input, $this->output),
(new Question("{$label}: "))->setHidden($hiddenInput)
);
}
/**
* Validate email address.
*
* @param string $email
* @return bool
*/
protected function validateEmail($email)
{
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
return true;
}
$this->output->write('<error>Invalid email address.</error>'.PHP_EOL);
return false;
}
/**
* Validate password.
*
* @param string $password
* @return bool
*/
protected function validatePassword($password)
{
if (strlen($password) >= 8) {
return true;
}
$this->output->write('<error>The input must be at least 8 characters.</error>'.PHP_EOL);
return false;
}
protected function askToEnableStatamicPro()
{
if ($this->input->getOption('pro') !== false || ! $this->input->isInteractive()) {
return $this;
}
$this->pro = confirm(