View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.jline;
20  
21  import java.io.BufferedReader;
22  import java.io.Console;
23  import java.io.File;
24  import java.io.IOException;
25  import java.io.InputStreamReader;
26  import java.lang.reflect.Method;
27  
28  import org.apache.maven.api.services.MessageBuilder;
29  import org.apache.maven.api.services.MessageBuilderFactory;
30  
31  /**
32   * Colorized message support. Maven only needs ANSI colors in its log output, so there is no terminal library here:
33   * styles are emitted as plain SGR escape sequences, and only when color is enabled.
34   */
35  public class MessageUtils {
36  
37      static MessageBuilderFactory messageBuilderFactory = new JLineMessageBuilderFactory();
38      static volatile boolean tty;
39      static volatile boolean colorEnabled;
40  
41      /**
42       * Detects whether standard output is an ANSI capable terminal and enables color accordingly. Only the CLI calls
43       * this; embedded use never does, so "auto" color stays off there.
44       */
45      public static void systemInstall() {
46          tty = detectAnsiTerminal();
47          colorEnabled = tty;
48          width = 0;
49      }
50  
51      /**
52       * Returns {@code true} if {@link #systemInstall()} detected an ANSI capable terminal on standard output.
53       */
54      public static boolean isTty() {
55          return tty;
56      }
57  
58      public static void setColorEnabled(boolean enabled) {
59          colorEnabled = enabled;
60      }
61  
62      public static boolean isColorEnabled() {
63          return colorEnabled;
64      }
65  
66      /**
67       * Returns the terminal width in columns, or {@code -1} if unknown. Taken from the {@code COLUMNS} environment
68       * variable if set, otherwise (on a detected non-Windows terminal) from {@code stty size}. Computed once.
69       */
70      public static int getTerminalWidth() {
71          int w = width;
72          if (w == 0) {
73              w = detectWidth();
74              width = w;
75          }
76          return w;
77      }
78  
79      static volatile int width; // 0 = not yet detected
80  
81      private static int detectWidth() {
82          int columns = parseWidth(System.getenv("COLUMNS"));
83          if (columns > 0) {
84              return columns;
85          }
86          if (!tty || System.getProperty("os.name", "").startsWith("Windows")) {
87              return -1;
88          }
89          // ponytail: read once, window resizes are not tracked; re-query periodically if a consumer ever needs it
90          try {
91              Process p = new ProcessBuilder("stty", "size")
92                      .redirectInput(new File("/dev/tty"))
93                      .redirectError(new File("/dev/null"))
94                      .start();
95              try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
96                  String size = r.readLine(); // "rows cols"
97                  p.waitFor();
98                  return size == null ? -1 : parseWidth(size.substring(size.indexOf(' ') + 1));
99              }
100         } catch (IOException e) {
101             return -1;
102         } catch (InterruptedException e) {
103             Thread.currentThread().interrupt();
104             return -1;
105         }
106     }
107 
108     static int parseWidth(String s) {
109         try {
110             int w = s == null ? -1 : Integer.parseInt(s.trim());
111             return w > 0 ? w : -1;
112         } catch (NumberFormatException e) {
113             return -1;
114         }
115     }
116 
117     public static MessageBuilder builder() {
118         return messageBuilderFactory.builder();
119     }
120 
121     /**
122      * Remove any ANSI code from a message (colors or other escape sequences).
123      *
124      * @param msg message eventually containing ANSI codes
125      * @return the message with ANSI codes removed
126      */
127     public static String stripAnsiCodes(String msg) {
128         return msg.replaceAll("\u001B\\[[;\\d]*[ -/]*[@-~]", "");
129     }
130 
131     static boolean detectAnsiTerminal() {
132         if ("dumb".equals(System.getenv("TERM"))) {
133             return false;
134         }
135         Console console = System.console();
136         if (console == null) {
137             return false; // stdin or stdout is redirected
138         }
139         try {
140             // Java 22+ returns a console even when redirected; isTerminal() tells the truth
141             Method isTerminal = Console.class.getMethod("isTerminal");
142             if (!(Boolean) isTerminal.invoke(console)) {
143                 return false;
144             }
145         } catch (ReflectiveOperationException e) {
146             // Java < 22: a non-null console already means a terminal
147         }
148         String osName = System.getProperty("os.name", "");
149         if (osName.startsWith("Windows")) {
150             // ponytail: no native call to switch on VT processing, so trust only consoles known to do ANSI already
151             // (Windows Terminal, ConEmu/Cmder, ANSICON, VS Code, mintty & co); legacy conhost users use --color=always
152             // Windows 11 defaults to Windows Terminal, which may not set WT_SESSION when it gets a console via
153             // default-terminal handoff (e.g. shells launched by GitHub Desktop); conhost there is opt-in (#14018)
154             // shortcut: Win11 with conhost as default terminal shows raw escapes, use --color=never; needs a JDK
155             // that reports "Windows 11" (older ones say "Windows 10" and keep the env checks)
156             return osName.startsWith("Windows 11")
157                     || System.getenv("WT_SESSION") != null
158                     || "ON".equals(System.getenv("ConEmuANSI"))
159                     || System.getenv("ANSICON") != null
160                     || "vscode".equals(System.getenv("TERM_PROGRAM"))
161                     || System.getenv("TERM") != null;
162         }
163         return true;
164     }
165 }