package com.squareup.spoon;

import com.google.common.base.Function;
import org.jacoco.core.tools.ExecFileLoader;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;

import static com.google.common.collect.Collections2.transform;
import static com.squareup.spoon.SpoonDeviceRunner.COVERAGE_DIR;
import static com.squareup.spoon.SpoonDeviceRunner.COVERAGE_FILE;
import static com.squareup.spoon.SpoonUtils.sanitizeSerial;

final class SpoonCoverageMerger {
  private static final String MERGED_COVERAGE_FILE = "merged-coverage.ec";
  private ExecFileLoader execFileLoader;

  public SpoonCoverageMerger() {
    this.execFileLoader = new ExecFileLoader();
  }

  public void mergeCoverageFiles(Set<String> serials, File outputDirectory) throws IOException {
    Collection<String> sanitizeSerials = transform(serials, toSanitizeSerials());
    for (String serial : sanitizeSerials) {
      String coverageFilePath = COVERAGE_DIR + "/" + serial + "/" + COVERAGE_FILE;
      execFileLoader.load(new File(outputDirectory, coverageFilePath));
    }
    String mergedCoverageFile = COVERAGE_DIR + "/" + MERGED_COVERAGE_FILE;
    execFileLoader.save(new File(outputDirectory, mergedCoverageFile), false);
  }

  private Function<String, String> toSanitizeSerials() {
    return new Function<String, String>() {
      @Override
      public String apply(String serials) {
        return sanitizeSerial(serials);
      }
    };
  }
}

@@ -26,94 +26,8 @@
 n;%0A%0A
-import com.google.common.base.Function;%0Aimport org.jacoco.core.tools.ExecFileLoader;%0A%0A
 impo
@@ -43,16 +43,16 @@
 o.File;%0A
+
 import j
@@ -121,16 +121,61 @@
 til.Set;
+%0Aimport org.jacoco.core.tools.ExecFileLoader;
 %0A%0Aimport
@@ -366,68 +366,8 @@
 ILE;
-%0Aimport static com.squareup.spoon.SpoonUtils.sanitizeSerial;
 %0A%0Afi
@@ -758,19 +758,29 @@
 erials, 
-toS
+SpoonUtils::s
 anitizeS
@@ -784,19 +784,16 @@
 zeSerial
-s()
 );%0A    f
@@ -1063,24 +1063,24 @@
 ERAGE_FILE;%0A
+
     execFile
@@ -1153,228 +1153,7 @@
 %0A  %7D
-%0A%0A  private Function%3CString, String%3E toSanitizeSerials() %7B%0A    return new Function%3CString, String%3E() %7B%0A      @Override%0A      public String apply(String serials) %7B%0A        return sanitizeSerial(serials);%0A      %7D%0A    %7D;%0A  %7D
 %0A%7D%0A

Add some Java 8-isms to coverage merger.