Java Code Examples for java.nio.file.Files#writeString()

The following examples show how to use java.nio.file.Files#writeString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Creator.java    From jmbe with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates JAR metadata directory and manifest file
 *
 * @param outputDirectory for writing files
 * @param version string for the library
 * @throws IOException if there is an error
 */
public static void createJarMetadata(Path outputDirectory, String version) throws IOException
{
    Path metaDirectory = outputDirectory.resolve("META-INF");
    if(!Files.exists(metaDirectory))
    {
        Files.createDirectory(metaDirectory);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Manifest-Version: 1.0\r\n");
    sb.append("Implementation-Title: jmbe\r\n");
    sb.append("Version: ").append(version).append("\r\n");
    sb.append("Site: https://github.com/DSheirer/jmbe\r\n");

    Path manifest = metaDirectory.resolve("MANIFEST.MF");
    Files.writeString(manifest, sb.toString(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
}
 
Example 2
Source File: FileTask.java    From helidon-build-tools with Apache License 2.0 6 votes vote down vote up
@Override
protected void doExecute(StagingContext context, Path dir, Map<String, String> variables) throws IOException {
    String resolvedTarget = resolveVar(target(), variables);
    String resolvedSource = resolveVar(source, variables);
    String resolvedContent = resolveVar(content, variables);
    Path targetFile = dir.resolve(resolvedTarget);
    if (resolvedSource != null && !resolvedSource.isEmpty()) {
        Path sourceFile = context.resolve(resolvedSource);
        if (!Files.exists(sourceFile)) {
            throw new IllegalStateException(sourceFile + " does not exist");
        }
        context.logInfo("Copying %s to %s", sourceFile, targetFile);
        Files.copy(sourceFile, targetFile);
    } else {
        Files.createFile(targetFile);
        if (resolvedContent != null && !resolvedContent.isEmpty()) {
            Files.writeString(targetFile, resolvedContent);
        }
    }
}
 
Example 3
Source File: MockUserManagementServiceTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAccountIncludesPasswordPolicy() throws IOException {
    Path licenseFilePath = Files.createTempFile("license", "txt");
    Files.writeString(licenseFilePath, VALID_LICENSE);
    ReflectionTestUtils.setField(underTest, "cmLicenseFilePath", licenseFilePath.toString());

    try {
        underTest.init();

        GetAccountRequest req = GetAccountRequest.getDefaultInstance();
        StreamRecorder<GetAccountResponse> observer = StreamRecorder.create();

        underTest.getAccount(req, observer);

        assertThat(observer.getValues().size()).isEqualTo(1);
        GetAccountResponse res = observer.getValues().get(0);
        assertThat(res.hasAccount()).isTrue();
        Account account = res.getAccount();
        assertThat(account.hasPasswordPolicy()).isTrue();
        WorkloadPasswordPolicy passwordPolicy = account.getPasswordPolicy();
        assertThat(passwordPolicy.getWorkloadPasswordMaxLifetime()).isEqualTo(MockUserManagementService.PASSWORD_LIFETIME);
    } finally {
        Files.delete(licenseFilePath);
    }
}
 
Example 4
Source File: ConfiguratorTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
private Optional<TransportSecurityOptions> createTransportSecurityOptions() throws IOException {
    KeyPair keyPair = KeyUtils.generateKeypair(EC);
    Path privateKeyFile = folder.newFile().toPath();
    Files.writeString(privateKeyFile, KeyUtils.toPem(keyPair.getPrivate()));

    X509Certificate certificate = X509CertificateBuilder
            .fromKeypair(keyPair, new X500Principal("CN=dummy"), EPOCH, EPOCH.plus(1, DAYS), SHA256_WITH_ECDSA, BigInteger.ONE)
            .build();
    Path certificateChainFile = folder.newFile().toPath();
    String certificatePem = X509CertificateUtils.toPem(certificate);
    Files.writeString(certificateChainFile, certificatePem);

    Path caCertificatesFile = folder.newFile().toPath();
    Files.writeString(caCertificatesFile, certificatePem);

    return Optional.of(new TransportSecurityOptions.Builder()
                               .withCertificates(certificateChainFile, privateKeyFile)
                               .withCaCertificates(caCertificatesFile)
                               .build());
}
 
Example 5
Source File: MinificationTest.java    From mangooio with Apache License 2.0 6 votes vote down vote up
@Test
public void testMinifyCSS() throws IOException {
    //given
    String uuid = UUID.randomUUID().toString();
    StringBuilder buffer = new StringBuilder();
    buffer.append("p {");
    buffer.append("    font: normal 14px/20px helvetica, arial, sans-serif;");
    buffer.append("    color: #333;");
    buffer.append("}");
    buffer.append(".woot {");
    buffer.append("    font-weight: bold;");
    buffer.append("}");
    
    //when
    Path inputFile = Files.createFile(Paths.get(TEMP + uuid + ".css"));
    Files.writeString(inputFile, buffer.toString(), StandardOpenOption.TRUNCATE_EXISTING);
    Minification.minify(inputFile.toAbsolutePath().toString());
    Path outputFile = Paths.get(TEMP + ASSET_PATH + Default.STYLESHEET_FOLDER.toString() + "/" + uuid + ".min.css");
    
    //then
    assertThat(Files.readString(outputFile), equalTo(CSS));
    assertThat(Files.size(outputFile), lessThan(Files.size(inputFile)));
    assertThat(Files.deleteIfExists(inputFile), equalTo(true));
    assertThat(Files.deleteIfExists(outputFile), equalTo(true));
}
 
Example 6
Source File: GitToHgConverterTests.java    From skara with GNU General Public License v2.0 5 votes vote down vote up
@Test
void convertMergeCommitWithP0Diff() throws IOException {
    try (var hgRoot = new TemporaryDirectory();
         var gitRoot = new TemporaryDirectory()) {
        var gitRepo = Repository.init(gitRoot.path(), VCS.GIT);
        var readme = gitRoot.path().resolve("README.md");

        Files.writeString(readme, "First line\n");
        gitRepo.add(readme);
        gitRepo.commit("First line", "Foo Bar", "[email protected]");

        Files.writeString(readme, "Second line", StandardOpenOption.APPEND);
        gitRepo.add(readme);
        var second = gitRepo.commit("Second line\n", "Foo Bar", "[email protected]");

        Files.writeString(readme, "Third line\n", StandardOpenOption.APPEND);
        gitRepo.add(readme);
        var third = gitRepo.commit("Third line", "Foo Bar", "[email protected]");

        gitRepo.checkout(second, false);

        var contributing = gitRoot.path().resolve("CONTRIBUTING.md");
        Files.writeString(contributing, "Contribute\n");
        gitRepo.add(contributing);
        var toMerge = gitRepo.commit("Contributing", "Foo Bar", "[email protected]");

        gitRepo.checkout(third, false);
        gitRepo.merge(toMerge);
        Files.writeString(readme, "Fourth line\n", StandardOpenOption.APPEND);
        gitRepo.add(readme);
        gitRepo.commit("Merge", "Foo Bar", "[email protected]");

        var hgRepo = Repository.init(hgRoot.path(), VCS.HG);
        var converter = new GitToHgConverter();
        converter.convert(gitRepo, hgRepo);
        assertReposEquals(gitRepo, hgRepo);
    }
}
 
Example 7
Source File: StartScriptsMutator.java    From gradle-modules-plugin with MIT License 5 votes vote down vote up
private static void replaceLibsPlaceHolder(Path path, String libText, String patchLibText) {
    try {
        String updatedScriptContent = Files.readString(path)
                .replaceAll(LIBS_PLACEHOLDER, libText)
                .replaceAll(PATCH_LIBS_PLACEHOLDER, patchLibText);

        Files.writeString(path, updatedScriptContent);
    } catch (IOException e) {
        throw new GradleException("Couldn't replace placeholder in " + path);
    }
}
 
Example 8
Source File: GitToHgConverterTests.java    From skara with GNU General Public License v2.0 5 votes vote down vote up
@Test
void convertCommitWithSummary() throws IOException {
    try (var hgRoot = new TemporaryDirectory();
         var gitRoot = new TemporaryDirectory()) {
        var gitRepo = Repository.init(gitRoot.path(), VCS.GIT);
        var readme = gitRoot.path().resolve("README.md");

        Files.writeString(readme, "Hello, world");
        gitRepo.add(readme);
        var message = List.of("1234567: Added README",
                              "",
                              "Additional text",
                              "",
                              "Co-authored-by: Baz Bar <[email protected]>");
        gitRepo.commit(String.join("\n", message), "Foo Bar", "[email protected]",
                                                   "Baz Bar", "[email protected]");

        var hgRepo = Repository.init(hgRoot.path(), VCS.HG);
        var converter = new GitToHgConverter();
        converter.convert(gitRepo, hgRepo);

        var hgCommits = hgRepo.commits().asList();
        assertEquals(1, hgCommits.size());
        var hgCommit = hgCommits.get(0);

        assertEquals(new Author("baz", null), hgCommit.author());
        assertEquals(List.of("1234567: Added README",
                             "Summary: Additional text",
                             "Contributed-by: Foo Bar <[email protected]>, Baz Bar <[email protected]>"),
                     hgCommit.message());
        assertReposEquals(gitRepo, hgRepo);
    }
}
 
Example 9
Source File: GitToHgConverterTests.java    From skara with GNU General Public License v2.0 5 votes vote down vote up
@Test
void convertMergeCommitWithP1Diff() throws IOException {
    try (var hgRoot = new TemporaryDirectory();
         var gitRoot = new TemporaryDirectory()) {
        var gitRepo = Repository.init(gitRoot.path(), VCS.GIT);
        var readme = gitRoot.path().resolve("README.md");

        Files.writeString(readme, "First line\n");
        gitRepo.add(readme);
        gitRepo.commit("First line", "Foo Bar", "[email protected]");

        Files.writeString(readme, "Second line\n", StandardOpenOption.APPEND);
        gitRepo.add(readme);
        var second = gitRepo.commit("Second line", "Foo Bar", "[email protected]");

        Files.writeString(readme, "Third line\n", StandardOpenOption.APPEND);
        gitRepo.add(readme);
        var third = gitRepo.commit("Third line", "Foo Bar", "[email protected]");

        gitRepo.checkout(second, false);

        var contributing = gitRoot.path().resolve("CONTRIBUTING.md");
        Files.writeString(contributing, "Contribute\n");
        gitRepo.add(contributing);
        var toMerge = gitRepo.commit("Contributing", "Foo Bar", "[email protected]");

        gitRepo.checkout(third, false);
        gitRepo.merge(toMerge);
        Files.writeString(contributing, "More contributions\n", StandardOpenOption.APPEND);
        gitRepo.add(contributing);
        gitRepo.commit("Merge", "Foo Bar", "[email protected]");

        var hgRepo = Repository.init(hgRoot.path(), VCS.HG);
        var converter = new GitToHgConverter();
        converter.convert(gitRepo, hgRepo);
        assertReposEquals(gitRepo, hgRepo);
    }
}
 
Example 10
Source File: ForwardBotTests.java    From skara with GNU General Public License v2.0 5 votes vote down vote up
@Test
void mirrorMasterBranches(TestInfo testInfo) throws IOException {
    try (var temp = new TemporaryDirectory()) {
        var host = TestHost.createNew(List.of(new HostUser(0, "duke", "J. Duke")));

        var fromDir = temp.path().resolve("from.git");
        var fromLocalRepo = Repository.init(fromDir, VCS.GIT);
        var fromHostedRepo = new TestHostedRepository(host, "test", fromLocalRepo);

        var toDir = temp.path().resolve("to.git");
        var toLocalRepo = Repository.init(toDir, VCS.GIT);
        var gitConfig = toDir.resolve(".git").resolve("config");
        Files.write(gitConfig, List.of("[receive]", "denyCurrentBranch = ignore"),
                    StandardOpenOption.APPEND);
        var toHostedRepo = new TestHostedRepository(host, "test-mirror", toLocalRepo);

        var newFile = fromDir.resolve("this-file-cannot-exist.txt");
        Files.writeString(newFile, "Hello world\n");
        fromLocalRepo.add(newFile);
        var newHash = fromLocalRepo.commit("An additional commit", "duke", "[email protected]");
        var fromCommits = fromLocalRepo.commits().asList();
        assertEquals(1, fromCommits.size());
        assertEquals(newHash, fromCommits.get(0).hash());

        var toCommits = toLocalRepo.commits().asList();
        assertEquals(0, toCommits.size());

        var storage = temp.path().resolve("storage");
        var bot = new ForwardBot(storage, fromHostedRepo, master, toHostedRepo, master);
        TestBotRunner.runPeriodicItems(bot);

        toCommits = toLocalRepo.commits().asList();
        assertEquals(1, toCommits.size());
        assertEquals(newHash, toCommits.get(0).hash());
    }
}
 
Example 11
Source File: GitToHgConverterTests.java    From skara with GNU General Public License v2.0 5 votes vote down vote up
@Test
void convertOneCommit() throws IOException {
    try (var hgRoot = new TemporaryDirectory();
         var gitRoot = new TemporaryDirectory()) {
        var gitRepo = Repository.init(gitRoot.path(), VCS.GIT);
        var readme = gitRoot.path().resolve("README.md");

        Files.writeString(readme, "Hello, world");
        gitRepo.add(readme);
        gitRepo.commit("1234567: Added README", "Foo Bar", "[email protected]");

        var hgRepo = Repository.init(hgRoot.path(), VCS.HG);
        var converter = new GitToHgConverter();
        converter.convert(gitRepo, hgRepo);

        var gitCommits = gitRepo.commits().asList();
        assertEquals(1, gitCommits.size());
        var gitCommit = gitCommits.get(0);

        var hgCommits = hgRepo.commits().asList();
        assertEquals(1, hgCommits.size());
        var hgCommit = hgCommits.get(0);

        assertEquals(hgCommit.author(), new Author("foo", null));
        assertEquals(hgCommit.message(), gitCommit.message());
        assertTrue(hgCommit.isInitialCommit());

        assertReposEquals(gitRepo, hgRepo);
    }
}
 
Example 12
Source File: N4jscMain.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private static void writePerformanceReportIfRequested(N4jscOptions options) throws N4jscException {
	if (options.isDefinedPerformanceOption()) {
		String performanceKey = options.getPerformanceKey();
		File performanceReportFile = options.getPerformanceReport();

		performanceReportFile = FileUtils.appendTimeStampToFileName(performanceReportFile.toPath()).toFile();

		String absFileString = performanceReportFile.toPath().toAbsolutePath().toString();
		N4jscConsole.println("Writing performance report: " + absFileString);

		try {
			if (absFileString.endsWith(".csv")) {
				if ("*".equals(performanceKey.trim())) {
					throw new UnsupportedOperationException(); // a validation makes sure we won't reach this line
				}
				DataCollectorCSVExporter.toFile(performanceReportFile, performanceKey);
			} else {
				String indent = "    ";
				String dataStr = "*".equals(performanceKey)
						? DataCollectorUtils.allDataToString(indent)
						: DataCollectorUtils.dataToString(performanceKey, indent);
				Files.writeString(performanceReportFile.toPath(), dataStr + System.lineSeparator());
			}
		} catch (IOException e) {
			throw new N4jscException(N4jscExitCode.PERFORMANCE_REPORT_ERROR, e);
		}
	}
}
 
Example 13
Source File: SwaggerGenerator.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void generateSwaggerJson() throws Exception {
    Set<Class<?>> classes = new HashSet<>(endpointConfig.getClasses());
    classes.add(FreeIpaApi.class);
    Swagger swagger = new Reader(SwaggerConfigLocator.getInstance().getConfig(SwaggerContextService.CONFIG_ID_DEFAULT).configure(new Swagger()))
            .read(classes);
    Path path = Paths.get("./build/swagger/freeipa.json");
    Files.createDirectories(path.getParent());
    Files.writeString(path, Json.pretty(swagger));
}
 
Example 14
Source File: ValidatorLoaderTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void initializeValidatorsWithBothLocalAndExternalSigners(@TempDir Path tempDir)
    throws IOException {
  final Path validatorKeyFile = tempDir.resolve("validatorKeyFile");
  Files.writeString(validatorKeyFile, VALIDATOR_KEY_FILE);

  final TekuConfiguration tekuConfiguration =
      TekuConfiguration.builder()
          .setValidatorExternalSignerUrl("http://localhost:9000")
          .setValidatorExternalSignerPublicKeys(Collections.singletonList(PUBLIC_KEY2))
          .setValidatorKeyFile(validatorKeyFile.toAbsolutePath().toString())
          .setValidatorKeystoreFiles(emptyList())
          .setValidatorKeystorePasswordFiles(emptyList())
          .build();
  final Map<BLSPublicKey, Validator> validators =
      ValidatorLoader.initializeValidators(tekuConfiguration);

  assertThat(validators).hasSize(2);

  final BLSPublicKey key1 = BLSPublicKey.fromBytes(Bytes.fromHexString(PUBLIC_KEY1));
  final Validator validator1 = validators.get(key1);
  assertThat(validator1).isNotNull();
  assertThat(validator1.getPublicKey()).isEqualTo(key1);
  assertThat(validator1.getSigner().getMessageSignerService())
      .isInstanceOf(LocalMessageSignerService.class);

  final BLSPublicKey key2 = BLSPublicKey.fromBytes(Bytes.fromHexString(PUBLIC_KEY2));
  final Validator validator2 = validators.get(key2);
  assertThat(validator2).isNotNull();
  assertThat(validator2.getPublicKey()).isEqualTo(key2);
  assertThat(validator2.getSigner().getMessageSignerService())
      .isInstanceOf(ExternalMessageSignerService.class);
}
 
Example 15
Source File: JWTAuthOptionsFactoryTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void failsToCreateOptionsWhenPublicKeyFileIsInvalid() throws IOException {
  final JWTAuthOptionsFactory jwtAuthOptionsFactory = new JWTAuthOptionsFactory();
  final Path enclavePublicKey = Files.createTempFile("enclave", "pub");
  Files.writeString(enclavePublicKey, "invalidDataNo---HeadersAndNotBase64");

  assertThatThrownBy(
          () -> jwtAuthOptionsFactory.createForExternalPublicKey(enclavePublicKey.toFile()))
      .isInstanceOf(IllegalStateException.class)
      .hasMessage("Authentication RPC public key file format is invalid");
}
 
Example 16
Source File: HgToGitConverterTests.java    From skara with GNU General Public License v2.0 5 votes vote down vote up
@Test
void convertCommitWithSummary() throws IOException {
    try (var hgRoot = new TemporaryDirectory();
         var gitRoot = new TemporaryDirectory()) {
        var hgRepo = Repository.init(hgRoot.path(), VCS.HG);
        var readme = hgRoot.path().resolve("README.md");

        Files.writeString(readme, "Hello, world");
        hgRepo.add(readme);
        var message = List.of("1234567: Added README", "Summary: additional text", "Contributed-by: [email protected], [email protected]");
        hgRepo.commit(String.join("\n", message), "foo", "[email protected]");

        var gitRepo = Repository.init(gitRoot.path(), VCS.GIT);

        var converter = new HgToGitConverter(Map.of(), Map.of(), Set.of(), Set.of(),
                                             Map.of("foo", "Foo Bar <[email protected]>"),
                                             Map.of("[email protected]", "Baz Bar <[email protected]>",
                                                    "[email protected]", "Foo Bar <[email protected]>"),
                                             Map.of("foo", List.of("[email protected]")));
        var marks = converter.convert(hgRepo, gitRepo);
        assertEquals(1, marks.size());

        var gitCommits = gitRepo.commits().asList();
        assertEquals(1, gitCommits.size());
        var gitCommit = gitCommits.get(0);

        var hgCommits = hgRepo.commits().asList();
        assertEquals(1, hgCommits.size());
        var hgCommit = hgCommits.get(0);

        assertEquals(new Author("Foo Bar", "[email protected]"), gitCommit.author());
        assertEquals(new Author("Foo Bar", "[email protected]"), gitCommit.committer());
        assertEquals(List.of("1234567: Added README", "", "Additional text", "", "Co-authored-by: Baz Bar <[email protected]>"),
                     gitCommit.message());
    }
}
 
Example 17
Source File: JwtHelper.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private RsaJsonWebKey generateNewKey() throws JoseException, FileNotFoundException, IOException {
    RsaJsonWebKey newKey = RsaJwkGenerator.generateJwk(2048);

    File file = new File(KEY_FILE_PATH);
    file.getParentFile().mkdirs();

    String keyJson = newKey.toJson(OutputControlLevel.INCLUDE_PRIVATE);

    Files.writeString(file.toPath(), keyJson, StandardCharsets.UTF_8);
    return newKey;
}
 
Example 18
Source File: SponsorTests.java    From skara with GNU General Public License v2.0 4 votes vote down vote up
@Test
void sponsorMergeCommit(TestInfo testInfo) throws IOException {
    try (var credentials = new HostCredentials(testInfo);
         var tempFolder = new TemporaryDirectory(false)) {
        var author = credentials.getHostedRepository();
        var integrator = credentials.getHostedRepository();
        var reviewer = credentials.getHostedRepository();

        var reviewerId = reviewer.forge().currentUser().id();
        var censusBuilder = credentials.getCensusBuilder()
                                       .addReviewer(reviewerId)
                                       .addAuthor(author.forge().currentUser().id());
        var mergeBot = PullRequestBot.newBuilder().repo(integrator).censusRepo(censusBuilder.build()).build();

        // Populate the projects repository
        var localRepo = CheckableRepository.init(tempFolder.path().resolve("local.git"), author.repositoryType());
        var initialHash = localRepo.resolve("master").orElseThrow();
        assertFalse(CheckableRepository.hasBeenEdited(localRepo));
        var anotherFile = localRepo.root().resolve("ANOTHER_FILE.txt");
        Files.writeString(anotherFile, "A string\n");
        localRepo.add(anotherFile);
        var masterHash = localRepo.commit("Another commit\n\nReviewed-by: " + reviewerId, "duke", "[email protected]");
        localRepo.push(masterHash, author.url(), "master", true);

        // Create a new branch, new commit and publish it
        var editBranch = localRepo.branch(initialHash, "edit");
        localRepo.checkout(editBranch);
        var editHash = CheckableRepository.appendAndCommit(localRepo);
        localRepo.push(editHash, author.url(), "edit", true);

        // Prepare to merge edit into master
        localRepo.checkout(new Branch("master"));
        var editToMasterBranch = localRepo.branch(masterHash, "edit->master");
        localRepo.checkout(editToMasterBranch);
        localRepo.merge(editHash);
        var mergeHash = localRepo.commit("Merge edit", "duke", "[email protected]");
        localRepo.push(mergeHash, author.url(), "edit->master", true);


        var pr = credentials.createPullRequest(author, "master", "edit->master", "Merge edit");

        // Approve it as another user
        var approvalPr = reviewer.pullRequest(pr.id());
        approvalPr.addReview(Review.Verdict.APPROVED, "Approved");

        // Let the bot see it
        TestBotRunner.runPeriodicItems(mergeBot);

        // Issue a merge command without being a Committer
        pr.addComment("/integrate");
        TestBotRunner.runPeriodicItems(mergeBot);

        //System.out.println(pr.comments());
        //for (var entry : pr.checks(pr.headHash()).entrySet()) {
        //    System.out.println(entry.getValue().summary().orElseThrow());
        //}

        // The bot should reply that a sponsor is required
        var sponsor = pr.comments().stream()
                        .filter(comment -> comment.body().contains("sponsor"))
                        .filter(comment -> comment.body().contains("your change"))
                        .count();
        assertEquals(1, sponsor);

        // The bot should not have pushed the commit
        var notPushed = pr.comments().stream()
                          .filter(comment -> comment.body().contains("Pushed as commit"))
                          .count();
        assertEquals(0, notPushed);

        // Reviewer now agrees to sponsor
        var reviewerPr = reviewer.pullRequest(pr.id());
        reviewerPr.addComment("/sponsor");
        TestBotRunner.runPeriodicItems(mergeBot);

        // The bot should have pushed the commit
        var pushed = pr.comments().stream()
                       .filter(comment -> comment.body().contains("Pushed as commit"))
                       .count();
        assertEquals(1, pushed);

        var targetRepo = Repository.clone(author.url(), tempFolder.path().resolve("target.git"));
        var masterHead = targetRepo.lookup(new Branch("origin/master")).orElseThrow();
        assertEquals("Merge edit", masterHead.message().get(0));
    }
}
 
Example 19
Source File: YamlValidatorKeyProviderTest.java    From teku with Apache License 2.0 4 votes vote down vote up
private Path writeTestFile(final Path tempDirectory, final String contents) throws IOException {
  final Path tempFile = tempDirectory.resolve("keys.yaml");
  Files.writeString(tempFile, contents);
  return tempFile;
}
 
Example 20
Source File: SponsorTests.java    From skara with GNU General Public License v2.0 4 votes vote down vote up
@Test
void noAutoRebase(TestInfo testInfo) throws IOException {
    try (var credentials = new HostCredentials(testInfo);
         var tempFolder = new TemporaryDirectory();
         var pushedFolder = new TemporaryDirectory()) {

        var author = credentials.getHostedRepository();
        var integrator = credentials.getHostedRepository();
        var reviewer = credentials.getHostedRepository();
        var censusBuilder = credentials.getCensusBuilder()
                                       .addAuthor(author.forge().currentUser().id())
                                       .addReviewer(integrator.forge().currentUser().id())
                                       .addReviewer(reviewer.forge().currentUser().id());
        var mergeBot = PullRequestBot.newBuilder().repo(integrator).censusRepo(censusBuilder.build()).build();

        // Populate the projects repository
        var localRepo = CheckableRepository.init(tempFolder.path(), author.repositoryType());
        var masterHash = localRepo.resolve("master").orElseThrow();
        assertFalse(CheckableRepository.hasBeenEdited(localRepo));
        localRepo.push(masterHash, author.url(), "master", true);

        // Make a change with a corresponding PR
        var editHash = CheckableRepository.appendAndCommit(localRepo);
        localRepo.push(editHash, author.url(), "edit", true);
        var pr = credentials.createPullRequest(author, "master", "edit", "This is a pull request");

        // Approve it as another user
        var approvalPr = integrator.pullRequest(pr.id());
        approvalPr.addReview(Review.Verdict.APPROVED, "Approved");

        // Push something unrelated to master
        localRepo.checkout(masterHash, true);
        var unrelated = localRepo.root().resolve("unrelated.txt");
        Files.writeString(unrelated, "Hello");
        localRepo.add(unrelated);
        var unrelatedHash = localRepo.commit("Unrelated", "X", "[email protected]");
        localRepo.push(unrelatedHash, author.url(), "master");

        // Issue a merge command without being a Committer
        pr.addComment("/integrate " + masterHash);
        TestBotRunner.runPeriodicItems(mergeBot);

        // The bot should reply with an error message
        assertLastCommentContains(pr, "the target branch is no longer at the requested hash");

        // Now choose the actual hash
        pr.addComment("/integrate " + unrelatedHash);
        TestBotRunner.runPeriodicItems(mergeBot);

        // The bot should reply that a sponsor is required
        assertLastCommentContains(pr, "your sponsor will make the final decision onto which target hash to integrate");

        // Push more unrelated things
        Files.writeString(unrelated, "Hello again");
        localRepo.add(unrelated);
        var unrelatedHash2 = localRepo.commit("Unrelated 2", "X", "[email protected]");
        localRepo.push(unrelatedHash2, author.url(), "master");

        // Reviewer now agrees to sponsor
        var reviewerPr = reviewer.pullRequest(pr.id());
        reviewerPr.addComment("/sponsor " + unrelatedHash);
        TestBotRunner.runPeriodicItems(mergeBot);

        // The bot should reply with an error message
        assertLastCommentContains(pr, "head of the target branch is no longer at the requested hash");

        // Use the current hash
        reviewerPr.addComment("/sponsor " + unrelatedHash2);
        TestBotRunner.runPeriodicItems(mergeBot);

        // The bot should reply with an ok message
        assertLastCommentContains(pr, "Pushed as commit");

        // The change should now be present on the master branch
        var pushedRepo = Repository.materialize(pushedFolder.path(), author.url(), "master");
        assertTrue(CheckableRepository.hasBeenEdited(pushedRepo));
    }
}