@Before
 public void setUp() {
   assumeTrue(Platform.detect() == Platform.MACOS || Platform.detect() == Platform.LINUX);
   generatedProject = new PBXProject("TestProject");
   sourcePathResolver =
       new SourcePathResolver(
           new BuildRuleResolver(
               TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()));
   pathRelativizer =
       new PathRelativizer(Paths.get("_output"), sourcePathResolver.deprecatedPathFunction());
 }
Exemplo n.º 2
0
  @Test
  public void testAppleLibraryBuildsFramework() throws Exception {
    assumeTrue(Platform.detect() == Platform.MACOS);
    assumeTrue(
        AppleNativeIntegrationTestUtils.isApplePlatformAvailable(
            ApplePlatform.builder().setName(ApplePlatform.Name.MACOSX).build()));

    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "apple_library_builds_something", tmp);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand(
            "build", "//Libraries/TestLibrary:TestLibrary#framework,macosx-x86_64");
    result.assertSuccess();

    Path frameworkPath =
        tmp.getRootPath()
            .resolve(BuckConstant.GEN_DIR)
            .resolve(
                "Libraries/TestLibrary/TestLibrary#framework,macosx-x86_64/TestLibrary.framework");
    assertThat(Files.exists(frameworkPath), is(true));
    assertThat(Files.exists(frameworkPath.resolve("Contents/Info.plist")), is(true));
    Path libraryPath = frameworkPath.resolve("Contents/MacOS/TestLibrary");
    assertThat(Files.exists(libraryPath), is(true));
    assertThat(
        workspace.runCommand("file", libraryPath.toString()).getStdout().get(),
        containsString("dynamically linked shared library"));
  }
Exemplo n.º 3
0
  @Test
  public void linkerFlags() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(this, "linker_flags", tmp);
    workspace.setUp();

    workspace.runBuckBuild("//:binary_with_linker_flag").assertFailure("--bad-flag");
    workspace.runBuckBuild("//:binary_with_library_dep").assertSuccess();
    workspace.runBuckBuild("//:binary_with_exported_flags_library_dep").assertFailure("--bad-flag");
    workspace.runBuckBuild("//:binary_with_prebuilt_library_dep").assertFailure("--bad-flag");

    // Build binary that has unresolved symbols.  Normally this would fail, but should work
    // with the proper linker flag.
    switch (Platform.detect()) {
      case MACOS:
        workspace.runBuckBuild("//:binary_with_unresolved_symbols_macos").assertSuccess();
        break;
      case LINUX:
        workspace.runBuckBuild("//:binary_with_unresolved_symbols_linux").assertSuccess();
        break;
        // $CASES-OMITTED$
      default:
        break;
    }
  }
Exemplo n.º 4
0
  @Test
  public void testAppleLibraryExportedHeaderSymlinkTree() throws IOException {
    assumeTrue(Platform.detect() == Platform.MACOS);

    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "apple_library_header_symlink_tree", tmp);
    workspace.setUp();
    ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath());

    BuildTarget buildTarget =
        BuildTargetFactory.newInstance(
            "//Libraries/TestLibrary:TestLibrary#"
                + "default,"
                + CxxDescriptionEnhancer.EXPORTED_HEADER_SYMLINK_TREE_FLAVOR);
    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand("build", buildTarget.getFullyQualifiedName());
    result.assertSuccess();

    Path inputPath = workspace.getPath(buildTarget.getBasePath()).toRealPath();
    Path outputPath =
        workspace.getPath(BuildTargets.getGenPath(filesystem, buildTarget, "%s")).toRealPath();

    assertIsSymbolicLink(
        outputPath.resolve("TestLibrary/PublicHeader.h"), inputPath.resolve("PublicHeader.h"));
  }
