Java 类com.facebook.buck.step.ExecutionContext 实例源码

项目:buck-cutom    文件:DxStepTest.java   
@Test
public void testDxCommandOptimizeNoJumbo() {
  // Context with --verbose 2.
  ExecutionContext context = createExecutionContext(2);
  Function<Path, Path> pathAbsolutifier = context.getProjectFilesystem().getAbsolutifier();

  DxStep dx = new DxStep(SAMPLE_OUTPUT_PATH, SAMPLE_FILES_TO_DEX);

  String expected = String.format("%s --output %s %s",
      EXPECTED_DX_PREFIX,
      SAMPLE_OUTPUT_PATH,
      Joiner.on(' ').join(Iterables.transform(SAMPLE_FILES_TO_DEX, pathAbsolutifier)));
  MoreAsserts.assertShellCommands(
      "Neither --no-optimize nor --force-jumbo should be present.",
      ImmutableList.of(expected),
      ImmutableList.<Step>of(dx),
      context);
  verifyAll();
}
项目:buck-cutom    文件:SymlinkFilesIntoDirectoryStep.java   
@Override
public int execute(ExecutionContext context) {
  // Note that because these paths are resolved to absolute paths, the symlinks will be absolute
  // paths, as well.
  ProjectFilesystem projectFilesystem = context.getProjectFilesystem();
  Path outDir = projectFilesystem.resolve(this.outDir);
  Path srcDir = projectFilesystem.resolve(this.srcDir);

  for (Path entry : entries) {
    Path link = outDir.resolve(entry);
    Path target = srcDir.resolve(entry);
    try {
      Files.createDirectories(link.getParent());
      Files.createSymbolicLink(link, target);
    } catch (IOException e) {
      context.logError(e, "Failed to create symlink from %s to %s.", link, target);
      return 1;
    }
  }
  return 0;
}
项目:buck-cutom    文件:TouchStepTest.java   
@Test
public void testGetShellCommand() {
  Path someFile = Paths.get("a/file.txt");
  TouchStep touchStep = new TouchStep(someFile);

  ProjectFilesystem projectFilesystem = new FakeProjectFilesystem() {
    @Override
    public Path resolve(Path relativePath) {
      return Paths.get("/abs/path").resolve(relativePath);
    }
  };
  ExecutionContext executionContext = TestExecutionContext
      .newBuilder()
      .setProjectFilesystem(projectFilesystem)
      .build();
  assertEquals(
      ImmutableList.of("touch", "/abs/path/a/file.txt"),
      touchStep.getShellCommandInternal(executionContext));
}
项目:buck-cutom    文件:DxStep.java   
private int executeInProcess(ExecutionContext context) {
  ImmutableList<String> argv = getShellCommandInternal(context);

  // The first arguments should be ".../dx --dex".  Strip them off
  // because we bypass the dispatcher and go straight to the dexer.
  Preconditions.checkState(argv.get(0).endsWith("/dx"));
  Preconditions.checkState(argv.get(1).equals("--dex"));
  ImmutableList<String> args = argv.subList(2, argv.size());

  try {
    return new com.android.dx.command.dexer.Main().run(
        args.toArray(new String[args.size()]),
        context.getStdOut(),
        context.getStdErr()
    );
  } catch (IOException e) {
    e.printStackTrace(context.getStdErr());
    return 1;
  }
}
项目:buck-cutom    文件:Genrule.java   
public AbstractGenruleStep createGenruleStep() {
  // The user's command (this.cmd) should be run from the directory that contains only the
  // symlinked files. This ensures that the user can reference only the files that were declared
  // as srcs. Without this, a genrule is not guaranteed to be hermetic.
  File workingDirectory = new File(absolutePathToSrcDirectory.toString());

  return new AbstractGenruleStep(
      getType(),
      getBuildTarget(),
      new CommandString(cmd, bash, cmdExe),
      getDeps(),
      workingDirectory) {
    @Override
    protected void addEnvironmentVariables(
        ExecutionContext context,
        ImmutableMap.Builder<String, String> environmentVariablesBuilder) {
      Genrule.this.addEnvironmentVariables(context, environmentVariablesBuilder);
    }
  };
}
项目:buck-cutom    文件:TestCommandTest.java   
@Test
public void testIsTestRunRequiredForTestInDebugMode()
    throws IOException, ExecutionException, InterruptedException {
  ExecutionContext executionContext = createMock(ExecutionContext.class);
  expect(executionContext.isDebugEnabled()).andReturn(true);

  replay(executionContext);

  assertTrue(
      "In debug mode, test should always run regardless of any cached results since " +
          "the user is expecting to hook up a debugger.",
      TestCommand.isTestRunRequiredForTest(
          createMock(TestRule.class),
          createMock(CachingBuildEngine.class),
          executionContext,
          createMock(TestRuleKeyFileHelper.class),
          true,
          false));

  verify(executionContext);
}
项目:buck-cutom    文件:PrebuiltJar.java   
@Override
public int execute(ExecutionContext context) {
  // TODO(simons): Because binaryJar could be a generated file, it may not be bit-for-bit
  // identical when generated across machines. Therefore, we should calculate its ABI based on
  // the contents of its .class files rather than just hashing its contents.
  String fileSha1;
  try {
    fileSha1 = context.getProjectFilesystem().computeSha1(binaryJar.resolve());
  } catch (IOException e) {
    context.logError(e, "Failed to calculate ABI for %s.", binaryJar);
    return 1;
  }

  Sha1HashCode abiKey = new Sha1HashCode(fileSha1);
  buildableContext.addMetadata(AbiRule.ABI_KEY_ON_DISK_METADATA, abiKey.getHash());

  return 0;
}
项目:buck-cutom    文件:ExopackageInstaller.java   
public ExopackageInstaller(
    ExecutionContext context,
    AdbHelper adbHelper,
    InstallableApk apkRule) {
  this.adbHelper = Preconditions.checkNotNull(adbHelper);
  this.projectFilesystem = context.getProjectFilesystem();
  this.eventBus = context.getBuckEventBus();
  this.apkRule = Preconditions.checkNotNull(apkRule);
  this.packageName = AdbHelper.tryToExtractPackageNameFromManifest(apkRule, context);
  this.dataRoot = "/data/local/tmp/exopackage/" + packageName;

  Preconditions.checkArgument(AdbHelper.PACKAGE_NAME_PATTERN.matcher(packageName).matches());

  Optional<InstallableApk.ExopackageInfo> exopackageInfo = apkRule.getExopackageInfo();
  Preconditions.checkArgument(exopackageInfo.isPresent());
  this.exopackageInfo = exopackageInfo.get();
}
项目:buck-cutom    文件:JavacInMemoryStepIntegrationTest.java   
@Test
public void testGetDescription() throws IOException {
  JavacInMemoryStep javac = createJavac(/* withSyntaxError */ false);
  ExecutionContext executionContext = createExecutionContext();
  String pathToOutputDir = new File(tmp.getRoot(), "out").getAbsolutePath();
  String pathToAbiFile = new File(tmp.getRoot(), "abi").getAbsolutePath();
  assertEquals(
      String.format("javac -source %s -target %s -g " +
          "-processorpath %s " +
          "-processor %s " +
          "-A%s=%s " +
          "-d %s " +
          "-classpath '' " +
          "@" + pathToSrcsList.toString(),
          JavaCompilerEnvironment.TARGETED_JAVA_VERSION,
          JavaCompilerEnvironment.TARGETED_JAVA_VERSION,
          AbiWritingAnnotationProcessingDataDecorator.ABI_PROCESSOR_CLASSPATH,
          AbiWriterProtocol.ABI_ANNOTATION_PROCESSOR_CLASS_NAME,
          AbiWriterProtocol.PARAM_ABI_OUTPUT_FILE,
          pathToAbiFile,
          pathToOutputDir),
      javac.getDescription(executionContext));
}
项目:buck-cutom    文件:JavacInMemoryStepTest.java   
@Test
public void testJavacCommand() {
  ExecutionContext context = TestExecutionContext.newInstance();

  JavacInMemoryStep firstOrder = createTestStep(BuildDependencies.FIRST_ORDER_ONLY);
  JavacInMemoryStep warn = createTestStep(BuildDependencies.WARN_ON_TRANSITIVE);
  JavacInMemoryStep transitive = createTestStep(BuildDependencies.TRANSITIVE);

  assertEquals(
      String.format("javac -source %s -target %s -g -d . -classpath foo.jar @%s",
          TARGETED_JAVA_VERSION, TARGETED_JAVA_VERSION, PATH_TO_SRCS_LIST),
      firstOrder.getDescription(context));
  assertEquals(
      String.format("javac -source %s -target %s -g -d . -classpath foo.jar @%s",
          TARGETED_JAVA_VERSION, TARGETED_JAVA_VERSION, PATH_TO_SRCS_LIST),
      warn.getDescription(context));
  assertEquals(
      String.format("javac -source %s -target %s -g -d . -classpath bar.jar%sfoo.jar @%s",
          TARGETED_JAVA_VERSION, TARGETED_JAVA_VERSION, File.pathSeparator, PATH_TO_SRCS_LIST),
      transitive.getDescription(context));
}
项目:buck-cutom    文件:SymlinkTreeStep.java   
@Override
public int execute(ExecutionContext context) {
  for (ImmutableMap.Entry<Path, Path> ent : links.entrySet()) {
    Path target = context.getProjectFilesystem().resolve(ent.getValue());
    Path link = context.getProjectFilesystem().resolve(root.resolve(ent.getKey()));
    try {
      context.getProjectFilesystem().mkdirs(link.getParent());
      context.getProjectFilesystem().createSymLink(target, link, true /* force */);
    } catch (IOException e) {
      String msg = String.format("failed creating linking \"%s\" -> \"%s\"", link, target);
      context.logError(e, msg);
      e.printStackTrace(context.getStdErr());
      return 1;
    }
  }
  return 0;
}
项目:buck-cutom    文件:RmStep.java   
public ImmutableList<String> getShellCommand(ExecutionContext context) {
  ImmutableList.Builder<String> args = ImmutableList.builder();
  args.add("rm");

  if (shouldRecurse) {
    args.add("-r");
  }

  if (shouldForceDeletion) {
    args.add("-f");
  }

  Path absolutePath = context.getProjectFilesystem().resolve(toDelete);
  args.add(absolutePath.toString());

  return args.build();
}
项目:buck-cutom    文件:RmStep.java   
@Override
public int execute(ExecutionContext context) {
  ProjectFilesystem projectFilesystem = context.getProjectFilesystem();
  if (shouldRecurse) {
    // Delete a folder recursively
    try {
      projectFilesystem.rmdir(toDelete);
    } catch (IOException e) {
      if (shouldForceDeletion) {
        return 0;
      }
      e.printStackTrace(context.getStdErr());
      return 1;
    }
  } else {
    // Delete a single file
    File file = projectFilesystem.resolve(toDelete).toFile();
    if (!file.delete() && !shouldForceDeletion) {
      return 1;
    }
  }
  return 0;
}
项目:buck-cutom    文件:UnzipStepTest.java   
@Test
public void testGetShellCommand() {
  Path zipFile = Paths.get("the/zipfile.zip");
  Path outputDirectory = Paths.get("an/output/dir");
  UnzipStep unzipStep = new UnzipStep(zipFile, outputDirectory);

  ProjectFilesystem projectFilesystem = new FakeProjectFilesystem() {
    @Override
    public Path resolve(Path relativePath) {
      return Paths.get("/abs/path").resolve(relativePath);
    }
  };
  ExecutionContext executionContext = TestExecutionContext
      .newBuilder()
      .setProjectFilesystem(projectFilesystem)
      .build();
  assertEquals(
      "unzip /abs/path/the/zipfile.zip -d /abs/path/an/output/dir",
      unzipStep.getDescription(executionContext));
}
项目:buck-cutom    文件:ProGuardObfuscateStepTest.java   
@Test
public void testSdkConfigArgs() {
  ExecutionContext context = createMock(ExecutionContext.class);
  AndroidPlatformTarget target = createMock(AndroidPlatformTarget.class);
  expect(context.getProjectDirectoryRoot()).andStubReturn(Paths.get("root"));
  expect(context.getAndroidPlatformTarget()).andStubReturn(target);
  expect(target.getProguardConfig()).andStubReturn(Paths.get("sdk-default.pro"));
  expect(target.getOptimizedProguardConfig()).andStubReturn(Paths.get("sdk-optimized.pro"));
  expect(target.getBootclasspathEntries()).andStubReturn(ImmutableList.<Path>of());
  replayAll();

  checkSdkConfig(context, ProGuardObfuscateStep.SdkProguardType.DEFAULT, "sdk-default.pro");
  checkSdkConfig(context, ProGuardObfuscateStep.SdkProguardType.OPTIMIZED, "sdk-optimized.pro");
  checkSdkConfig(context, ProGuardObfuscateStep.SdkProguardType.NONE, null);

  verifyAll();
}
项目:buck-cutom    文件:CopyStep.java   
@Override
public String getDescription(ExecutionContext context) {
  ImmutableList.Builder<String> args = ImmutableList.builder();
  args.add("cp");
  switch (copySourceMode) {
    case FILE:
      args.add(source.toString());
      break;
    case DIRECTORY_AND_CONTENTS:
      args.add("-R");
      args.add(source.toString());
      break;
    case DIRECTORY_CONTENTS_ONLY:
      args.add("-R");
      // BSD and GNU cp have different behaviors with -R:
      // http://jondavidjohn.com/blog/2012/09/linux-vs-osx-the-cp-command
      //
      // To work around this, we use "sourceDir/*" as the source to
      // copy in this mode.
      args.add(source.resolve("*").toString());
      break;
  }
  args.add(destination.toString());
  return Joiner.on(" ").join(args.build());
}
项目:buck-cutom    文件:Genrule.java   
protected void addEnvironmentVariables(ExecutionContext context,
    ImmutableMap.Builder<String, String> environmentVariablesBuilder) {
  environmentVariablesBuilder.put("SRCS", Joiner.on(' ').join(srcsToAbsolutePaths.values()));
  environmentVariablesBuilder.put("OUT", getAbsoluteOutputFilePath());

  final Set<String> depFiles = Sets.newHashSet();
  final Set<BuildRule> processedBuildRules = Sets.newHashSet();
  for (BuildRule dep : getDeps()) {
    transformNames(processedBuildRules, depFiles, dep);
  }

  environmentVariablesBuilder.put(
      "GEN_DIR", relativeToAbsolutePathFunction.apply(BuckConstant.GEN_PATH).toString());
  environmentVariablesBuilder.put("DEPS", Joiner.on(' ').skipNulls().join(depFiles));
  environmentVariablesBuilder.put("SRCDIR", absolutePathToSrcDirectory.toString());
  environmentVariablesBuilder.put("TMP", absolutePathToTmpDirectory.toString());

  Optional<AndroidPlatformTarget> optionalAndroid = context.getAndroidPlatformTargetOptional();
  if (optionalAndroid.isPresent()) {
    AndroidPlatformTarget android = optionalAndroid.get();

    environmentVariablesBuilder.put("DX", android.getDxExecutable().toString());
    environmentVariablesBuilder.put("ZIPALIGN", android.getZipalignExecutable().toString());
  }
}
项目:buck-cutom    文件:MoreAsserts.java   
/**
 * Invokes the {@link Step#getDescription(ExecutionContext)} method on each of the observed steps
 * to create a list of strings and compares it to the expected value.
 */
