Skip to content

Commit e141876

Browse files
committed
Refactor ColorCommand execution logic for improved clarity and error handling
See #13, #18
1 parent e08ace1 commit e141876

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

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

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,38 @@ public class ColorCommand implements Command {
88
public void execute(String[] args, ShellContext context) {
99
if (args.length == 1) {
1010
String color = args[0];
11+
12+
if (color.length() != 2) {
13+
System.out.println("Usage: color <background><text>");
14+
return;
15+
}
16+
1117
String background = String.valueOf(color.charAt(0));
1218
String text = String.valueOf(color.charAt(1));
1319

14-
if (background == text) {
20+
if (background.equals(text)) {
1521
return;
1622
}
1723

18-
int bgIndex = Integer.parseInt(background,16);
19-
int fgIndex = Integer.parseInt(text,16);
24+
int bgIndex, fgIndex;
25+
try {
26+
bgIndex = Integer.parseInt(background,16);
27+
fgIndex = Integer.parseInt(text,16);
28+
} catch (NumberFormatException e) {
29+
System.out.println("Invalid color code. must use two hexadecimal digits.");
30+
System.out.println("Example: color 0A");
31+
return;
32+
}
2033

2134
String[] ansiForeground = {"30","34","32","36","31","35","33","37","90","94","92","96","91","95","93","97"};
2235
String[] ansiBackground = {"40","44","42","46","41","45","43","47","100","104","102","106","101","105","103","107"};
2336

37+
if (bgIndex >= ansiBackground.length || fgIndex >= ansiForeground.length) {
38+
System.out.println("Invalid color code. must use two hexadecimal digits.");
39+
System.out.println("Example: color 0A");
40+
return;
41+
}
42+
2443
String bg = "\033[" + ansiBackground[bgIndex] + "m";
2544
String fg = "\033[" + ansiForeground[fgIndex] + "m";
2645

0 commit comments

Comments
 (0)