Exemplo n.º 5
0
  @Test
  public void testAppleLibraryBuildsFramework() throws Exception {
    assumeTrue(Platform.detect() == Platform.MACOS);
    assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX));

    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "apple_library_builds_something", tmp);
    workspace.setUp();
    ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath());

    BuildTarget target =
        BuildTargetFactory.newInstance(
            "//Libraries/TestLibrary:TestLibrary#framework,macosx-x86_64,no-debug");
    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand("build", target.getFullyQualifiedName());
    result.assertSuccess();

    Path frameworkPath =
        workspace.getPath(
            BuildTargets.getGenPath(
                    filesystem,
                    BuildTarget.builder(target)
                        .addFlavors(AppleDescriptions.INCLUDE_FRAMEWORKS_FLAVOR)
                        .build(),
                    "%s")
                .resolve("TestLibrary.framework"));
    assertThat(Files.exists(frameworkPath), is(true));
    assertThat(Files.exists(frameworkPath.resolve("Resources/Info.plist")), is(true));
    Path libraryPath = frameworkPath.resolve("TestLibrary");
    assertThat(Files.exists(libraryPath), is(true));
    assertThat(
        workspace.runCommand("file", libraryPath.toString()).getStdout().get(),
        containsString("dynamically linked shared library"));
  }
Exemplo n.º 6
0
  @Test
  public void testAppleDynamicLibraryWithDsym() throws Exception {
    assumeTrue(Platform.detect() == Platform.MACOS);
    assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX));

    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(this, "apple_library_shared", tmp);
    workspace.setUp();
    ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath());

    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand(
            "build",
            "//Libraries/TestLibrary:TestLibrary#shared,macosx-x86_64,dwarf-and-dsym",
            "--config",
            "cxx.cflags=-g");
    result.assertSuccess();

    Path output =
        tmp.getRoot()
            .resolve(filesystem.getBuckPaths().getGenDir())
            .resolve("Libraries/TestLibrary/TestLibrary#macosx-x86_64,shared")
            .resolve("libLibraries_TestLibrary_TestLibrary.dylib");
    assertThat(Files.exists(output), is(true));

    Path dsymPath =
        tmp.getRoot()
            .resolve(filesystem.getBuckPaths().getGenDir())
            .resolve("Libraries/TestLibrary")
            .resolve("TestLibrary#apple-dsym,macosx-x86_64,shared.dSYM");
    assertThat(Files.exists(dsymPath), is(true));
    AppleDsymTestUtil.checkDsymFileHasDebugSymbol("+[TestClass answer]", workspace, dsymPath);
  }
Exemplo n.º 7
0
  @Test
  public void testShouldIncludeDxInEnvironmentIfPresent() {
    File fakeDx = new File("."); // We do no checks on whether dx is executable, but it must exist
    AndroidPlatformTarget android = EasyMock.createNiceMock(AndroidPlatformTarget.class);
    EasyMock.expect(android.getDxExecutable()).andStubReturn(fakeDx);
    EasyMock.replay(android);

    Genrule rule =
        Genrule.newGenruleBuilder(new FakeAbstractBuildRuleBuilderParams())
            .setBuildTarget(BuildTargetFactory.newInstance("//example:genrule"))
            .setBash(Optional.of("true"))
            .setOut("/dev/null")
            .build(new BuildRuleResolver());

    ExecutionContext context =
        ExecutionContext.builder()
            .setConsole(new TestConsole())
            .setProjectFilesystem(new ProjectFilesystem(new File(".")))
            .setAndroidPlatformTarget(Optional.of(android))
            .setEventBus(BuckEventBusFactory.newInstance())
            .setPlatform(Platform.detect())
            .build();

    ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
    rule.addEnvironmentVariables(context, builder);
    ImmutableMap<String, String> env = builder.build();

    assertEquals(fakeDx.getAbsolutePath(), env.get("DX"));

    EasyMock.verify(android);
  }
 @Test
 public void catMoreTextThanFitsInSingleBufferReceivedOnStdout() throws Exception {
   ProcessExecutorParams params;
   if (Platform.detect() == Platform.WINDOWS) {
     params =
         ProcessExecutorParams.ofCommand(
             "python", "-c", "import sys, shutil; shutil.copyfileobj(sys.stdin, sys.stdout)");
   } else {
     params = ProcessExecutorParams.ofCommand("cat");
   }
   ListeningProcessExecutor executor = new ListeningProcessExecutor();
   StringBuilder sb = new StringBuilder();
   // Use a 3 byte Unicode sequence to ensure writes go across byte buffer
   // boundaries, and append it as many times as needed to ensure it doesn't
   // fit in a single I/O buffer.
   String threeByteUTF8 = "\u2764";
   for (int i = 0; i < ListeningProcessExecutor.LaunchedProcess.BUFFER_CAPACITY + 1; i++) {
     sb.append(threeByteUTF8);
   }
   sb.append(String.format("%n"));
   String longString = sb.toString();
   StdinWritingListener listener = new StdinWritingListener(longString);
   ListeningProcessExecutor.LaunchedProcess process = executor.launchProcess(params, listener);
   process.wantWrite();
   int returnCode = executor.waitForProcess(process);
   assertThat(returnCode, equalTo(0));
   assertThat(listener.capturedStdout.toString("UTF-8"), equalTo(longString));
   assertThat(listener.capturedStderr.toString("UTF-8"), is(emptyString()));
 }