public static void assertSteps(
    String userMessage,
    List<String> expectedStepDescriptions,
    List<Step> observedSteps,
    final ExecutionContext executionContext) {
  ImmutableList<String> commands = FluentIterable
      .from(observedSteps)
      .transform(new Function<Step, String>() {
        @Override
        public String apply(Step step) {
          return step.getDescription(executionContext);
        }
      })
      .toList();
  assertListEquals(
      userMessage,
      expectedStepDescriptions,
      commands);
}
项目:buck-cutom    文件:SmartDexingStep.java   
@Override
public String getDescription(ExecutionContext context) {
  StringBuilder b = new StringBuilder();
  b.append(getShortName());
  b.append(' ');

  Multimap<Path, Path> outputToInputs = outputToInputsSupplier.get();
  for (Path output : outputToInputs.keySet()) {
    b.append("-out ");
    b.append(output.toString());
    b.append("-in ");
    Joiner.on(':').appendTo(b,
        Iterables.transform(outputToInputs.get(output), Functions.toStringFunction()));
  }

  return b.toString();
}
项目:buck-cutom    文件:PythonTest.java   
private Step getRunTestStep() {
  return new ShellStep() {

    @Override
    protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
      ProjectFilesystem fs = context.getProjectFilesystem();
      return ImmutableList.of(
          fs.resolve(binary.resolve()).toString(),
          "-o", fs.resolve(getPathToTestOutputResult()).toString());
    }

    @Override
    public String getShortName() {
      return "pyunit";
    }

  };
}
项目:buck-cutom    文件:GenerateManifestStepTest.java   
@Test
public void testManifestGeneration() throws IOException {
  String expectedOutputPath = testDataPath("AndroidManifest.expected.xml").toString();
  SourcePath libraryManifestA = testDataPath("AndroidManifestA.xml");
  SourcePath libraryManifestB = testDataPath("AndroidManifestB.xml");
  SourcePath libraryManifestC = testDataPath("AndroidManifestC.xml");
  ImmutableSet.Builder<SourcePath> libraryManifestFiles = ImmutableSet.builder();
  libraryManifestFiles.add(libraryManifestA);
  libraryManifestFiles.add(libraryManifestB);
  libraryManifestFiles.add(libraryManifestC);

  ExecutionContext context = TestExecutionContext.newInstance();

  GenerateManifestStep manifestCommand = new GenerateManifestStep(
      skeletonPath,
      libraryManifestFiles.build(),
      manifestPath);
  int result = manifestCommand.execute(context);

  assertEquals(0, result);

  String expected = Files.toString(new File(expectedOutputPath), Charsets.UTF_8);
  String output = Files.toString(manifestPath.toFile(), Charsets.UTF_8);

  assertEquals(expected, output);
}
项目:buck-cutom    文件:ShTestTest.java   
@Test
public void testHasTestResultFiles() {
  ShTest shTest = new ShTest(
      new FakeBuildRuleParamsBuilder(
          BuildTarget.builder("//test/com/example", "my_sh_test").build())
          .build(),
      new TestSourcePath("run_test.sh"),
      /* labels */ ImmutableSet.<Label>of());

  ProjectFilesystem filesystem = createMock(ProjectFilesystem.class);
  EasyMock.expect(filesystem.isFile(shTest.getPathToTestOutputResult())).andReturn(true);
  ExecutionContext executionContext = createMock(ExecutionContext.class);
  EasyMock.expect(executionContext.getProjectFilesystem()).andReturn(filesystem);

  replayAll();

  assertTrue("hasTestResultFiles() should return true if result.json exists.",
      shTest.hasTestResultFiles(executionContext));
}
项目:buck-cutom    文件:ExternalJavacTest.java   
@Test
public void testJavacCommand() {
  ExecutionContext context = TestExecutionContext.newInstance();

  ExternalJavacStep firstOrder = createTestStep(BuildDependencies.FIRST_ORDER_ONLY);
  ExternalJavacStep warn = createTestStep(BuildDependencies.WARN_ON_TRANSITIVE);
  ExternalJavacStep transitive = createTestStep(BuildDependencies.TRANSITIVE);

  assertEquals("fakeJavac -source 6 -target 6 -g -d . -classpath foo.jar @" + PATH_TO_SRCS_LIST,
      firstOrder.getDescription(context));
  assertEquals("fakeJavac -source 6 -target 6 -g -d . -classpath foo.jar @" + PATH_TO_SRCS_LIST,
      warn.getDescription(context));
  assertEquals("fakeJavac -source 6 -target 6 -g -d . -classpath bar.jar" + File.pathSeparator +
      "foo.jar @" + PATH_TO_SRCS_LIST,
      transitive.getDescription(context));
}
项目:buck-cutom    文件:GenProGuardConfigStep.java   
@Override
protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
  ImmutableList.Builder<String> args = ImmutableList.builder();
  AndroidPlatformTarget androidPlatformTarget = context.getAndroidPlatformTarget();

  args.add(androidPlatformTarget.getAaptExecutable().toString());
  args.add("package");

  // Specify where the ProGuard config should be written.
  args.add("-G").add(proguardConfigurationPath.toString());

  // Add all of the res/ directories.
  for (Path res : resDirectories) {
    args.add("-S").add(res.toString());
  }

  // Add the remaining flags.
  args.add("-M").add(androidManifestPath.toString());
  args.add("--auto-add-overlay");
  args.add("-I").add(androidPlatformTarget.getAndroidJar().toString());

  return args.build();
}
项目:buck-cutom    文件:ApkBuilderStep.java   
private PrivateKeyAndCertificate createKeystoreProperties(ExecutionContext context)
    throws CertificateException,
        IOException,
        KeyStoreException,
        NoSuchAlgorithmException,
        UnrecoverableKeyException {
  ProjectFilesystem projectFilesystem = context.getProjectFilesystem();
  KeystoreProperties keystoreProperties = KeystoreProperties.createFromPropertiesFile(
      pathToKeystore,
      pathToKeystorePropertiesFile,
      projectFilesystem);
  KeyStore keystore = KeyStore.getInstance(JARSIGNER_KEY_STORE_TYPE);
  InputStream inputStream = projectFilesystem.getInputStreamForRelativePath(pathToKeystore);
  char[] keystorePassword = keystoreProperties.getStorepass().toCharArray();
  keystore.load(inputStream, keystorePassword);

  String alias = keystoreProperties.getAlias();
  char[] keyPassword = keystoreProperties.getKeypass().toCharArray();
  Key key = keystore.getKey(alias, keyPassword);
  Certificate certificate = keystore.getCertificate(alias);

  return new PrivateKeyAndCertificate((PrivateKey) key, (X509Certificate) certificate);
}
项目:buck-cutom    文件:SplitZipStep.java   
/**
 * Construct a {@link Set} of internal class names that must go into the primary dex.
 * <p/>
 * @return ImmutableSet of class internal names.
 */
