Ind.ie is now Small Technology Foundation.
frankencover.it 11.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
#!/usr/bin/env groovy
import groovy.io.FileType
import org.apache.tools.ant.util.FileUtils

import static org.fusesource.jansi.Ansi.Attribute.INTENSITY_BOLD
import static org.fusesource.jansi.Ansi.Attribute.INTENSITY_BOLD_OFF
import static org.fusesource.jansi.Ansi.Color.RED
import static org.fusesource.jansi.Ansi.Color.GREEN
import static org.fusesource.jansi.Ansi.Color.YELLOW
import static org.fusesource.jansi.Ansi.Color.DEFAULT
import static org.fusesource.jansi.Ansi.ansi

new FrankenCliReader(args).execute()

class FrankenCliReader
{

    public String[] args
    public CliBuilder cli

    public FrankenCliReader(args)
    {
        super()
        this.args = args
        this.cli = initCliBuilder()
    }

    public void execute()
    {
        def opt = cli.parse(args)
        if (!opt) {
            System.exit(-1)
        }
        if (opt.h) {
            cli.usage()
        }


        String outPutDir = opt.getProperty("o") ?: "build/reports"
        String sourceDir = opt.getProperty("s")

        //Stop some non-source tree symbols leaking into the report
        def reportConfig = new ReportConfig(directory: "${sourceDir}", excludeSymbols:
                ["main.m",
                 "queue.h",
                 "once.h",
                 "CGGeometry.h",
                 "MKGeometry.h",
                 "NSRange.h"])

        def ideConfig = new IDEConfig(withXcode: true, withAppCodeIfAvailable: true)
        if (opt.getProperty("x") || opt.getProperty("a")) {
            ideConfig.withAppCodeIfAvailable = opt.getProperty("a")
            ideConfig.withXcode = opt.getProperty("x")
        }
        if (opt.getProperty("p")) {
            ideConfig.customDirectory = opt.getProperty("p")
        }

        Double requiredCoverage = opt.getProperty("r") ? new Double(opt.getProperty("r").replaceAll("%", "")) : 0
        def generator = new ReportGenerator(outPutDir, requiredCoverage, reportConfig, ideConfig, new AntBuilder(), opt.getProperty("d"))
        generator.generate()
        System.exit(generator.failed ? -1 : 0)
    }

    private CliBuilder initCliBuilder()
    {
        def usageInstructions = """groovy http://frankencover.it/with -s <sourceDir> <options>\n\n
        |For instructions on configuring Xcode to output coverage data, visit http://frankencover.it\n\n
        """.stripMargin().stripIndent()
        CliBuilder builder = new CliBuilder(usage: usageInstructions)
        builder.with
                {
                    h(longOpt: 'help', 'Help - Usage Information')
                    s(longOpt: 'source-dir', 'The source directory to generate coverage for', args: 1, type: String, required: true)
                    o(longOpt: 'output-dir', 'The output directory to write coverage report', args: 1, type: String, required: false)
                    p(longOpt: 'products-dir', 'Use custom directory to search for code coverage files, instead of the IDE default', args: 1, type: String, required: false)
                    r(longOpt: 'required-coverage', 'Required line coverage', args: 1, type: String, required: false)
                    a(longOpt: 'appcode', 'Search in AppCode\'s output directory. (default is both Xcode and AppCode\'s output dirs)', args: 0, type: boolean, required: false)
                    x(longOpt: 'xcode', 'Search in Xcode\'s output directory. (default is both Xcode and AppCode\'s output dirs)', args: 0, type: boolean, required: false)
                    d(longOpt: 'debug', 'Print debugging output.', type: boolean, required: false)
                    //TODO: Do we need the following opt?
                    //e(longOpt: 'exclude', 'Comma separated list of symbols to exclude from report', args: 1, type: String, required: false)
                }
        return builder
    }
}


class ReportGenerator
{
    String outputDir
    Double requiredCoverage
    ReportConfig reportConfig
    IDEConfig ideConfig
    AntBuilder ant
    boolean debug