Exemplo n.º 9
0
  @Before
  public void setUp() throws IOException, InterruptedException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(this, "query_command", tmp);
    workspace.setUp();
    Cell cell =
        new TestCellBuilder().setFilesystem(new ProjectFilesystem(workspace.getDestPath())).build();

    TestConsole console = new TestConsole();
    CommandRunnerParams params =
        CommandRunnerParamsForTesting.createCommandRunnerParamsForTesting(
            console,
            cell,
            new FakeAndroidDirectoryResolver(),
            new NoopArtifactCache(),
            BuckEventBusFactory.newInstance(),
            FakeBuckConfig.builder().build(),
            Platform.detect(),
            ImmutableMap.copyOf(System.getenv()),
            new FakeJavaPackageFinder(),
            new ObjectMapper(),
            Optional.<WebServer>absent());

    buckQueryEnvironment = new BuckQueryEnvironment(params, /* enableProfiling */ false);
    cellRoot = workspace.getDestPath();
    executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
  }
Exemplo n.º 10
0
  @Test
  public void frameworkDependenciesDoNotContainTransitiveDependencies() throws Exception {
    assumeTrue(Platform.detect() == Platform.MACOS);
    assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX));

    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "apple_library_with_library_dependencies", tmp);
    workspace.setUp();
    ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath());

    BuildTarget target =
        BuildTargetFactory.newInstance(
            "//Libraries/TestLibrary:TestLibrary#framework,macosx-x86_64");
    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand("build", target.getFullyQualifiedName());
    result.assertSuccess();

    Path frameworkPath =
        workspace.getPath(
            BuildTargets.getGenPath(
                    filesystem,
                    BuildTarget.builder(target)
                        .addFlavors(AppleDebugFormat.DWARF.getFlavor())
                        .addFlavors(AppleDescriptions.INCLUDE_FRAMEWORKS_FLAVOR)
                        .build(),
                    "%s")
                .resolve("TestLibrary.framework"));
    assertThat(Files.exists(frameworkPath), is(true));
    Path frameworksPath = frameworkPath.resolve("Frameworks");
    assertThat(Files.exists(frameworksPath), is(true));
    Path depFrameworksPath = frameworksPath.resolve("TestLibraryDep.framework/Frameworks");
    assertThat(Files.exists(depFrameworksPath), is(false));
  }
Exemplo n.º 11
0
  @Test
  public void noIncludeFrameworksDoesntContainFrameworkDependencies() throws Exception {
    assumeTrue(Platform.detect() == Platform.MACOS);
    assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX));

    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "apple_library_with_library_dependencies", tmp);
    workspace.setUp();
    ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath());

    BuildTarget target =
        BuildTargetFactory.newInstance(
            "//Libraries/TestLibrary:TestLibrary#"
                + "dwarf-and-dsym,framework,macosx-x86_64,no-include-frameworks");
    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand("build", target.getFullyQualifiedName());
    result.assertSuccess();

    Path frameworkPath =
        workspace.getPath(
            BuildTargets.getGenPath(filesystem, target, "%s").resolve("TestLibrary.framework"));
    assertThat(Files.exists(frameworkPath), is(true));
    assertThat(Files.exists(frameworkPath.resolve("Resources/Info.plist")), is(true));
    Path libraryPath = frameworkPath.resolve("TestLibrary");
    assertThat(Files.exists(libraryPath), is(true));
    assertThat(
        workspace.runCommand("file", libraryPath.toString()).getStdout().get(),
        containsString("dynamically linked shared library"));
    Path frameworksPath = frameworkPath.resolve("Contents/Frameworks");
    assertThat(Files.exists(frameworksPath), is(false));
  }
