Skip to content

Commit 602d1ee

Browse files
Merge pull request #18 from nihaltp/feat/color
Add ColorCommand to change text and background colors using color
2 parents ea53bc9 + 3500a32 commit 602d1ee

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

src/main/java/com/mycmd/App.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ private static void registerCommands(Map<String, Command> commands) {
5252
commands.put("exit", new ExitCommand());
5353
commands.put("ver", new VersionCommand());
5454
commands.put("title", new TitleCommand());
55+
commands.put("color", new ColorCommand());
5556
commands.put("hostname", new HostnameCommand());
5657
commands.put("whoami", new WhoamiCommand());
5758
commands.put("touch", new TouchCommand());
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.mycmd.commands;
2+
3+
import com.mycmd.Command;
4+
import com.mycmd.ShellContext;
5+
6+
public class ColorCommand implements Command {
7+
@Override
8+
public void execute(String[] args, ShellContext context) {
9+
if (args.length == 1) {
10+
String color = args[0];
11+
12+
if (color.length() != 2) {
13+
System.out.println("Usage: color <background><text>");
14+
return;
15+
}
16+
17+
String background = String.valueOf(color.charAt(0));
18+
String text = String.valueOf(color.charAt(1));
19+
20+
if (background.equals(text)) {
21+
return;
22+
}
23+
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+
}
33+
34+
String[] ansiForeground = {"30","34","32","36","31","35","33","37","90","94","92","96","91","95","93","97"};
35+
String[] ansiBackground = {"40","44","42","46","41","45","43","47","100","104","102","106","101","105","103","107"};
36+
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+
43+
String bg = "\033[" + ansiBackground[bgIndex] + "m";
44+
String fg = "\033[" + ansiForeground[fgIndex] + "m";
45+
46+
System.out.println(bg + fg);
47+
}
48+
49+
else {
50+
// set default color
51+
System.out.println("\033[0m");
52+
}
53+
}
54+
}

0 commit comments

Comments
 (0)