View Javadoc
1   /*
2    * #%L
3    * wcm.io
4    * %%
5    * Copyright (C) 2014 wcm.io
6    * %%
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   * #L%
19   */
20  package io.wcm.maven.plugins.nodejs.mojo;
21  
22  import java.io.BufferedReader;
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.io.InputStreamReader;
26  import java.util.regex.Pattern;
27  
28  import org.apache.maven.plugin.logging.Log;
29  
30  /**
31   * Logs the output of the nodejs process
32   */
33  final class NodejsOutputStreamHandler extends Thread {
34  
35    private static final Pattern ERROR_LOG_PATTERN = Pattern.compile(".*(ERROR|FAILED|ERR|npm error).*");
36    private static final Pattern WARNING_LOG_PATTERN = Pattern.compile(".*(warn).*", Pattern.CASE_INSENSITIVE);
37  
38    private final InputStream inputStream;
39    private final Log logger;
40  
41    NodejsOutputStreamHandler(InputStream inputStream, Log logger) {
42      this.inputStream = inputStream;
43      this.logger = logger;
44    }
45  
46    @Override
47    @SuppressWarnings("PMD.AssignmentInOperand")
48    public void run() {
49      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
50      String line;
51      try {
52        while ((line = reader.readLine()) != null) {
53          line = formatLine(line);
54          if (ERROR_LOG_PATTERN.matcher(line).matches()) {
55            logger.error(line);
56          }
57          else if (WARNING_LOG_PATTERN.matcher(line).matches()) {
58            logger.warn(line);
59          }
60          else {
61            logger.info(line);
62          }
63        }
64      }
65      catch (IOException ex) {
66        logger.error(ex);
67      }
68    }
69  
70    /**
71     * Format line for maven output
72     * @param line Line string
73     * @return Formatted line
74     */
75    private String formatLine(String line) {
76      // Remove ANSI VT100  control characters
77      String formatted = line.replaceAll("\u001B\\[[\\d;]*[^\\d;]", "");
78      return "[nodejs] " + formatted;
79    }
80  
81  }