Exemplo n.º 12
0
  @Before
  public void setUp() throws IOException, InterruptedException {
    console = new TestConsole();
    workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "target_command", tmp);
    workspace.setUp();

    filesystem = new ProjectFilesystem(workspace.getDestPath().toRealPath().normalize());
    Cell cell = new TestCellBuilder().setFilesystem(filesystem).build();
    AndroidDirectoryResolver androidDirectoryResolver = new FakeAndroidDirectoryResolver();
    ArtifactCache artifactCache = new NoopArtifactCache();
    BuckEventBus eventBus = BuckEventBusFactory.newInstance();
    objectMapper = new ObjectMapper();

    targetsCommand = new TargetsCommand();
    params =
        CommandRunnerParamsForTesting.createCommandRunnerParamsForTesting(
            console,
            cell,
            androidDirectoryResolver,
            artifactCache,
            eventBus,
            FakeBuckConfig.builder().build(),
            Platform.detect(),
            ImmutableMap.copyOf(System.getenv()),
            new FakeJavaPackageFinder(),
            objectMapper,
            Optional.<WebServer>absent());
    executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
  }
Exemplo n.º 13
0
 private String getFileContentsWithAbsolutePath(Path path) throws IOException {
   String platformExt = null;
   switch (Platform.detect()) {
     case LINUX:
       platformExt = "linux";
       break;
     case MACOS:
       platformExt = "macos";
       break;
     case WINDOWS:
       platformExt = "win";
       break;
     case FREEBSD:
       platformExt = "freebsd";
       break;
     case UNKNOWN:
       // Leave platformExt as null.
       break;
   }
   if (platformExt != null) {
     String extension = com.google.common.io.Files.getFileExtension(path.toString());
     String basename = com.google.common.io.Files.getNameWithoutExtension(path.toString());
     Path platformPath =
         extension.length() > 0
             ? path.getParent()
                 .resolve(String.format("%s.%s.%s", basename, platformExt, extension))
             : path.getParent().resolve(String.format("%s.%s", basename, platformExt));
     if (platformPath.toFile().exists()) {
       path = platformPath;
     }
   }
   return new String(Files.readAllBytes(path), UTF_8);
 }
Exemplo n.º 14
0
  @Test
  public void testIgnorePaths() throws IOException {
    ProjectFilesystem filesystem = EasyMock.createMock(ProjectFilesystem.class);
    EasyMock.expect(filesystem.getPathRelativizer())
        .andReturn(Functions.<String>identity())
        .times(2);
    BuildTargetParser parser = EasyMock.createMock(BuildTargetParser.class);
    EasyMock.replay(filesystem, parser);

    Reader reader =
        new StringReader(
            Joiner.on('\n').join("[project]", "ignore = .git, foo, bar/, baz//, a/b/c"));
    BuckConfig config = BuckConfig.createFromReader(reader, filesystem, parser, Platform.detect());

    ImmutableSet<String> ignorePaths = config.getIgnorePaths();
    assertEquals(
        "Should ignore paths, sans trailing slashes",
        ignorePaths,
        ImmutableSet.of(
            BuckConstant.BUCK_OUTPUT_DIRECTORY,
            ".idea",
            System.getProperty(BuckConfig.BUCK_BUCKD_DIR_KEY, ".buckd"),
            config.getCacheDir(),
            ".git",
            "foo",
            "bar",
            "baz",
            "a/b/c"));

    EasyMock.verify(filesystem, parser);
  }