private ImmutableSet<String> getRequiredPrimaryDexClassNames(
    ExecutionContext context,
    ProguardTranslatorFactory translatorFactory,
    Supplier<ImmutableList<ClassNode>> classesSupplier)
    throws IOException {
  ImmutableSet.Builder<String> builder = ImmutableSet.builder();

  Optional<Path> primaryDexClassesFile = dexSplitMode.getPrimaryDexClassesFile()
      .transform(SourcePaths.TO_PATH);
  if (primaryDexClassesFile.isPresent()) {
    Iterable<String> classes = FluentIterable
        .from(context.getProjectFilesystem().readLines(primaryDexClassesFile.get()))
        .transform(STRING_TRIM)
        .filter(IS_NEITHER_EMPTY_NOR_COMMENT);
    builder.addAll(classes);
  }

  // If there is a scenario file but overflow is not allowed, then the scenario dependencies
  // are required, and therefore get added here.
  if (!dexSplitMode.isPrimaryDexScenarioOverflowAllowed() && primaryDexScenarioFile.isPresent()) {
    addScenarioClasses(context, translatorFactory, classesSupplier, builder);
  }

  return ImmutableSet.copyOf(builder.build());
}
项目:buck-cutom    文件:ShellStep.java   
/**
 * This method is idempotent.
 * @return the shell command arguments
 */