    boolean failed

    private File reportLocation

    // ================================================================ //
    // Constructors

    ReportGenerator(outputDir, requiredCoverage, reportConfig, ideConfig, ant, debug)
    {
        this.outputDir = outputDir
        this.requiredCoverage = requiredCoverage
        this.reportConfig = reportConfig
        this.ideConfig = ideConfig
        this.ant = ant
        this.reportLocation = new File("${outputDir}/coverage")
        this.debug = debug

        print ansi().a(INTENSITY_BOLD)
        print ansi().fg(YELLOW).a("\n▸ ")
        print ansi().fg(DEFAULT).a("Code Coverage ").reset().a("${reportConfig.directory}\n")
    }

    // ================================================================ //
    // Public

    public void generate()
    {
        def tempDir = "${outputDir}/temp"
        def collationDir = "${tempDir}/coverage-data-collate"
        def coverageData = "${tempDir}/coverage-data"
        def coverageInfoFile = "${tempDir}/coverage.info"
        def genHtmlCmd = "genhtml --no-function-coverage --no-branch-coverage"
        def excludeSymbols = reportConfig.excludeSymbols.join(" ")

        def script = """\
            |#!/bin/sh
            |mkdir -p ${collationDir}
            |mkdir -p ${coverageData}
            |find ${ideConfig.searchDirectories()} ${reportConfig.dataFileNames()} | rsync --files-from=- / ${collationDir}
            |find ${collationDir} -type file -exec cp -fr {} ${coverageData} \\;
            |rm -fr ${collationDir}
            |geninfo ${coverageData}/*.gcno --no-recursion --output-filename ${coverageInfoFile}.temp
            |lcov -r ${coverageInfoFile}.temp ${excludeSymbols} > ${coverageInfoFile}
            |${genHtmlCmd} -o ${reportLocation.absolutePath} --prefix ${reportConfig.prefix()} ${coverageInfoFile}
            """.stripMargin()


        if (debug) println(script)
        
        Process process = "bash".execute();
        process.outputStream.write(script.getBytes())
        process.outputStream.close()
        process.waitFor()

        printSummary(coverageInfoFile)
        if (!debug) "rm -fr ${tempDir}".execute().waitFor()

    }

    private void printSummary(coverageInfoFile)
    {
        OutputStream os = new ByteArrayOutputStream()
        Process summary = "lcov --summary ${coverageInfoFile}".execute()
        summary.consumeProcessOutput(os, os)
        summary.waitFor()


        def parser = new ReportParser(os.toString())
        parser.print()

        if (parser.lineCoveragePercent < requiredCoverage) {
            print ansi().a(INTENSITY_BOLD).fg(RED).a("  <----- Required coverage is ${requiredCoverage}%").reset()
            failed = true
        }
        print ansi().a("\n").reset()
        print ansi().a("   📊  full report..: ${outputDir}/coverage/index.html")
        print ansi().a("\n\n").reset()
    }


}


class ReportParser
{

    Double lineCoveragePercent;
    String lineCoverageDetail;

    // ================================================================ //
    // Constructors

    ReportParser(String summary)
    {
        boolean linesFound = false
        summary.eachLine {
            if (it.contains("lines.....")) {
                def lineSummaries = it.split("%")
                lineCoveragePercent = lineSummaries[0].split()[1].toDouble()
                lineCoverageDetail = lineSummaries[1].trim()
                linesFound = true
            }
        }
        if (!linesFound) {
            throw new RuntimeException(ansi().a(INTENSITY_BOLD).fg(RED).a("\n\n✗ Coverage data not found\n").reset()
                    .a("    ☐ To see how to set build flags, visit http://frankencover.it\n")
                    .a("    ☐ Exercise your code with tests or otherwise.\n")
                    .a("    ☐ Run this script again.\n\n").toString())
        };
    }

    // ================================================================ //
    // Public