Exemplo n.º 15
0
  @Test
  public void testInferCxxBinaryDepsCaching() throws IOException {
    assumeTrue(Platform.detect() != Platform.WINDOWS);
    ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace(this, tmp);
    workspace.enableDirCache(); // enable the cache

    CxxPlatform cxxPlatform = DefaultCxxPlatforms.build(new CxxBuckConfig(new FakeBuckConfig()));
    BuildTarget inputBuildTarget = BuildTargetFactory.newInstance("//foo:binary_with_deps");
    String inputBuildTargetName =
        inputBuildTarget.withFlavors(CxxInferEnhancer.INFER).getFullyQualifiedName();

    /*
     * Build the given target and check that it succeeds.
     */
    workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();

    /*
     * Check that building after clean will use the cache
     */
    workspace.runBuckCommand("clean").assertSuccess();
    workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
    BuckBuildLog buildLog = workspace.getBuildLog();
    for (BuildTarget buildTarget : buildLog.getAllTargets()) {
      buildLog.assertTargetWasFetchedFromCache(buildTarget.toString());
    }

    /*
     * Check that if the file in the binary target changes, then all the deps will be fetched
     * from the cache
     */
    String sourceName = "src_with_deps.c";
    workspace.replaceFileContents("foo/" + sourceName, "10", "30");
    workspace.runBuckCommand("clean").assertSuccess();
    workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess();
    buildLog = workspace.getBuildLog();

    CxxSourceRuleFactory cxxSourceRuleFactory =
        CxxSourceRuleFactoryHelper.of(inputBuildTarget, cxxPlatform);

    BuildTarget captureBuildTarget = cxxSourceRuleFactory.createInferCaptureBuildTarget(sourceName);

    // this is flavored, and denotes the analysis step (generates a local report)
    BuildTarget inferAnalysisTarget = inputBuildTarget.withFlavors(CxxInferEnhancer.INFER_ANALYZE);

    // this is the flavored version of the top level target (the one give in input to buck)
    BuildTarget inferReportTarget = inputBuildTarget.withFlavors(CxxInferEnhancer.INFER);

    String bt;
    for (BuildTarget buildTarget : buildLog.getAllTargets()) {
      bt = buildTarget.toString();
      if (bt.equals(inferAnalysisTarget.toString())
          || bt.equals(captureBuildTarget.toString())
          || bt.equals(inferReportTarget.toString())) {
        buildLog.assertTargetBuiltLocally(bt);
      } else {
        buildLog.assertTargetWasFetchedFromCache(buildTarget.toString());
      }
    }
  }
Exemplo n.º 16
0
 private BuckConfig createWithDefaultFilesystem(Reader reader, @Nullable BuildTargetParser parser)
     throws IOException {
   ProjectFilesystem projectFilesystem = new ProjectFilesystem(new File("."));
   if (parser == null) {
     parser = new BuildTargetParser(projectFilesystem);
   }
   return BuckConfig.createFromReader(reader, projectFilesystem, parser, Platform.detect());
 }
Exemplo n.º 17
0
 @Test
 public void genruleUsingBinaryUsingSharedLinkStyle() throws IOException {
   assumeThat(Platform.detect(), oneOf(Platform.LINUX, Platform.MACOS));
   ProjectWorkspace workspace =
       TestDataHelper.createProjectWorkspaceForScenario(this, "shared_link_style", tmp);
   workspace.setUp();
   workspace.runBuckBuild("//:gen").assertSuccess();
 }
Exemplo n.º 18
0
 public static ExecutionContext.Builder newBuilder() {
   return ExecutionContext.builder()
       .setConsole(new TestConsole())
       .setProjectFilesystem(new ProjectFilesystem(new File(".")))
       .setEventBus(BuckEventBusFactory.newInstance())
       .setPlatform(Platform.detect())
       .setEnvironment(ImmutableMap.copyOf(System.getenv()));
 }
Exemplo n.º 19
0
 @Test
 public void buildBinaryWithPerFileFlags() throws IOException {
   assumeThat(Platform.detect(), is(Platform.MACOS));
   ProjectWorkspace workspace =
       TestDataHelper.createProjectWorkspaceForScenario(this, "per_file_flags", tmp);
   workspace.setUp();
   ProjectWorkspace.ProcessResult result = workspace.runBuckBuild("//:binary");
   result.assertSuccess();
 }
Exemplo n.º 20
0
 BuckConfig createBuckConfig(String contents) throws IOException, NoSuchBuildTargetException {
   ProjectFilesystem dummyProjectFilesystem = EasyMock.createMock(ProjectFilesystem.class);
   EasyMock.replay(dummyProjectFilesystem);
   return BuckConfig.createFromReader(
       new StringReader(contents),
       dummyProjectFilesystem,
       new BuildTargetParser(dummyProjectFilesystem),
       Platform.detect());
 }
Exemplo n.º 21
0
 public ProcessResult runBuckdCommand(
     NGContext context, CapturingPrintStream stderr, String... args) throws IOException {
   assumeTrue(
       "watchman must exist to run buckd",
       new ExecutableFinder(Platform.detect())
           .getOptionalExecutable(Paths.get("watchman"), ImmutableMap.copyOf(System.getenv()))
           .isPresent());
   return runBuckCommandWithEnvironmentOverridesAndContext(
       destPath, Optional.of(context), ImmutableMap.of(), stderr, args);
 }
