Skip to content

Commit 7252ece

Browse files
committed
refactor: Improve input handling in TimeoutCommand for better interrupt detection
1 parent 608ce62 commit 7252ece

File tree

1 file changed

+31
-12
lines changed

1 file changed

+31
-12
lines changed

src/main/java/com/mycmd/commands/TimeoutCommand.java

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -64,26 +64,39 @@ public void execute(String[] args, ShellContext context) {
6464
return;
6565
}
6666

67-
Thread inputThread =
68-
new Thread(
69-
() -> {
70-
try {
71-
System.in.read();
72-
} catch (IOException e) {
73-
// Ignore
74-
}
75-
});
76-
inputThread.setDaemon(true);
67+
AtomicBoolean interrupted = new AtomicBoolean(false);
68+
Thread inputThread = null;
7769

7870
if (!noBreak) {
71+
inputThread =
72+
new Thread(
73+
() -> {
74+
try {
75+
int r;
76+
// Read until a newline is encountered so we only exit on Enter
77+
while ((r = System.in.read()) != -1) {
78+
if (r == '\n') {
79+
interrupted.set(true);
80+
break;
81+
}
82+
}
83+
} catch (IOException e) {
84+
// Ignore: if System.in is closed or an I/O error occurs we
85+
// cannot reliably wait for Enter; treat as no-interrupt.
86+
}
87+
});
88+
inputThread.setDaemon(true);
7989
inputThread.start();
8090
}
8191
System.out.println();
8292

8393
for (; seconds > 0; seconds--) {
84-
if (!noBreak && !inputThread.isAlive()) {
94+
if (!noBreak && interrupted.get()) {
8595
System.out.println("\r");
8696
System.out.println();
97+
if (inputThread != null && inputThread.isAlive()) {
98+
inputThread.interrupt();
99+
}
87100
return;
88101
}
89102

@@ -104,13 +117,19 @@ public void execute(String[] args, ShellContext context) {
104117
break;
105118
}
106119
}
120+
107121
try {
122+
// Drain any remaining bytes so subsequent commands don't immediately see
123+
// leftover input. This is a best-effort drain; System.in.available() may
124+
// not be supported on all streams, but for typical console streams it helps.
108125
while (System.in.available() > 0) {
109126
System.in.read();
110127
}
111128
} catch (IOException e) {
112-
// Ignore
129+
// Ignore: if we can't drain the stream it's non-fatal; any leftover input
130+
// will be handled by the next read and is acceptable.
113131
}
132+
114133
System.out.println("\r");
115134
System.out.println();
116135
}

0 commit comments

Comments
 (0)