    void print()
    {

        print ansi().a(INTENSITY_BOLD)
        if (lineCoveragePercent < 60) {
            print ansi().fg(RED).a("    ✗").reset()
            print ansi().a(" lines........: ")
            print ansi().fg(RED)
        }
        else if (lineCoveragePercent < 79) {
            print ansi().fg(YELLOW).a("    ⚠").reset()
            print ansi().a(" lines........: ")
            print ansi().fg(YELLOW)
        }
        else {
            print ansi().fg(GREEN).a("    ✓").reset()
            print ansi().a(" lines........: ")
            print ansi().fg(GREEN)
        }

        print ansi().a(INTENSITY_BOLD)
        print ansi().a("${lineCoveragePercent}% ").reset()
        print ansi().a("${lineCoverageDetail}")
    }


}

class ReportConfig
{

    String directory
    List<String> excludeSymbols

    //Private
    private List<String> fileNames;

    // ================================================================ //
    // Public

    String prefix()
    {
        def prefix
        if (directory.startsWith("/")) {
            prefix = directory
        }
        else {
            def baseDir = new File(".").getAbsolutePath()
            prefix = baseDir.substring(0, baseDir.length() - 1) + "${directory}"
        }
        return prefix
    }

    String dataFileNames()
    {
        def dataFiles = new ArrayList<String>();
        cachedFileNames().each { fileName ->
            dataFiles.add("-name ${fileName}.gcno")
            dataFiles.add("-name ${fileName}.gcda")
        }
        dataFiles.join(' -o ')
    }

    public void setDirectory(String directory)
    {
        this.directory = directory.endsWith("/") ? directory : directory + "/"
    }

    // ================================================================ //
    // Private

    private List<String> cachedFileNames()
    {
        if (!fileNames) {
            fileNames = new ArrayList<String>()

            def searchDir = directory.startsWith("/") ? new File(directory) : new File("./${directory}")

            searchDir.eachFileRecurse(FileType.FILES) { file ->
                def fileName = file.name;
                if (fileName.endsWith(".h")) {
                    fileNames << fileName.substring(0, fileName.length() - 2)
                }
            }
        }

        //println ("Filenames: " + fileNames)
        fileNames
    }


}

class IDEConfig
{

    public boolean withAppCodeIfAvailable
    public boolean withXcode
    public String customDirectory

    def cachedAppCodeDir = null

    public String xcodeDir()
    {
        return "~/Library/Developer/Xcode/DerivedData"
    }

    public String appCodeDirOrNull()
    {
        if (cachedAppCodeDir == null) {
            def highestAppCodeInstalled = 0
            new File("${System.getProperty("user.home")}/Library/Caches").eachFile(FileType.DIRECTORIES) { directory ->
                def dir = directory.name;
                if (dir.startsWith("appCode")) {
                    def appCodeVersion = dir.replaceAll("[^\\d.]", "").toInteger()
                    highestAppCodeInstalled = appCodeVersion > highestAppCodeInstalled ? appCodeVersion : highestAppCodeInstalled
                }
            }
            if (highestAppCodeInstalled) {
                cachedAppCodeDir = "~/Library/Caches/appCode${highestAppCodeInstalled}"
            }
        }
        return cachedAppCodeDir
    }

    public String searchDirectories()
    {
        return customDirectory ? customDirectory : ideDirectories()
    }

    public void setCustomDirectory(String customDirectory) {
        println "setting custom dir to " + customDirectory
        this.customDirectory = customDirectory
        this.withAppCodeIfAvailable = false
        this.withXcode = false
    }

    private String ideDirectories()
    {
        def searchDirectories = new StringBuilder()
        if (withXcode) {
            searchDirectories.append(xcodeDir())
            searchDirectories.append(" ")
        }
        if (withAppCodeIfAvailable && appCodeDirOrNull() != null) {
            searchDirectories.append(appCodeDirOrNull())
        }
        return searchDirectories.toString()
    }

}