public final ImmutableList<String> getShellCommand(ExecutionContext context) {
  if (shellCommandArgs == null) {
    shellCommandArgs = getShellCommandInternal(context);
  }
  return shellCommandArgs;
}
项目:onos    文件:OSGiWrapper.java   
@Override
public StepExecutionResult execute(ExecutionContext executionContext)
        throws IOException, InterruptedException {
    stderr = executionContext.getStdErr();
    boolean success = execute();
    stderr = System.err;
    return success ? StepExecutionResult.SUCCESS : StepExecutionResult.ERROR;
}
项目:buck-cutom    文件:AppleResourceTest.java   
/**
 * Tests an apple_resource rule with a directory resource.
 */
@Test
public void testAppleResourceRuleWithDirectoryResource() throws IOException {
  AppleResourceDescription.Arg args = new AppleResourceDescription.Arg();
  args.dirs = ImmutableSortedSet.of(Paths.get("MyLibrary.bundle"));
  args.files = ImmutableSortedSet.of();
  args.variants = Optional.absent();

  AppleResource appleResource = new AppleResource(
      new FakeBuildRuleParamsBuilder(
          BuildTarget.builder("//path/to/app", "MyApp").build()).build(),
      new FakeDirectoryTraverser(),
      args);

  FakeProjectFilesystem projectFilesystem = new FakeProjectFilesystem();

  List<Step> steps = appleResource.getBuildSteps(
      FakeBuildContext.NOOP_CONTEXT,
      new FakeBuildableContext());

  ExecutionContext executionContext = TestExecutionContext
      .newBuilder()
      .setProjectFilesystem(projectFilesystem)
      .build();

  MoreAsserts.assertSteps("Copy the resources to the expected location",
      ImmutableList.of(
          "cp -R MyLibrary.bundle buck-out/bin/path/to/app/MyApp.app"),
      steps,
      executionContext);
}
项目:buck-cutom    文件:UnzipStep.java   
@Override
public int execute(ExecutionContext context) throws InterruptedException {
  ProjectFilesystem filesystem = context.getProjectFilesystem();
  Path zip = filesystem.getPathForRelativeExistingPath(zipFile).toAbsolutePath();
  Path out = filesystem.getPathForRelativeExistingPath(destinationDirectory).toAbsolutePath();

  try {
    Unzip.extractZipFile(zip, out, true);
  } catch (IOException e) {
    LOG.warn(e, "Unable to unpack zip: %s", zipFile);
    return 1;
  }
  return 0;
}
项目:buck-cutom    文件:UnzipStep.java   
@Override
public String getDescription(ExecutionContext context) {
  ProjectFilesystem projectFilesystem = context.getProjectFilesystem();
  return String.format(
      "unzip %s -d %s",
      MorePaths.pathWithUnixSeparators(projectFilesystem.resolve(zipFile)),
      MorePaths.pathWithUnixSeparators(projectFilesystem.resolve(destinationDirectory)));
}
项目:buck-cutom    文件:ZipalignStep.java   
@Override
protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
  ImmutableList.Builder<String> args = ImmutableList.builder();

  AndroidPlatformTarget androidPlatformTarget = context.getAndroidPlatformTarget();
  args.add(androidPlatformTarget.getZipalignExecutable().toString());
  args.add("-f").add("4");
  args.add(inputFile.toString());
  args.add(outputFile.toString());
  return args.build();
}
项目:buck-cutom    文件:CompilerStep.java   
@Override
protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
  ImmutableList.Builder<String> cmdBuilder = ImmutableList.builder();

  cmdBuilder.add(compiler);

  if (context.isDebugEnabled()) {
    cmdBuilder.add("-g");
  }

  if (!shouldLink) {
    cmdBuilder.add("-c");
  }

  if (shouldAddProjectRootToIncludePaths) {
    cmdBuilder.add("-I");
    cmdBuilder.add(context.getProjectDirectoryRoot().toString());
  }

  for (Path includePath : includePaths) {
    cmdBuilder.add("-I");
    cmdBuilder.add(includePath.toString());
  }

  cmdBuilder.addAll(commandLineArgs);

  for (Path src : srcs) {
    cmdBuilder.add(src.toString());
  }
  cmdBuilder.add("-o").add(outputFile.toString());

  return cmdBuilder.build();
}
项目:buck-cutom    文件:TestCommandTest.java   
@Test
public void testIsTestRunRequiredForTestBuiltFromCacheIfHasTestResultFiles()
    throws IOException, ExecutionException, InterruptedException {
  ExecutionContext executionContext = createMock(ExecutionContext.class);
  expect(executionContext.isDebugEnabled()).andReturn(false);

  FakeTestRule testRule = new FakeTestRule(
      JavaTestDescription.TYPE,
      ImmutableSet.of(new Label("windows")),
      BuildTargetFactory.newInstance("//:lulz"),
      ImmutableSortedSet.<BuildRule>of(),
      ImmutableSet.<BuildTargetPattern>of());

  CachingBuildEngine cachingBuildEngine = createMock(CachingBuildEngine.class);
  expect(cachingBuildEngine.getBuildRuleResult(BuildTargetFactory.newInstance("//:lulz")))
      .andReturn(new BuildRuleSuccess(testRule, BuildRuleSuccess.Type.FETCHED_FROM_CACHE));
  replay(executionContext, cachingBuildEngine);

  assertTrue(
      "A cache hit updates the build artifact but not the test results. " +
          "Therefore, the test should be re-run to ensure the test results are up to date.",
      TestCommand.isTestRunRequiredForTest(
          testRule,
          cachingBuildEngine,
          executionContext,
          createMock(TestRuleKeyFileHelper.class),
          /* results cache enabled */ true,
          /* running with test selectors */ false));

  verify(executionContext, cachingBuildEngine);
}
项目:buck-cutom    文件:AndroidBinaryTest.java   
private void createAndroidBinaryRuleAndTestCopyNativeLibraryCommand(
    ImmutableSet<TargetCpuType> cpuFilters,
    String sourceDir,
    String destinationDir,
    ImmutableList<String> expectedCommandDescriptions) {

  class FakeProjectFilesystem extends ProjectFilesystem {

    public FakeProjectFilesystem() {
      super(new File("."));
    }

    @Override
    public Path resolve(Path path) {
      return path;
    }
  }

  // Invoke copyNativeLibrary to populate the steps.
  ImmutableList.Builder<Step> stepsBuilder = ImmutableList.builder();
  AndroidBinary.copyNativeLibrary(
      Paths.get(sourceDir), Paths.get(destinationDir), cpuFilters, stepsBuilder);
  ImmutableList<Step> steps = stepsBuilder.build();

  assertEquals(steps.size(), expectedCommandDescriptions.size());
  ExecutionContext context = createMock(ExecutionContext.class);
  expect(context.getProjectFilesystem()).andReturn(new FakeProjectFilesystem()).anyTimes();
  replay(context);

  for (int i = 0; i < steps.size(); ++i) {
    String description = steps.get(i).getDescription(context);
    assertEquals(expectedCommandDescriptions.get(i), description);
  }

  verify(context);
}
项目:buck-cutom    文件:FakeTestRule.java   
@Override
public Callable<TestResults> interpretTestResults(
    ExecutionContext executionContext,
    boolean isUsingTestSelectors,
    boolean isDryRun) {
  throw new UnsupportedOperationException("interpretTestResults() not supported in fake");
}
项目:buck-cutom    文件:SymlinkFileStepTest.java   
@Test
public void testReplaceMalformedSymlink() throws IOException, InterruptedException {
  assumeTrue(Platform.detect() != Platform.WINDOWS);

  // Run `ln -s /path/that/does/not/exist dummy` in /tmp.
  ProcessBuilder builder = new ProcessBuilder();
  builder.command("ln", "-s", "/path/that/does/not/exist", "my_symlink");
  File tmp = tmpDir.getRoot();
  builder.directory(tmp);
  Process process = builder.start();
  process.waitFor();

  // Verify that the symlink points to a non-existent file.
  Path symlink = Paths.get(tmp.getAbsolutePath(), "my_symlink");
  assertFalse("exists() should reflect the existence of what the symlink points to",
      symlink.toFile().exists());
  assertTrue("even though exists() is false, isSymbolicLink should be true",
      java.nio.file.Files.isSymbolicLink(symlink));

  // Create an ExecutionContext to return the ProjectFilesystem.
  ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot());
  ExecutionContext executionContext = TestExecutionContext.newBuilder()
      .setProjectFilesystem(projectFilesystem)
      .build();

  tmpDir.newFile("dummy");
  SymlinkFileStep symlinkStep = new SymlinkFileStep(
      /* source */ Paths.get("dummy"),
      /* target */ Paths.get("my_symlink"),
      /* useAbsolutePaths*/ true);
  int exitCode = symlinkStep.execute(executionContext);
  assertEquals(0, exitCode);
  assertTrue(java.nio.file.Files.isSymbolicLink(symlink));
  assertTrue(symlink.toFile().exists());
}
项目:buck-cutom    文件:DxStepTest.java   
@Test
public void testUseCustomDxOption() {
  // Context with --verbose 2.
  ExecutionContext context = createExecutionContext(2);
  Function<Path, Path> pathAbsolutifier = context.getProjectFilesystem().getAbsolutifier();

  DxStep dx = new DxStep(SAMPLE_OUTPUT_PATH,
      SAMPLE_FILES_TO_DEX,
      EnumSet.of(Option.USE_CUSTOM_DX_IF_AVAILABLE),
      new Supplier<String>() {
        @Override
        public String get() {
          return "/home/mbolin/dx";
        }
      });

  String expected = String.format("%s --output %s %s",
      EXPECTED_DX_PREFIX.replace("/usr/bin/dx", "/home/mbolin/dx"),
      SAMPLE_OUTPUT_PATH,
      Joiner.on(' ').join(Iterables.transform(SAMPLE_FILES_TO_DEX, pathAbsolutifier)));
  MoreAsserts.assertShellCommands(
      "/home/mbolin/dx should be used instead of /usr/bin/dx.",
      ImmutableList.of(expected),
      ImmutableList.<Step>of(dx),
      context);
  verifyAll();
}
项目:buck-cutom    文件:ExternalJavacStep.java   
@Override
public String getDescription(ExecutionContext context) {
  StringBuilder builder = new StringBuilder(pathToJavac.toString());
  builder.append(" ");
  Joiner.on(" ").appendTo(builder, getOptions(context, getClasspathEntries()));
  builder.append(" ");

  if (pathToSrcsList.isPresent()) {
    builder.append("@").append(pathToSrcsList.get());
  } else {
    Joiner.on(" ").appendTo(builder, javaSourceFilePaths);
  }

  return builder.toString();
}
项目:buck-cutom    文件:JavacInMemoryStepIntegrationTest.java   
@Test
public void testClassesFile() throws IOException, InterruptedException {
  JavacInMemoryStep javac = createJavac(/* withSyntaxError */ false);
  ExecutionContext executionContext = createExecutionContext();
  int exitCode = javac.execute(executionContext);
  assertEquals("javac should exit with code 0.", exitCode, 0);

  File srcsListFile = pathToSrcsList.toFile();
  assertTrue(srcsListFile.exists());
  assertTrue(srcsListFile.isFile());
  assertEquals("Example.java", Files.toString(srcsListFile, Charsets.UTF_8).trim());
}