Exemplo n.º 22
0
 ProjectCommandForTest() {
   super(
       new CommandRunnerParams(
           new TestConsole(),
           new ProjectFilesystem(new File(".")),
           new KnownBuildRuleTypes(),
           new InstanceArtifactCacheFactory(artifactCache),
           BuckEventBusFactory.newInstance(),
           BuckTestConstant.PYTHON_INTERPRETER,
           Platform.detect()));
 }
Exemplo n.º 23
0
 public ProcessResult runBuckdCommand(NGContext context, String... args) throws IOException {
   assumeTrue(
       "watchman must exist to run buckd",
       new ExecutableFinder(Platform.detect())
           .getOptionalExecutable(Paths.get("watchman"), ImmutableMap.copyOf(System.getenv()))
           .isPresent());
   return runBuckCommandWithEnvironmentAndContext(
       destPath,
       Optional.of(context),
       Optional.<BuckEventListener>absent(),
       Optional.<ImmutableMap<String, String>>absent(),
       args);
 }
Exemplo n.º 24
0
  @Test
  public void testAppleLibraryBuildsSomething() throws IOException {
    assumeTrue(Platform.detect() == Platform.MACOS);
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(
            this, "apple_library_builds_something", tmp);
    workspace.setUp();

    ProjectWorkspace.ProcessResult result =
        workspace.runBuckCommand("build", "//Libraries/TestLibrary:TestLibrary#static,default");
    result.assertSuccess();

    assertTrue(Files.exists(tmp.getRootPath().resolve(BuckConstant.GEN_DIR)));
  }
Exemplo n.º 25
0
 @Test
 public void buildBinaryUsingStaticPicLinkStyle() throws IOException {
   assumeThat(Platform.detect(), oneOf(Platform.LINUX, Platform.MACOS));
   ProjectWorkspace workspace =
       TestDataHelper.createProjectWorkspaceForScenario(this, "static_pic_link_style", tmp);
   workspace.setUp();
   workspace
       .runBuckCommand(
           "build",
           // This should only work (on some architectures) if PIC was used to build all included
           // object files.
           "--config",
           "cxx.cxxldflags=-shared",
           "//:bar")
       .assertSuccess();
 }
Exemplo n.º 26
0
  @Test
  public void testIgnorePathsWithAbsoluteCacheDir() throws IOException {

    ProjectFilesystem filesystem = EasyMock.createMock(ProjectFilesystem.class);
    BuildTargetParser parser = EasyMock.createMock(BuildTargetParser.class);
    EasyMock.replay(filesystem, parser);
    Reader reader = new StringReader(Joiner.on('\n').join("[cache]", "dir = /cache_dir"));
    BuckConfig config = BuckConfig.createFromReader(reader, filesystem, parser, Platform.detect());

    ImmutableSet<String> ignorePaths = config.getIgnorePaths();
    assertFalse(
        "Absolute cache directory should not be in set of ignored paths",
        ignorePaths.contains("/cache_dir"));

    EasyMock.verify(filesystem, parser);
  }
 @Test
 public void echoTextReceivedOnStdout() throws Exception {
   ListeningProcessExecutor executor = new ListeningProcessExecutor();
   CapturingListener listener = new CapturingListener();
   ProcessExecutorParams params;
   if (Platform.detect() == Platform.WINDOWS) {
     params = ProcessExecutorParams.ofCommand("cmd.exe", "/c", "echo", "Hello");
   } else {
     params = ProcessExecutorParams.ofCommand("echo", "Hello");
   }
   ListeningProcessExecutor.LaunchedProcess process = executor.launchProcess(params, listener);
   int returnCode = executor.waitForProcess(process);
   assertThat(returnCode, equalTo(0));
   assertThat(listener.capturedStdout.toString("UTF-8"), equalTo(String.format("Hello%n")));
   assertThat(listener.capturedStderr.toString("UTF-8"), is(emptyString()));
 }
 @Test
 public void processFailureExitCodeNotZero() throws Exception {
   ProcessExecutorParams params;
   if (Platform.detect() == Platform.WINDOWS) {
     params = ProcessExecutorParams.ofCommand("cmd.exe", "/c", "exit", "1");
   } else {
     params = ProcessExecutorParams.ofCommand("false");
   }
   ListeningProcessExecutor executor = new ListeningProcessExecutor();
   CapturingListener listener = new CapturingListener();
   ListeningProcessExecutor.LaunchedProcess process = executor.launchProcess(params, listener);
   int returnCode = executor.waitForProcess(process);
   assertThat(returnCode, not(equalTo(0)));
   assertThat(listener.capturedStdout.toString("UTF-8"), is(emptyString()));
   assertThat(listener.capturedStderr.toString("UTF-8"), is(emptyString()));
 }
  @Test
  public void shouldFindNeededDependenciesFromSymbols() throws IOException, InterruptedException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(this, "symbol_finder", temporaryFolder);
    workspace.setUp();

    ProjectFilesystem projectFilesystem = new ProjectFilesystem(temporaryFolder.getRootPath());
    ImmutableMap<String, String> environment = ImmutableMap.copyOf(System.getenv());

    Config rawConfig =
        Config.createDefaultConfig(
            projectFilesystem.getRootPath(),
            ImmutableMap.<String, ImmutableMap<String, String>>of());
    BuckConfig config =
        new BuckConfig(
            rawConfig, projectFilesystem, Architecture.detect(), Platform.detect(), environment);
    ImmutableSet<Description<?>> allDescriptions =
        DefaultKnownBuildRuleTypes.getDefaultKnownBuildRuleTypes(projectFilesystem)
            .getAllDescriptions();
    BuckEventBus buckEventBus = BuckEventBusFactory.newInstance();

    MissingSymbolsHandler missingSymbolsHandler =
        MissingSymbolsHandler.create(
            projectFilesystem,
            allDescriptions,
            config,
            buckEventBus,
            new TestConsole(),
            DEFAULT_JAVAC_OPTIONS,
            environment);

    MissingSymbolEvent missingSymbolEvent =
        MissingSymbolEvent.create(
            BuildTargetFactory.newInstance(workspace.getDestPath(), "//java/com/example/b:b"),
            "com.example.a.A",
            MissingSymbolEvent.SymbolType.Java);

    ImmutableSetMultimap<BuildTarget, BuildTarget> neededDeps =
        missingSymbolsHandler.getNeededDependencies(ImmutableList.of(missingSymbolEvent));

    assertEquals(
        "MissingSymbolsHandler failed to find the needed dependency.",
        neededDeps,
        ImmutableSetMultimap.of(
            BuildTargetFactory.newInstance(workspace.getDestPath(), "//java/com/example/b:b"),
            BuildTargetFactory.newInstance(workspace.getDestPath(), "//java/com/example/a:a")));
  }
