This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-9251-675167c1fcba483c726a26c990d06323f85794d6 in repository https://gitbox.apache.org/repos/asf/texera.git
commit 60f32abcd7c2b4ce586cacf90dceb59165ca74ec Author: Xinyuan Lin <[email protected]> AuthorDate: Mon Nov 2 22:03:12 2026 +0000 refactor(workflow-core): drop pre-LakeFS git dataset storage (#9251) ### What changes were proposed in this PR? Removes the obsolete pre-LakeFS local-git dataset storage package in `common/workflow-core`: - Drops `GitVersionControlLocalFileStorage.java` (-210 lines). - Drops `JGitVersionControl.java` (-248 lines). - Drops `PhysicalFileNode.java` (-109 lines). - Drops companion unit test suites (-1,061 lines): - `amber/src/test/java/org/apache/texera/web/resource/dashboard/user/dataset/GitVersionControlLocalFileStorageSpec.java` - `common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/util/dataset/GitVersionControlLocalFileStorageSpec.scala` - `common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/util/dataset/JGitVersionControlSpec.scala` - `common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/util/dataset/PhysicalFileNodeSpec.scala` The local-git dataset versioning architecture was completely superseded by LakeFS / Iceberg storage (`LakeFSStorage`, `IcebergCatalogInstance`, `IcebergDocument`), leaving this package with zero callers across active engine and services. **+0/-1,628 lines.** Pure refactoring with no behavior change. ### Any related issues, documentation, discussions? Closes #9249. ### How was this PR tested? - Scalafmt check passed: ```bash sbt "project WorkflowCore" scalafmtCheck "Test / scalafmtCheck" sbt "project WorkflowExecutionService" scalafmtCheck "Test / scalafmtCheck" ``` - WorkflowCore and Amber compilation passed: ```bash sbt "project WorkflowCore" compile Test/compile sbt "project WorkflowExecutionService" Test/compile ``` - WorkflowCore unit tests passed (715 tests, 47 suites): ```bash sbt "project WorkflowCore" test ``` - Verified 0 callers repo-wide across all 3,517 files. ### Was this PR authored or co-authored using generative AI tooling? Generated-by: Antigravity 2.0 --- .../GitVersionControlLocalFileStorageSpec.java | 222 -------- .../dataset/GitVersionControlLocalFileStorage.java | 210 -------- .../storage/util/dataset/JGitVersionControl.java | 248 --------- .../storage/util/dataset/PhysicalFileNode.java | 109 ---- .../GitVersionControlLocalFileStorageSpec.scala | 173 ------- .../util/dataset/JGitVersionControlSpec.scala | 556 --------------------- .../util/dataset/PhysicalFileNodeSpec.scala | 110 ---- 7 files changed, 1628 deletions(-) diff --git a/amber/src/test/java/org/apache/texera/web/resource/dashboard/user/dataset/GitVersionControlLocalFileStorageSpec.java b/amber/src/test/java/org/apache/texera/web/resource/dashboard/user/dataset/GitVersionControlLocalFileStorageSpec.java deleted file mode 100644 index a07410b145..0000000000 --- a/amber/src/test/java/org/apache/texera/web/resource/dashboard/user/dataset/GitVersionControlLocalFileStorageSpec.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.texera.web.resource.dashboard.user.dataset; - -import org.apache.texera.amber.core.storage.util.dataset.GitVersionControlLocalFileStorage; -import org.apache.texera.amber.core.storage.util.dataset.PhysicalFileNode; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -public class GitVersionControlLocalFileStorageSpec { - - private Path testRepoPath; - - private List<String> testRepoMasterCommitHashes; - private final String testFile1Name = "testFile1.txt"; - - private final String testFile2Name = "testFile2.txt"; - private final String testDirectoryName = "testDir"; - - private final String testFile1ContentV1 = "This is a test file1 v1"; - private final String testFile1ContentV2 = "This is a test file1 v2"; - private final String testFile1ContentV3 = "This is a test file1 v3"; - - private final String testFile2Content = "This is a test file2 in the testDir"; - - private void writeFileToRepo(Path filePath, String fileContent) throws IOException, GitAPIException { - try (ByteArrayInputStream input = new ByteArrayInputStream(fileContent.getBytes())) { - GitVersionControlLocalFileStorage.writeFileToRepo(testRepoPath, filePath, input); - } - } - - @Before - public void setUp() throws IOException, GitAPIException { - // Create a temporary directory for the repository - testRepoPath = Files.createTempDirectory("testRepo"); - GitVersionControlLocalFileStorage.initRepo(testRepoPath); - - Path file1Path = testRepoPath.resolve(testFile1Name); - // Version 1 - String v1Hash = GitVersionControlLocalFileStorage.withCreateVersion( - testRepoPath, - "v1", - () -> { - try { - writeFileToRepo(file1Path, testFile1ContentV1); - } catch (IOException | GitAPIException e) { - throw new RuntimeException(e); - } - }); - - String v2Hash = GitVersionControlLocalFileStorage.withCreateVersion( - testRepoPath, - "v2", - () -> { - try { - writeFileToRepo(file1Path, testFile1ContentV2); - } catch (IOException | GitAPIException e) { - throw new RuntimeException(e); - } - }); - - // Version 3 - String v3Hash = GitVersionControlLocalFileStorage.withCreateVersion( - testRepoPath, - "v3", - () -> { - try { - writeFileToRepo(file1Path, testFile1ContentV3); - } catch (IOException | GitAPIException e) { - throw new RuntimeException(e); - } - }); - - testRepoMasterCommitHashes = new ArrayList<String>() {{ - add(v1Hash); - add(v2Hash); - add(v3Hash); - }}; - } - - @After - public void tearDown() throws IOException { - // Clean up the test repository directory - GitVersionControlLocalFileStorage.deleteRepo(testRepoPath); - } - - @Test - public void testFileContentAcrossVersions() throws IOException, GitAPIException { - // File path for the test file - Path filePath = testRepoPath.resolve(testFile1Name); - - // testRepoMasterCommitHashes is populated in chronological order: v1, v2, v3 - // Retrieve and compare file content for version 1 - ByteArrayOutputStream outputV1 = new ByteArrayOutputStream(); - GitVersionControlLocalFileStorage.retrieveFileContentOfVersion(testRepoPath, testRepoMasterCommitHashes.get(0), filePath, outputV1); - String retrievedContentV1 = outputV1.toString(); - Assert.assertEquals( - "Content for version 1 does not match", - testFile1ContentV1, - retrievedContentV1); - - // Retrieve and compare file content for version 2 - ByteArrayOutputStream outputV2 = new ByteArrayOutputStream(); - GitVersionControlLocalFileStorage.retrieveFileContentOfVersion(testRepoPath, testRepoMasterCommitHashes.get(1), filePath, outputV2); - String retrievedContentV2 = outputV2.toString(); - Assert.assertEquals( - "Content for version 2 does not match", - testFile1ContentV2, - retrievedContentV2); - - // Retrieve and compare file content for version 3 - ByteArrayOutputStream outputV3 = new ByteArrayOutputStream(); - GitVersionControlLocalFileStorage.retrieveFileContentOfVersion(testRepoPath, testRepoMasterCommitHashes.get(2), filePath, outputV3); - String retrievedContentV3 = outputV3.toString(); - Assert.assertEquals( - "Content for version 3 does not match", - testFile1ContentV3, - retrievedContentV3); - } - - @Test - public void testFileTreeRetrieval() throws Exception { - // File path for the test file - Path file1Path = testRepoPath.resolve(testFile1Name); - PhysicalFileNode file1Node = new PhysicalFileNode(testRepoPath, file1Path, Files.size(file1Path)); - Set<PhysicalFileNode> physicalFileNodes = new HashSet<PhysicalFileNode>() {{ - add(file1Node); - }}; - - // first retrieve the latest version's file tree - Assert.assertEquals("File Tree should match", - physicalFileNodes, - GitVersionControlLocalFileStorage.retrieveRootFileNodesOfVersion(testRepoPath, testRepoMasterCommitHashes.get(testRepoMasterCommitHashes.size() - 1))); - - // now we add a new file testDir/testFile2.txt - Path testDirPath = testRepoPath.resolve(testDirectoryName); - Path file2Path = testDirPath.resolve(testFile2Name); - - String v4Hash = GitVersionControlLocalFileStorage.withCreateVersion(testRepoPath, "v4", () -> { - try { - writeFileToRepo(file2Path, testFile2Content); - } catch (IOException | GitAPIException e) { - throw new RuntimeException(e); - } - }); - testRepoMasterCommitHashes.add(v4Hash); - - PhysicalFileNode dirNode = new PhysicalFileNode(testRepoPath, testDirPath, 0); // Directories typically have size 0 - dirNode.addChildNode(new PhysicalFileNode(testRepoPath, file2Path, Files.size(file2Path))); - // update the expected fileNodes - physicalFileNodes.add(dirNode); - - // check the file tree - Assert.assertEquals( - "File Tree should match", - physicalFileNodes, - GitVersionControlLocalFileStorage.retrieveRootFileNodesOfVersion(testRepoPath, v4Hash)); - - // now we delete the file1, check the filetree - String v5Hash = GitVersionControlLocalFileStorage.withCreateVersion(testRepoPath, "v5", () -> { - try { - GitVersionControlLocalFileStorage.removeFileFromRepo(testRepoPath, file1Path); - } catch (IOException | GitAPIException e) { - throw new RuntimeException(e); - } - }); - - physicalFileNodes.remove(file1Node); - Assert.assertEquals( - "File1 should be gone", - physicalFileNodes, - GitVersionControlLocalFileStorage.retrieveRootFileNodesOfVersion(testRepoPath, v5Hash) - ); - - } - - @Test - public void testUncommittedCheckAndRecoverToLatest() throws Exception { - Path tempFilePath = testRepoPath.resolve("tempFile"); - String content = "some random content"; - writeFileToRepo(tempFilePath, content); - - Assert.assertTrue( - "There should be some uncommitted changes", - GitVersionControlLocalFileStorage.hasUncommittedChanges(testRepoPath)); - - GitVersionControlLocalFileStorage.discardUncommittedChanges(testRepoPath); - - Assert.assertFalse("There should be no uncommitted changes", - GitVersionControlLocalFileStorage.hasUncommittedChanges(testRepoPath)); - } -} diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/util/dataset/GitVersionControlLocalFileStorage.java b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/util/dataset/GitVersionControlLocalFileStorage.java deleted file mode 100644 index 9208bad126..0000000000 --- a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/util/dataset/GitVersionControlLocalFileStorage.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.texera.amber.core.storage.util.dataset; - -import org.eclipse.jgit.api.errors.GitAPIException; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.util.Comparator; -import java.util.Set; - -/** - * Git-based implementation of the VersionControlFileStorageService, using local file storage. - */ -public class GitVersionControlLocalFileStorage { - - /** - * Writes content from the InputStream to a file at the given path. And stage the file addition/modification to git - * This function WILL create the missing parent directory along the path - - * This method is NOT THREAD SAFE, as it did the file I/O and the git add operation - * @param filePath The path within the repository to write the file. - * @param inputStream The InputStream from which to read the content. - * @throws IOException If an I/O error occurs. - */ - public static void writeFileToRepo(Path repoPath, Path filePath, InputStream inputStream) throws IOException, GitAPIException { - Files.createDirectories(filePath.getParent()); - Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING); - // stage the addition/modification - JGitVersionControl.add(repoPath, filePath); - } - - /** - * Deletes a file at the given path. - * If the file path is pointing to a directory, or if file does not exist, error will be thrown - - * This method is NOT THREAD SAFE, as it did the file I/O and the git rm operation - * @param filePath The path of the file to delete. - * @throws IOException If an I/O error occurs. - */ - public static void removeFileFromRepo(Path repoPath, Path filePath) throws IOException, GitAPIException { - if (Files.isDirectory(filePath)) { - throw new IllegalArgumentException("Provided path is a directory, not a file: " + filePath); - } - - Files.delete(filePath); - // stage the deletion - JGitVersionControl.rm(repoPath, filePath); - } - - /** - * Deletes the entire repository specified by the path. - - * This method is NOT THREAD SAFE, as it did the file I/O recursively - * @param directoryPath The path of the directory to delete. - * @throws IOException If an I/O error occurs. - */ - public static void deleteRepo(Path directoryPath) throws IOException { - try (var stream = Files.walk(directoryPath)) { - stream - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); - } - } - - /** - * Initializes a new repository for version control at the specified path. - - * This method is NOT THREAD SAFE - * @param baseRepoPath Path to initialize the repository at. - * @return The branch identifier - * @throws IOException If an I/O error occurs. - * @throws GitAPIException If the JGit operation is interrupted. - */ - public static String initRepo(Path baseRepoPath) throws IOException, GitAPIException { - // Check if the directory exists, if not, create it - if (Files.notExists(baseRepoPath)) { - Files.createDirectories(baseRepoPath); - } - - return JGitVersionControl.initRepo(baseRepoPath); - } - - /** - * Executes a group of file operations as a single versioned transaction. The version is bumped after the operations finish. - - * This method is NOT THREAD SAFE as it potentially does lots of file I/O along with git operations - * @param baseRepoPath The repository path. - * @param versionName The name or message associated with the version. - * @param operations The file operations to be executed within this versioned transaction. - * @throws IOException If an I/O error occurs. - * @throws GitAPIException If a Git operation fails. - */ - public static String withCreateVersion(Path baseRepoPath, String versionName, Runnable operations) throws IOException, GitAPIException { - // Execute the provided file operations - operations.run(); - // After successful execution, create a new version with the specified name - return JGitVersionControl.commit(baseRepoPath, versionName); - } - - /** - * Retrieves the set of file nodes at the root level, identified by its commit hash. - - * This method is THREAD SAFE - * @param baseRepoPath The repository path. - * @param versionCommitHashVal The commit hash of the version. - * @return A set of file nodes at the root level of the given repo at given version - */ - public static Set<PhysicalFileNode> retrieveRootFileNodesOfVersion(Path baseRepoPath, String versionCommitHashVal) throws Exception { - return JGitVersionControl.getRootFileNodeOfCommit(baseRepoPath, versionCommitHashVal); - } - - /** - * Retrieves the content of a specific file from a specific version identified by its commit hash. - * Writes the file content to the provided OutputStream. - - * This method is THREAD SAFE - * @param baseRepoPath The repository path. - * @param commitHash The commit hash of the version from which the file content is retrieved. - * @param filePath The path of the file within the repository. - * @param outputStream The OutputStream to which the file content is written. - * @throws IOException If an I/O error occurs. - * @throws GitAPIException If the operation is interrupted. - */ - public static void retrieveFileContentOfVersion(Path baseRepoPath, String commitHash, Path filePath, OutputStream outputStream) throws IOException, GitAPIException { - JGitVersionControl.readFileContentOfCommitAsOutputStream(baseRepoPath, commitHash, filePath, outputStream); - } - - public static InputStream retrieveFileContentOfVersionAsInputStream(Path baseRepoPath, String commitHash, Path filePath) throws IOException { - return JGitVersionControl.readFileContentOfCommitAsInputStream(baseRepoPath, commitHash, filePath); - } - - /** - * Creates a temporary file and writes the content of a specific version of a file, identified by its commit hash, into this temporary file. - * This method is useful for retrieving and working with specific versions of a file from a Git repository in a temporary and isolated manner. - * - * The temporary file is created in the system's default temporary-file directory, with a prefix "versionedFile" and a ".tmp" suffix. - * The created temporary file is marked for deletion on JVM exit, ensuring no leftover files during runtime, though it's the caller's responsibility to manage the file if it needs to persist longer. - * - * @param baseRepoPath The path to the repository where the file version is to be retrieved from. This should be a valid path to a local repository managed by Git. - * @param commitHash The commit hash that identifies the specific version of the file to retrieve. This commit must exist in the repository's history. - * @param filePath The path of the file within the repository, relative to the repository's root directory. This file should exist in the commit specified. - * @return The {@link Path} to the created temporary file, which contains the content of the specified file version. This path is absolute, ensuring it can be accessed directly. - * @throws IOException If an I/O error occurs during file operations, including issues with creating the temporary file or writing to it. - * @throws GitAPIException If the operation to retrieve file content from the Git repository fails. This could be due to issues with accessing the repository, the commit hash, or the file path specified. - */ - public static Path writeVersionedFileToTempFile(Path baseRepoPath, String commitHash, Path filePath) throws IOException, GitAPIException { - // Generate a temporary file - Path tempFile = Files.createTempFile("versionedFile", ".tmp"); - - // Ensure the file gets deleted on JVM exit - tempFile.toFile().deleteOnExit(); - - // Use the retrieveFileContentOfVersion method to write the file content into the temp file - try (OutputStream outputStream = Files.newOutputStream(tempFile)) { - retrieveFileContentOfVersion(baseRepoPath, commitHash, filePath, outputStream); - } - - // Return the absolute path of the temporary file - return tempFile.toAbsolutePath(); - } - - /** - * Check if there is any uncommitted change in the given repo - - * This method is THREAD SAFE - * @param repoPath The repository path - * @return True if there are uncommitted changes. - * @throws GitAPIException - * @throws IOException - */ - public static boolean hasUncommittedChanges(Path repoPath) throws GitAPIException, IOException { - return JGitVersionControl.hasUncommittedChanges(repoPath); - } - - /** - * Recovers the repository to its latest version, discarding any uncommitted changes if any. - - * This method is NOT THREAD SAFE - * @param baseRepoPath The repository path. - * @throws IOException If an I/O error occurs. - * @throws GitAPIException If the operation is interrupted. - */ - public static void discardUncommittedChanges(Path baseRepoPath) throws IOException, GitAPIException { - JGitVersionControl.discardUncommittedChanges(baseRepoPath); - } -} diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/util/dataset/JGitVersionControl.java b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/util/dataset/JGitVersionControl.java deleted file mode 100644 index 4b438ae537..0000000000 --- a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/util/dataset/JGitVersionControl.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.texera.amber.core.storage.util.dataset; - -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.ResetCommand; -import org.eclipse.jgit.api.Status; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.ObjectLoader; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevWalk; -import org.eclipse.jgit.storage.file.FileRepositoryBuilder; -import org.eclipse.jgit.treewalk.TreeWalk; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -public class JGitVersionControl { - - public static String initRepo(Path path) throws GitAPIException, IOException { - File gitDir = path.resolve(".git").toFile(); - if (gitDir.exists()) { - throw new IOException("Repository already exists at " + path); - } - // try-with-resource make sure the resource is released - try (Git git = Git.init().setDirectory(path.toFile()).call()) { - // Retrieve the default branch name - Ref head = git.getRepository().exactRef("HEAD"); - if (head == null || head.getTarget() == null) { - return null; - } - String refName = head.getTarget().getName(); - // HEAD should be in the form of 'ref: refs/heads/defaultBranchName' - if (!refName.startsWith("refs/heads/")) { - return null; - } - return refName.substring("refs/heads/".length()); - } - } - - public static InputStream readFileContentOfCommitAsInputStream(Path repoPath, String commitHash, Path filePath) throws IOException { - if (!filePath.startsWith(repoPath)) { - throw new IllegalArgumentException("File path must be under the repository path."); - } - - if (Files.isDirectory(filePath)) { - throw new IllegalArgumentException("File path points to a directory, not a file."); - } - - try (Repository repository = new FileRepositoryBuilder() - .setGitDir(repoPath.resolve(".git").toFile()) - .build(); - RevWalk revWalk = new RevWalk(repository)) { - - RevCommit commit = revWalk.parseCommit(repository.resolve(commitHash)); - TreeWalk treeWalk = - TreeWalk.forPath(repository, repoPath.relativize(filePath).toString(), commit.getTree()); - if (treeWalk == null) { - throw new IOException("File not found in commit: " + filePath); - } - ObjectId objectId = treeWalk.getObjectId(0); - ObjectLoader loader = repository.open(objectId); - - // Return the InputStream for caller to manage - return loader.openStream(); - } - } - - public static void readFileContentOfCommitAsOutputStream(Path repoPath, String commitHash, Path filePath, OutputStream outputStream) throws IOException { - if (!filePath.startsWith(repoPath)) { - throw new IllegalArgumentException("File path must be under the repository path."); - } - - if (Files.isDirectory(filePath)) { - throw new IllegalArgumentException("File path points to a directory, not a file."); - } - - try (Repository repository = new FileRepositoryBuilder() - .setGitDir(repoPath.resolve(".git").toFile()) - .build(); - RevWalk revWalk = new RevWalk(repository)) { - - RevCommit commit = revWalk.parseCommit(repository.resolve(commitHash)); - TreeWalk treeWalk = - TreeWalk.forPath(repository, repoPath.relativize(filePath).toString(), commit.getTree()); - if (treeWalk == null) { - throw new IOException("File not found in commit: " + filePath); - } - ObjectId objectId = treeWalk.getObjectId(0); - ObjectLoader loader = repository.open(objectId); - - loader.copyTo(outputStream); - } - } - - public static Set<PhysicalFileNode> getRootFileNodeOfCommit(Path repoPath, String commitHash) throws Exception { - Map<String, PhysicalFileNode> pathToFileNodeMap = new HashMap<>(); - Set<PhysicalFileNode> rootNodes = new HashSet<>(); - - try (Repository repository = new FileRepositoryBuilder() - .setGitDir(repoPath.resolve(".git").toFile()) - .build(); - RevWalk revWalk = new RevWalk(repository)) { - ObjectId commitId = repository.resolve(commitHash); - RevCommit commit = revWalk.parseCommit(commitId); - - try (TreeWalk treeWalk = new TreeWalk(repository)) { - treeWalk.addTree(commit.getTree()); - treeWalk.setRecursive(false); - - while (treeWalk.next()) { - Path fullPath = repoPath.resolve(treeWalk.getPathString()); - long size = 0; - if (!treeWalk.isSubtree()) { - // Get file size for non-directory entries - ObjectId objectId = treeWalk.getObjectId(0); - ObjectLoader loader = repository.open(objectId); - size = loader.getSize(); - } - PhysicalFileNode currentNode = createOrGetNode(pathToFileNodeMap, repoPath, fullPath, size); - - if (treeWalk.isSubtree()) { - treeWalk.enterSubtree(); - } else { - // For files, we've already added them. Just ensure parent linkage is correct. - ensureParentChildLink(pathToFileNodeMap, repoPath, fullPath, currentNode); - } - - // For directories, also ensure they are correctly linked - if (currentNode.isDirectory()) { - ensureParentChildLink(pathToFileNodeMap, repoPath, fullPath, currentNode); - } - } - } - } - - // Extract root nodes - pathToFileNodeMap.values().forEach(node -> { - if (node.getAbsolutePath().getParent().equals(repoPath)) { - rootNodes.add(node); - } - }); - - return rootNodes; - } - - private static PhysicalFileNode createOrGetNode(Map<String, PhysicalFileNode> map, Path repoPath, Path path, long size) { - return map.computeIfAbsent(path.toString(), k -> new PhysicalFileNode(repoPath, path, size)); - } - - private static PhysicalFileNode createOrGetNode(Map<String, PhysicalFileNode> map, Path repoPath, Path path) { - return map.computeIfAbsent(path.toString(), k -> new PhysicalFileNode(repoPath, path, 0)); - } - - private static void ensureParentChildLink(Map<String, PhysicalFileNode> map, Path repoPath, Path childPath, PhysicalFileNode childNode) { - Path parentPath = childPath.getParent(); - if (parentPath != null && !parentPath.equals(repoPath)) { - PhysicalFileNode parentNode = createOrGetNode(map, repoPath, parentPath); - parentNode.addChildNode(childNode); - } - } - - public static void add(Path repoPath, Path filePath) throws IOException, GitAPIException { - try (Git git = Git.open(repoPath.toFile())) { - // Stage the file addition/modification - git.add().addFilepattern(repoPath.relativize(filePath).toString()).call(); - } - } - - public static void rm(Path repoPath, Path filePath) throws IOException, GitAPIException { - try (Git git = Git.open(repoPath.toFile())) { - git.rm().addFilepattern(repoPath.relativize(filePath).toString()).call(); // Stages the file deletion - } - } - - // create a commit, and return the commit hash - public static String commit(Path repoPath, String commitMessage) throws IOException, GitAPIException { - FileRepositoryBuilder builder = new FileRepositoryBuilder(); - try (Repository repository = builder.setGitDir(repoPath.resolve(".git").toFile()) - .readEnvironment() // scan environment GIT_* variables - .findGitDir() // scan up the file system tree - .build()) { - - try (Git git = new Git(repository)) { - // Commit the changes that have been staged - RevCommit commit = git.commit().setMessage(commitMessage).call(); - - // Return the commit hash - return commit.getId().getName(); - } - } - } - - public static void discardUncommittedChanges(Path repoPath) throws IOException, GitAPIException { - try (Repository repository = new FileRepositoryBuilder() - .setGitDir(repoPath.resolve(".git").toFile()) - .build(); - Git git = new Git(repository)) { - - // Reset hard to discard changes in tracked files - git.reset().setMode(ResetCommand.ResetType.HARD).call(); - - // Clean the working directory to remove untracked files - git.clean().setCleanDirectories(true).call(); - } - } - - public static boolean hasUncommittedChanges(Path repoPath) throws IOException, GitAPIException { - try (Repository repository = new FileRepositoryBuilder() - .setGitDir(repoPath.resolve(".git").toFile()) - .readEnvironment() - .findGitDir() - .build(); - Git git = new Git(repository)) { - - Status status = git.status().call(); - return !status.isClean(); - } - } -} diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/util/dataset/PhysicalFileNode.java b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/util/dataset/PhysicalFileNode.java deleted file mode 100644 index 07510335c1..0000000000 --- a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/util/dataset/PhysicalFileNode.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.texera.amber.core.storage.util.dataset; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.*; - -public class PhysicalFileNode { - private final Path absoluteFilePath; - private final Path relativeFilePath; - private final Set<PhysicalFileNode> children; - private long size; - - public PhysicalFileNode(Path repoPath, Path path, long size) { - this.absoluteFilePath = path; - this.relativeFilePath = repoPath.relativize(this.absoluteFilePath); - this.children = new HashSet<>(); - this.size = size; - } - - public boolean isFile() { - return Files.isRegularFile(absoluteFilePath); - } - - public boolean isDirectory() { - return Files.isDirectory(absoluteFilePath); - } - - public Path getAbsolutePath() { - return absoluteFilePath; - } - - public Path getRelativePath() { - return relativeFilePath; - } - - public void addChildNode(PhysicalFileNode child) { - if (!child.getAbsolutePath().getParent().equals(this.absoluteFilePath)) { - throw new IllegalArgumentException("Child node is not a direct subpath of the parent node"); - } - this.children.add(child); - } - - public Set<PhysicalFileNode> getChildren() { - return children; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - PhysicalFileNode physicalFileNode = (PhysicalFileNode) o; - return Objects.equals(absoluteFilePath, physicalFileNode.absoluteFilePath) && - Objects.equals(children, physicalFileNode.children); - } - - @Override - public int hashCode() { - return Objects.hash(absoluteFilePath, children); - } - - /** - * Collects the relative paths of all file nodes from a given set of FileNode. - * @param nodes The set of FileNode to collect file paths from. - * @return A list of strings representing the relative paths of all file nodes. - */ - public static List<String> getAllFileRelativePaths(Set<PhysicalFileNode> nodes) { - List<String> filePaths = new ArrayList<>(); - getAllFileRelativePathsHelper(nodes, filePaths); - return filePaths; - } - - /** - * Helper method to recursively collect the relative paths of all file nodes. - * @param nodes The current set of FileNode to collect file paths from. - * @param filePaths The list to add the relative paths of the file nodes to. - */ - private static void getAllFileRelativePathsHelper(Set<PhysicalFileNode> nodes, List<String> filePaths) { - for (PhysicalFileNode node : nodes) { - if (node.isFile()) { - filePaths.add(node.getRelativePath().toString()); - } else if (node.isDirectory()) { - getAllFileRelativePathsHelper(node.getChildren(), filePaths); - } - } - } - - public long getSize() { - return size; - } -} diff --git a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/util/dataset/GitVersionControlLocalFileStorageSpec.scala b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/util/dataset/GitVersionControlLocalFileStorageSpec.scala deleted file mode 100644 index ef8660ff1f..0000000000 --- a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/util/dataset/GitVersionControlLocalFileStorageSpec.scala +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. - * - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.texera.amber.core.storage.util.dataset - -import org.eclipse.jgit.api.Git -import org.scalatest.flatspec.AnyFlatSpec - -import java.io.{ByteArrayInputStream, ByteArrayOutputStream} -import java.nio.charset.StandardCharsets -import java.nio.file.{Files, Path} -import scala.jdk.CollectionConverters._ -import scala.util.Using - -class GitVersionControlLocalFileStorageSpec extends AnyFlatSpec { - - private def deleteIfExists(path: Path): Unit = { - if (Files.exists(path)) { - Using.resource(Files.walk(path)) { stream => - stream.iterator().asScala.toSeq.reverse.foreach { p => - // best-effort: JGit can keep Windows handles on .git objects; leftover temp - // files are harmless and get reaped by the OS. - try Files.deleteIfExists(p) - catch { case _: java.io.IOException => () } - } - } - } - } - - // JGit's commit() does not set an author/committer; configure identity on the - // temp repo before any commit call, otherwise commit() throws. - private def setIdentity(repo: Path): Unit = { - Using.resource(Git.open(repo.toFile)) { git => - val config = git.getRepository.getConfig - config.setString("user", null, "name", "texera-test") - config.setString("user", null, "email", "t@t") - config.save() - } - } - - "GitVersionControlLocalFileStorage.deleteRepo" should "delete a repository directory recursively" in { - val repoDir = Files.createTempDirectory("texera-delete-repo-test") - - try { - val nestedDir = Files.createDirectories(repoDir.resolve("nested").resolve("child")) - val rootFile = Files.writeString(repoDir.resolve("root.txt"), "root") - val nestedFile = Files.writeString(nestedDir.resolve("data.txt"), "data") - - assert(Files.exists(repoDir)) - assert(Files.exists(rootFile)) - assert(Files.exists(nestedFile)) - - GitVersionControlLocalFileStorage.deleteRepo(repoDir) - - assert(!Files.exists(repoDir)) - } finally { - deleteIfExists(repoDir) - } - } - - "GitVersionControlLocalFileStorage" should "support a full versioned lifecycle over a temp repo" in { - // Create then delete the temp dir so initRepo exercises its createDirectories branch. - val repoDir = Files.createTempDirectory("texera-vc-lifecycle") - deleteIfExists(repoDir) - assert(!Files.exists(repoDir)) - - try { - val branch = GitVersionControlLocalFileStorage.initRepo(repoDir) - assert(branch != null) - assert(Files.exists(repoDir.resolve(".git"))) - setIdentity(repoDir) - - // Write a top-level file (hello.txt) into the repo and commit it as version "v1". - // A nested path would exercise JGitVersionControl.add's OS-separator pathspec, which - // JGit rejects on Windows; the versioned-storage surface is covered with a root file. - val filePathInRepo = repoDir.resolve("hello.txt") - val content = "hello-versioned-content" - GitVersionControlLocalFileStorage.writeFileToRepo( - repoDir, - filePathInRepo, - new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)) - ) - - val commitHash = GitVersionControlLocalFileStorage.withCreateVersion( - repoDir, - "v1", - new Runnable { override def run(): Unit = () } - ) - assert(commitHash.matches("[0-9a-f]{40}")) - - // Root file nodes of the version include the committed hello.txt. - val rootNodes = GitVersionControlLocalFileStorage - .retrieveRootFileNodesOfVersion(repoDir, commitHash) - .asScala - .toSeq - val relPaths = PhysicalFileNode.getAllFileRelativePaths(rootNodes.toSet.asJava).asScala - assert(relPaths.contains("hello.txt")) - - // Retrieve content via OutputStream. - val out = new ByteArrayOutputStream() - GitVersionControlLocalFileStorage.retrieveFileContentOfVersion( - repoDir, - commitHash, - filePathInRepo, - out - ) - assert(new String(out.toByteArray, StandardCharsets.UTF_8) == content) - - // Retrieve content via InputStream. - Using.resource( - GitVersionControlLocalFileStorage.retrieveFileContentOfVersionAsInputStream( - repoDir, - commitHash, - filePathInRepo - ) - ) { in => - assert(new String(in.readAllBytes(), StandardCharsets.UTF_8) == content) - } - - // Write the versioned file content into a temp file: must be absolute with matching content. - val tempFile = GitVersionControlLocalFileStorage.writeVersionedFileToTempFile( - repoDir, - commitHash, - filePathInRepo - ) - try { - assert(tempFile.isAbsolute) - assert(new String(Files.readAllBytes(tempFile), StandardCharsets.UTF_8) == content) - } finally { - Files.deleteIfExists(tempFile) - } - - // hasUncommittedChanges / discardUncommittedChanges toggle. - assert(!GitVersionControlLocalFileStorage.hasUncommittedChanges(repoDir)) - Files.write(filePathInRepo, "dirty".getBytes(StandardCharsets.UTF_8)) - assert(GitVersionControlLocalFileStorage.hasUncommittedChanges(repoDir)) - GitVersionControlLocalFileStorage.discardUncommittedChanges(repoDir) - assert(!GitVersionControlLocalFileStorage.hasUncommittedChanges(repoDir)) - assert(new String(Files.readAllBytes(filePathInRepo), StandardCharsets.UTF_8) == content) - - // removeFileFromRepo: directory guard then happy-path delete. - val subDir = repoDir.resolve("subdir") - Files.createDirectories(subDir) - val ex = intercept[IllegalArgumentException] { - GitVersionControlLocalFileStorage.removeFileFromRepo(repoDir, subDir) - } - assert(ex.getMessage.contains("directory")) - - GitVersionControlLocalFileStorage.removeFileFromRepo(repoDir, filePathInRepo) - assert(!Files.exists(filePathInRepo)) - } finally { - deleteIfExists(repoDir) - } - } -} diff --git a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/util/dataset/JGitVersionControlSpec.scala b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/util/dataset/JGitVersionControlSpec.scala deleted file mode 100644 index 9a9a619a89..0000000000 --- a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/util/dataset/JGitVersionControlSpec.scala +++ /dev/null @@ -1,556 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. - * - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.texera.amber.core.storage.util.dataset - -import org.eclipse.jgit.api.Git -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers - -import java.io.{ByteArrayOutputStream, IOException} -import java.nio.charset.StandardCharsets -import java.nio.file.{Files, Path} -import scala.jdk.CollectionConverters._ -import scala.util.Using - -class JGitVersionControlSpec extends AnyFlatSpec with Matchers { - - private def deleteIfExists(path: Path): Unit = { - if (Files.exists(path)) { - Using.resource(Files.walk(path)) { stream => - stream.iterator().asScala.toSeq.reverse.foreach { p => - // best-effort: JGit can keep Windows handles on .git objects; leftover temp - // files are harmless and get reaped by the OS. - try Files.deleteIfExists(p) - catch { case _: java.io.IOException => () } - } - } - } - } - - // JGit's commit() does not set an author/committer; configure identity on the - // temp repo before any commit call, otherwise commit() throws. - private def setIdentity(repo: Path): Unit = { - Using.resource(Git.open(repo.toFile)) { git => - val config = git.getRepository.getConfig - config.setString("user", null, "name", "texera-test") - config.setString("user", null, "email", "t@t") - config.save() - } - } - - private def writeFile(path: Path, content: String): Unit = { - Files.createDirectories(path.getParent) - Files.write(path, content.getBytes(StandardCharsets.UTF_8)) - } - - // Stage every working-tree change portably. JGitVersionControl.add relativizes with the - // OS path separator, and JGit's pathspec matcher rejects the Windows "dir\\file" form; the - // "." pattern walks the tree emitting correct forward-slash entries on every platform, so - // it is used to stage nested files as fixture setup. - private def stageAll(repo: Path): Unit = - Using.resource(Git.open(repo.toFile))(_.add().addFilepattern(".").call()) - - "JGitVersionControl.initRepo" should "initialize a repo and return a non-null default branch" in { - val repo = Files.createTempDirectory("texera-jgit-init") - try { - val branch = JGitVersionControl.initRepo(repo) - branch should not be null - Files.exists(repo.resolve(".git")) shouldBe true - } finally { - deleteIfExists(repo) - } - } - - it should "throw IOException when a repository already exists" in { - val repo = Files.createTempDirectory("texera-jgit-init-exists") - try { - JGitVersionControl.initRepo(repo) - val ex = intercept[IOException] { - JGitVersionControl.initRepo(repo) - } - ex.getMessage should include("Repository already exists") - } finally { - deleteIfExists(repo) - } - } - - "JGitVersionControl.commit" should "stage, commit, and return a 40-char hex hash" in { - val repo = Files.createTempDirectory("texera-jgit-commit") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - - val file = repo.resolve("top.txt") - writeFile(file, "hello") - JGitVersionControl.add(repo, file) - - val hash = JGitVersionControl.commit(repo, "initial commit") - hash should fullyMatch regex "[0-9a-f]{40}" - } finally { - deleteIfExists(repo) - } - } - - "JGitVersionControl.getRootFileNodeOfCommit" should "return top-level and nested nodes with size and relative path" in { - val repo = Files.createTempDirectory("texera-jgit-tree") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - - val topFile = repo.resolve("top.txt") - val topContent = "top-content" - writeFile(topFile, topContent) - - val nestedFile = repo.resolve("dir").resolve("nested.txt") - val nestedContent = "nested-file-content" - writeFile(nestedFile, nestedContent) - - JGitVersionControl.add(repo, topFile) - stageAll(repo) // stage the nested file portably (see stageAll) - val hash = JGitVersionControl.commit(repo, "add files") - - val rootNodes = JGitVersionControl.getRootFileNodeOfCommit(repo, hash).asScala.toSeq - - // Root level should contain the top-level file and the "dir" directory node. - val relPaths = rootNodes.map(_.getRelativePath.toString).toSet - relPaths should contain("top.txt") - relPaths should contain("dir") - - val topNode = rootNodes.find(_.getRelativePath.toString == "top.txt").get - topNode.isDirectory shouldBe false - topNode.getSize shouldBe topContent.getBytes(StandardCharsets.UTF_8).length.toLong - - val dirNode = rootNodes.find(_.getRelativePath.toString == "dir").get - dirNode.isDirectory shouldBe true - - val childNode = dirNode.getChildren.asScala.head - childNode.getRelativePath.toString should (be("dir/nested.txt") or be("dir\\nested.txt")) - childNode.isDirectory shouldBe false - childNode.getSize shouldBe nestedContent.getBytes(StandardCharsets.UTF_8).length.toLong - } finally { - deleteIfExists(repo) - } - } - - "JGitVersionControl read methods" should "round-trip file content via InputStream and OutputStream" in { - val repo = Files.createTempDirectory("texera-jgit-read") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - - val file = repo.resolve("data.txt") - val content = "round-trip-content" - writeFile(file, content) - JGitVersionControl.add(repo, file) - val hash = JGitVersionControl.commit(repo, "add data") - - // OutputStream variant - val out = new ByteArrayOutputStream() - JGitVersionControl.readFileContentOfCommitAsOutputStream(repo, hash, file, out) - new String(out.toByteArray, StandardCharsets.UTF_8) shouldBe content - - // InputStream variant - Using.resource(JGitVersionControl.readFileContentOfCommitAsInputStream(repo, hash, file)) { - in => - val bytes = in.readAllBytes() - new String(bytes, StandardCharsets.UTF_8) shouldBe content - } - } finally { - deleteIfExists(repo) - } - } - - "JGitVersionControl.readFileContentOfCommitAsInputStream" should "reject a path outside the repository" in { - val repo = Files.createTempDirectory("texera-jgit-guard-in-out") - val outside = Files.createTempDirectory("texera-jgit-guard-in-outside") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - val file = repo.resolve("data.txt") - writeFile(file, "x") - JGitVersionControl.add(repo, file) - val hash = JGitVersionControl.commit(repo, "c") - - intercept[IllegalArgumentException] { - JGitVersionControl.readFileContentOfCommitAsInputStream( - repo, - hash, - outside.resolve("f.txt") - ) - } - } finally { - deleteIfExists(repo) - deleteIfExists(outside) - } - } - - it should "reject a path that points to a directory" in { - val repo = Files.createTempDirectory("texera-jgit-guard-in-dir") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - val dir = repo.resolve("dir") - val file = dir.resolve("nested.txt") - writeFile(file, "x") - JGitVersionControl.add(repo, file) - val hash = JGitVersionControl.commit(repo, "c") - - intercept[IllegalArgumentException] { - JGitVersionControl.readFileContentOfCommitAsInputStream(repo, hash, dir) - } - } finally { - deleteIfExists(repo) - } - } - - it should "throw IOException for a file not present in the commit" in { - val repo = Files.createTempDirectory("texera-jgit-guard-in-missing") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - val file = repo.resolve("data.txt") - writeFile(file, "x") - JGitVersionControl.add(repo, file) - val hash = JGitVersionControl.commit(repo, "c") - - intercept[IOException] { - JGitVersionControl.readFileContentOfCommitAsInputStream( - repo, - hash, - repo.resolve("missing.txt") - ) - } - } finally { - deleteIfExists(repo) - } - } - - "JGitVersionControl.readFileContentOfCommitAsOutputStream" should "reject a path outside the repository" in { - val repo = Files.createTempDirectory("texera-jgit-guard-out-out") - val outside = Files.createTempDirectory("texera-jgit-guard-out-outside") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - val file = repo.resolve("data.txt") - writeFile(file, "x") - JGitVersionControl.add(repo, file) - val hash = JGitVersionControl.commit(repo, "c") - - intercept[IllegalArgumentException] { - JGitVersionControl.readFileContentOfCommitAsOutputStream( - repo, - hash, - outside.resolve("f.txt"), - new ByteArrayOutputStream() - ) - } - } finally { - deleteIfExists(repo) - deleteIfExists(outside) - } - } - - it should "reject a path that points to a directory" in { - val repo = Files.createTempDirectory("texera-jgit-guard-out-dir") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - val dir = repo.resolve("dir") - val file = dir.resolve("nested.txt") - writeFile(file, "x") - JGitVersionControl.add(repo, file) - val hash = JGitVersionControl.commit(repo, "c") - - intercept[IllegalArgumentException] { - JGitVersionControl.readFileContentOfCommitAsOutputStream( - repo, - hash, - dir, - new ByteArrayOutputStream() - ) - } - } finally { - deleteIfExists(repo) - } - } - - it should "throw IOException for a file not present in the commit" in { - val repo = Files.createTempDirectory("texera-jgit-guard-out-missing") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - val file = repo.resolve("data.txt") - writeFile(file, "x") - JGitVersionControl.add(repo, file) - val hash = JGitVersionControl.commit(repo, "c") - - intercept[IOException] { - JGitVersionControl.readFileContentOfCommitAsOutputStream( - repo, - hash, - repo.resolve("missing.txt"), - new ByteArrayOutputStream() - ) - } - } finally { - deleteIfExists(repo) - } - } - - "JGitVersionControl.rm" should "stage a file deletion so a subsequent commit drops the file" in { - val repo = Files.createTempDirectory("texera-jgit-rm") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - - val file = repo.resolve("data.txt") - writeFile(file, "content") - JGitVersionControl.add(repo, file) - JGitVersionControl.commit(repo, "add") - - JGitVersionControl.rm(repo, file) - val hash = JGitVersionControl.commit(repo, "remove") - - val rootNodes = JGitVersionControl.getRootFileNodeOfCommit(repo, hash).asScala.toSeq - rootNodes.map(_.getRelativePath.toString) should not contain "data.txt" - } finally { - deleteIfExists(repo) - } - } - - "JGitVersionControl.hasUncommittedChanges" should "return false on a clean repo and true after a change" in { - val repo = Files.createTempDirectory("texera-jgit-status") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - - val file = repo.resolve("data.txt") - writeFile(file, "content") - JGitVersionControl.add(repo, file) - JGitVersionControl.commit(repo, "add") - - JGitVersionControl.hasUncommittedChanges(repo) shouldBe false - - writeFile(repo.resolve("new.txt"), "new") - JGitVersionControl.hasUncommittedChanges(repo) shouldBe true - } finally { - deleteIfExists(repo) - } - } - - "JGitVersionControl.discardUncommittedChanges" should "revert the working directory to the last commit" in { - val repo = Files.createTempDirectory("texera-jgit-discard") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - - val file = repo.resolve("data.txt") - writeFile(file, "original") - JGitVersionControl.add(repo, file) - JGitVersionControl.commit(repo, "add") - - // Modify tracked file and add an untracked file - writeFile(file, "modified") - writeFile(repo.resolve("untracked.txt"), "junk") - JGitVersionControl.hasUncommittedChanges(repo) shouldBe true - - JGitVersionControl.discardUncommittedChanges(repo) - - JGitVersionControl.hasUncommittedChanges(repo) shouldBe false - new String(Files.readAllBytes(file), StandardCharsets.UTF_8) shouldBe "original" - Files.exists(repo.resolve("untracked.txt")) shouldBe false - } finally { - deleteIfExists(repo) - } - } - - it should "return the branch name that the new repository actually has checked out" in { - val repo = Files.createTempDirectory("texera-jgit-branch") - try { - val branch = JGitVersionControl.initRepo(repo) - // initRepo strips the "refs/heads/" prefix off the HEAD symref; the result must - // be the very branch JGit reports for the fresh repository. - val actual = Using.resource(Git.open(repo.toFile))(_.getRepository.getBranch) - branch shouldBe actual - branch should not startWith "refs/heads/" - } finally { - deleteIfExists(repo) - } - } - - "JGitVersionControl.getRootFileNodeOfCommit" should "return an empty set for a commit with no files" in { - val repo = Files.createTempDirectory("texera-jgit-empty-tree") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - // an initial commit with nothing staged has an empty tree, so the tree walk - // yields no entries at all - val hash = JGitVersionControl.commit(repo, "empty commit") - - JGitVersionControl.getRootFileNodeOfCommit(repo, hash).asScala shouldBe empty - } finally { - deleteIfExists(repo) - } - } - - it should "link nested directories at depth two down to the leaf file" in { - val repo = Files.createTempDirectory("texera-jgit-deep-tree") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - - val leafContent = "deep-content" - writeFile(repo.resolve("a").resolve("b").resolve("leaf.txt"), leafContent) - stageAll(repo) - val hash = JGitVersionControl.commit(repo, "add nested dirs") - - val rootNodes = JGitVersionControl.getRootFileNodeOfCommit(repo, hash).asScala.toSeq - // only the top-level directory "a" is a root node; everything else hangs off it - rootNodes.map(_.getRelativePath.toString) shouldBe Seq("a") - - val aNode = rootNodes.head - aNode.isDirectory shouldBe true - aNode.getChildren.size shouldBe 1 - - val bNode = aNode.getChildren.asScala.head - bNode.getRelativePath.toString should (be("a/b") or be("a\\b")) - bNode.isDirectory shouldBe true - bNode.getChildren.size shouldBe 1 - - val leafNode = bNode.getChildren.asScala.head - leafNode.getRelativePath.toString should (be("a/b/leaf.txt") or be("a\\b\\leaf.txt")) - leafNode.isDirectory shouldBe false - leafNode.getSize shouldBe leafContent.getBytes(StandardCharsets.UTF_8).length.toLong - } finally { - deleteIfExists(repo) - } - } - - "JGitVersionControl commit-hash resolution" should "accept a symbolic ref such as HEAD" in { - val repo = Files.createTempDirectory("texera-jgit-symref") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - val file = repo.resolve("data.txt") - writeFile(file, "head-content") - JGitVersionControl.add(repo, file) - JGitVersionControl.commit(repo, "add") - - // the commitHash argument is resolved by JGit, so any revision expression works - val out = new ByteArrayOutputStream() - JGitVersionControl.readFileContentOfCommitAsOutputStream(repo, "HEAD", file, out) - new String(out.toByteArray, StandardCharsets.UTF_8) shouldBe "head-content" - - Using.resource(JGitVersionControl.readFileContentOfCommitAsInputStream(repo, "HEAD", file)) { - in => new String(in.readAllBytes(), StandardCharsets.UTF_8) shouldBe "head-content" - } - } finally { - deleteIfExists(repo) - } - } - - it should "read the version stored in each commit after a tracked file is modified" in { - val repo = Files.createTempDirectory("texera-jgit-history") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - - val file = repo.resolve("data.txt") - writeFile(file, "v1") - JGitVersionControl.add(repo, file) - val firstHash = JGitVersionControl.commit(repo, "v1") - - // re-staging a tracked file picks up the modification - writeFile(file, "v2-longer") - JGitVersionControl.add(repo, file) - val secondHash = JGitVersionControl.commit(repo, "v2") - - secondHash should not be firstHash - - def contentAt(hash: String): String = { - val out = new ByteArrayOutputStream() - JGitVersionControl.readFileContentOfCommitAsOutputStream(repo, hash, file, out) - new String(out.toByteArray, StandardCharsets.UTF_8) - } - contentAt(firstHash) shouldBe "v1" - contentAt(secondHash) shouldBe "v2-longer" - - // the node size reported for the latest commit follows the new content - val node = JGitVersionControl - .getRootFileNodeOfCommit(repo, secondHash) - .asScala - .find(_.getRelativePath.toString == "data.txt") - .get - node.getSize shouldBe "v2-longer".length.toLong - } finally { - deleteIfExists(repo) - } - } - - "JGitVersionControl.readFileContentOfCommitAsOutputStream" should "copy binary content byte-for-byte" in { - val repo = Files.createTempDirectory("texera-jgit-binary") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - - val bytes = Array[Byte](0, 1, 127, -128, -1, 13, 10, 0) - val file = repo.resolve("blob.bin") - Files.write(file, bytes) - JGitVersionControl.add(repo, file) - val hash = JGitVersionControl.commit(repo, "add binary") - - val out = new ByteArrayOutputStream() - JGitVersionControl.readFileContentOfCommitAsOutputStream(repo, hash, file, out) - out.toByteArray shouldBe bytes - - Using.resource(JGitVersionControl.readFileContentOfCommitAsInputStream(repo, hash, file)) { - in => in.readAllBytes() shouldBe bytes - } - } finally { - deleteIfExists(repo) - } - } - - "JGitVersionControl.hasUncommittedChanges" should "report a staged deletion as uncommitted" in { - val repo = Files.createTempDirectory("texera-jgit-staged-rm") - try { - JGitVersionControl.initRepo(repo) - setIdentity(repo) - - val file = repo.resolve("data.txt") - writeFile(file, "content") - JGitVersionControl.add(repo, file) - JGitVersionControl.commit(repo, "add") - JGitVersionControl.hasUncommittedChanges(repo) shouldBe false - - // rm only stages the removal; the index now differs from HEAD - JGitVersionControl.rm(repo, file) - JGitVersionControl.hasUncommittedChanges(repo) shouldBe true - Files.exists(file) shouldBe false - - JGitVersionControl.commit(repo, "remove") - JGitVersionControl.hasUncommittedChanges(repo) shouldBe false - } finally { - deleteIfExists(repo) - } - } -} diff --git a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/util/dataset/PhysicalFileNodeSpec.scala b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/util/dataset/PhysicalFileNodeSpec.scala deleted file mode 100644 index d12431ae40..0000000000 --- a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/util/dataset/PhysicalFileNodeSpec.scala +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.texera.amber.core.storage.util.dataset - -import org.scalatest.flatspec.AnyFlatSpec - -import java.nio.file.{Files, Path} -import scala.jdk.CollectionConverters._ -import scala.util.Using - -class PhysicalFileNodeSpec extends AnyFlatSpec { - - private def withRepo(body: Path => Unit): Unit = { - val repo = Files.createTempDirectory("pfn-") - try body(repo) - finally { - // Files.walk returns a Stream holding a directory handle; close it so temp - // cleanup does not intermittently fail (notably on Windows) on a leaked handle. - Using.resource(Files.walk(repo)) { stream => - stream - .sorted(java.util.Comparator.reverseOrder[Path]()) - .forEach(p => Files.deleteIfExists(p)) - } - } - } - - "PhysicalFileNode" should "expose its paths, size, and empty children" in withRepo { repo => - val file = Files.createFile(repo.resolve("a.txt")) - val node = new PhysicalFileNode(repo, file, 42L) - assert(node.getAbsolutePath == file) - assert(node.getRelativePath == repo.relativize(file)) - assert(node.getRelativePath.toString == "a.txt") - assert(node.getSize == 42L) - assert(node.getChildren.isEmpty) - } - - it should "report isFile / isDirectory from the filesystem" in withRepo { repo => - val file = Files.createFile(repo.resolve("a.txt")) - val dir = Files.createDirectory(repo.resolve("sub")) - val fileNode = new PhysicalFileNode(repo, file, 0L) - val dirNode = new PhysicalFileNode(repo, dir, 0L) - assert(fileNode.isFile && !fileNode.isDirectory) - assert(dirNode.isDirectory && !dirNode.isFile) - val missing = new PhysicalFileNode(repo, repo.resolve("nope"), 0L) - assert(!missing.isFile && !missing.isDirectory) - } - - it should "accept a direct child and reject a non-direct one" in withRepo { repo => - val sub = Files.createDirectory(repo.resolve("sub")) - val parent = new PhysicalFileNode(repo, sub, 0L) - val child = new PhysicalFileNode(repo, sub.resolve("child.txt"), 0L) - parent.addChildNode(child) - assert(parent.getChildren.size == 1) - assert(parent.getChildren.contains(child)) - - val parentOfRepo = new PhysicalFileNode(repo, repo, 0L) - val deep = new PhysicalFileNode(repo, sub.resolve("deep.txt"), 0L) - val ex = intercept[IllegalArgumentException](parentOfRepo.addChildNode(deep)) - assert(ex.getMessage == "Child node is not a direct subpath of the parent node") - } - - it should "define equals and hashCode over the absolute path and children only" in withRepo { - repo => - val file = Files.createFile(repo.resolve("a.txt")) - val other = Files.createFile(repo.resolve("b.txt")) - val node = new PhysicalFileNode(repo, file, 1L) - assert(node.equals(node)) // identity - assert(!node.equals(null)) - assert(!node.equals("not a node")) - // size is excluded from equals/hashCode - val sameByPath = new PhysicalFileNode(repo, file, 999L) - assert(node == sameByPath) - assert(node.hashCode == sameByPath.hashCode) - assert(node != new PhysicalFileNode(repo, other, 1L)) - } - - "PhysicalFileNode.getAllFileRelativePaths" should "collect files recursively through directories" in withRepo { - repo => - val sub = Files.createDirectory(repo.resolve("sub")) - val topFile = Files.createFile(repo.resolve("top.txt")) - val innerFile = Files.createFile(sub.resolve("inner.txt")) - val topNode = new PhysicalFileNode(repo, topFile, 0L) - val dirNode = new PhysicalFileNode(repo, sub, 0L) - dirNode.addChildNode(new PhysicalFileNode(repo, innerFile, 0L)) - val nodes = new java.util.HashSet[PhysicalFileNode]() - nodes.add(topNode) - nodes.add(dirNode) - val result = PhysicalFileNode.getAllFileRelativePaths(nodes).asScala.toSet - assert( - result == Set(repo.relativize(topFile).toString, repo.relativize(innerFile).toString) - ) - } -}
