2 * SonarQube JavaScript Plugin
3 * Copyright (C) 2011-2016 SonarSource SA
4 * mailto:contact AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package de.example.plugins.custom.javascript.minify;
23 import java.nio.charset.Charset;
26 * An object to assess if a .js file is a minified file or not.
28 * An instance of this class is likely to consider as minified a .js file that,
29 * although formally not minified, has an unusually high average line length.
30 * This situation is typical of files that have been generated by some tool.
31 * Such files are of poor interest as regards a SonarQube analysis.
33 public class MinificationAssessor {
35 private static final int DEFAULT_AVERAGE_LINE_LENGTH_THRESHOLD = 200;
37 private Charset encoding;
40 * Value of the average line length
41 * (= number of chars in the file / number of lines in the file)
42 * below which a file is not assessed as being a minified file.
44 private int averageLineLengthThreshold;
46 public MinificationAssessor(Charset encoding) {
47 this(encoding, DEFAULT_AVERAGE_LINE_LENGTH_THRESHOLD);
50 public MinificationAssessor(Charset encoding, int averageLineLengthThreshold) {
51 this.encoding = encoding;
52 this.averageLineLengthThreshold = averageLineLengthThreshold;
55 public boolean isMinified(File file) {
56 return isJavaScriptFile(file) &&
57 (hasMinifiedFileName(file) || hasExcessiveAverageLineLength(file));
60 private static boolean hasMinifiedFileName(File file) {
61 String fileName = file.getName();
62 return fileName.endsWith("-min.js") || fileName.endsWith(".min.js");
65 private static boolean isJavaScriptFile(File file) {
66 return file.getName().endsWith(".js");
69 private boolean hasExcessiveAverageLineLength(File file) {
70 int averageLineLength = new AverageLineLengthCalculator(file, encoding).getAverageLineLength();
71 return averageLineLength > averageLineLengthThreshold;