Exemplo n.º 30
0
  /**
   * This will copy the template directory, renaming files named {@code BUCK.test} to {@code BUCK}
   * in the process. Files whose names end in {@code .expected} will not be copied.
   */
  public void setUp() throws IOException {
    DefaultKnownBuildRuleTypes.resetInstance();

    MoreFiles.copyRecursively(templatePath, destPath, BUILD_FILE_RENAME);

    // If there's a local.properties in the host project but not in the destination, make a copy.
    Path localProperties = FileSystems.getDefault().getPath("local.properties");
    Path destLocalProperties = destPath.resolve(localProperties.getFileName());

    if (localProperties.toFile().exists() && !destLocalProperties.toFile().exists()) {
      java.nio.file.Files.copy(localProperties, destLocalProperties);
    }

    if (Platform.detect() == Platform.WINDOWS) {
      // Hack for symlinks on Windows.
      SimpleFileVisitor<Path> copyDirVisitor =
          new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs)
                throws IOException {
              // On Windows, symbolic links from git repository are checked out as normal files
              // containing a one-line path. In order to distinguish them, paths are read and
              // pointed
              // files are trued to locate. Once the pointed file is found, it will be copied to
              // target.
              // On NTFS length of path must be greater than 0 and less than 4096.
              if (attrs.size() > 0 && attrs.size() <= 4096) {
                File file = path.toFile();
                String linkTo = Files.toString(file, Charsets.UTF_8);
                File linkToFile = new File(templatePath.toFile(), linkTo);
                if (linkToFile.isFile()) {
                  java.nio.file.Files.copy(
                      linkToFile.toPath(), path, StandardCopyOption.REPLACE_EXISTING);
                } else if (linkToFile.isDirectory()) {
                  if (!file.delete()) {
                    throw new IOException();
                  }
                  MoreFiles.copyRecursively(linkToFile.toPath(), path);
                }
              }
              return FileVisitResult.CONTINUE;
            }
          };
      java.nio.file.Files.walkFileTree(destPath, copyDirVisitor);
    }
    isSetUp = true;
  }