4
4
5
5
use App \InitializesCommands ;
6
6
use App \Shell \Docker ;
7
+ use Illuminate \Support \Collection ;
7
8
use Illuminate \Support \Str ;
8
9
use LaravelZero \Framework \Commands \Command ;
9
10
11
+ use function Laravel \Prompts \select ;
12
+
10
13
class LogCommand extends Command
11
14
{
12
15
use InitializesCommands;
13
16
17
+ const MENU_TITLE = 'Takeout containers logs ' ;
18
+
14
19
protected $ signature = 'logs {containerId?} ' ;
15
20
protected $ description = 'Display container logs. ' ;
16
21
protected $ docker ;
@@ -20,17 +25,25 @@ public function handle(Docker $docker): void
20
25
$ this ->docker = $ docker ;
21
26
$ this ->initializeCommand ();
22
27
23
- $ container = $ this ->argument ('containerId ' );
28
+ $ loggableContainers = $ this ->loggableContainers ();
29
+
30
+
31
+ if ($ loggableContainers ->isEmpty ()) {
32
+ $ this ->info ("No Takeout containers available. \n" );
33
+
34
+ return ;
35
+ }
24
36
25
- if (! $ container ) {
26
- $ this ->error ( " Please pass a valid container ID. \n" );
37
+ if (filled ( $ service = $ this -> argument ( ' containerId ' )) ) {
38
+ $ this ->logsByServiceNameOrContainerId ( $ service , $ loggableContainers );
27
39
28
40
return ;
29
41
}
30
42
31
- $ this ->logs ($ container );
43
+ $ this ->logs ($ this -> selectOptions ( $ loggableContainers ) );
32
44
}
33
45
46
+
34
47
public function logs (string $ container ): void
35
48
{
36
49
if (Str::contains ($ container , ' - ' )) {
@@ -39,4 +52,41 @@ public function logs(string $container): void
39
52
40
53
$ this ->docker ->logContainer ($ container );
41
54
}
55
+
56
+ private function loggableContainers (): Collection
57
+ {
58
+ return $ this ->docker ->activeTakeoutContainers ()->mapWithKeys (function ($ container ) {
59
+ return [$ container ['container_id ' ] => str_replace ('TO-- ' , '' , $ container ['names ' ])];
60
+ });
61
+ }
62
+
63
+ private function selectOptions ($ stoppableContainers )
64
+ {
65
+ return select (
66
+ label: self ::MENU_TITLE ,
67
+ options: $ stoppableContainers
68
+ );
69
+ }
70
+
71
+ private function logsByServiceNameOrContainerId (string $ service , Collection $ loggableContainers ): void
72
+ {
73
+ $ containersByServiceName = $ loggableContainers
74
+ ->filter (function ($ containerName , $ key ) use ($ service ) {
75
+ return Str::startsWith ($ containerName , $ service ) || $ key === $ service ;
76
+ });
77
+
78
+ if ($ containersByServiceName ->isEmpty ()) {
79
+ $ this ->info ('No containers found for ' . $ service );
80
+
81
+ return ;
82
+ }
83
+
84
+ if ($ containersByServiceName ->count () === 1 ) {
85
+ $ this ->logs ($ containersByServiceName ->keys ()->first ());
86
+
87
+ return ;
88
+ }
89
+
90
+ $ this ->logs ($ this ->selectOptions ($ containersByServiceName ));
91
+ }
42
92
}
0 commit comments