Search in sources :

Example 76 with RevCommit

use of org.eclipse.jgit.revwalk.RevCommit in project kie-wb-common by kiegroup.

the class KieDefaultMavenCompilerTest method buildWithAllDecoratorsTest.

// 
@Test
public void buildWithAllDecoratorsTest() throws Exception {
    String alternateSettingsAbsPath = new File("src/test/settings.xml").getAbsolutePath();
    AFCompiler compiler = KieMavenCompilerFactory.getCompiler(KieDecorator.JGIT_BEFORE_AND_LOG_AFTER);
    String MASTER_BRANCH = "master";
    // Setup origin in memory
    final URI originRepo = URI.create("git://repo");
    final JGitFileSystem origin = (JGitFileSystem) ioService.newFileSystem(originRepo, new HashMap<String, Object>() {

        {
            put("init", Boolean.TRUE);
            put("internal", Boolean.TRUE);
            put("listMode", "ALL");
        }
    });
    assertNotNull(origin);
    ioService.startBatch(origin);
    ioService.write(origin.getPath("/dummy/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("target/test-classes/kjar-2-single-resources/pom.xml").toPath())));
    ioService.write(origin.getPath("/dummy/src/main/java/org/kie/maven/plugin/test/Person.java"), new String(java.nio.file.Files.readAllBytes(new File("target/test-classes/kjar-2-single-resources/src/main/java/org/kie/maven/plugin/test/Person.java").toPath())));
    ioService.write(origin.getPath("/dummy/src/main/resources/AllResourceTypes/simple-rules.drl"), new String(java.nio.file.Files.readAllBytes(new File("target/test-classes/kjar-2-single-resources/src/main/resources/AllResourceTypes/simple-rules.drl").toPath())));
    ioService.write(origin.getPath("/dummy/src/main/resources/META-INF/kmodule.xml"), new String(java.nio.file.Files.readAllBytes(new File("target/test-classes/kjar-2-single-resources/src/main/resources/META-INF/kmodule.xml").toPath())));
    ioService.endBatch();
    RevCommit lastCommit = origin.getGit().resolveRevCommit(origin.getGit().getRef(MASTER_BRANCH).getObjectId());
    assertNotNull(lastCommit);
    // clone into a regularfs
    Path tmpRootCloned = Files.createTempDirectory("cloned");
    Path tmpCloned = Files.createDirectories(Paths.get(tmpRootCloned.toString(), ".clone.git"));
    // @TODO find a way to retrieve the address git://... of the repo
    final Git cloned = Git.cloneRepository().setURI("git://localhost:9418/repo").setBare(false).setDirectory(tmpCloned.toFile()).call();
    assertNotNull(cloned);
    // @TODO refactor and use only one between the URI or Git
    // @TODO find a way to resolve the problem of the prjname inside .git folder
    WorkspaceCompilationInfo info = new WorkspaceCompilationInfo(Paths.get(tmpCloned + "/dummy"));
    CompilationRequest req = new DefaultCompilationRequest(mavenRepo.toAbsolutePath().toString(), info, new String[] { MavenCLIArgs.COMPILE, MavenCLIArgs.ALTERNATE_USER_SETTINGS + alternateSettingsAbsPath }, new HashMap<>(), Boolean.TRUE);
    CompilationResponse res = compiler.compileSync(req);
    if (res.getMavenOutput().isPresent() && !res.isSuccessful()) {
        TestUtil.writeMavenOutputIntoTargetFolder(res.getMavenOutput().get(), "KieDefaultMavenCompilerTest.buildWithAllDecoratorsTest");
    }
    assertTrue(res.getMavenOutput().isPresent());
    assertTrue(res.isSuccessful());
    lastCommit = origin.getGit().resolveRevCommit(origin.getGit().getRef(MASTER_BRANCH).getObjectId());
    assertNotNull(lastCommit);
    // change one file and commit on the origin repo
    ioService.write(origin.getPath("/dummy/src/main/java/org/kie/maven/plugin/test/Person.java"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/Person.java").toPath())));
    RevCommit commitBefore = origin.getGit().resolveRevCommit(origin.getGit().getRef(MASTER_BRANCH).getObjectId());
    assertNotNull(commitBefore);
    assertFalse(lastCommit.getId().toString().equals(commitBefore.getId().toString()));
    // recompile
    res = compiler.compileSync(req);
    if (res.getMavenOutput().isPresent() && !res.isSuccessful()) {
        TestUtil.writeMavenOutputIntoTargetFolder(res.getMavenOutput().get(), "KieDefaultMavenCompilerTest.buildWithAllDecoratorsTest");
    }
    assertTrue(res.isSuccessful());
    assertTrue(res.getMavenOutput().isPresent());
    TestUtil.rm(tmpRootCloned.toFile());
}
Also used : Path(org.uberfire.java.nio.file.Path) HashMap(java.util.HashMap) CompilationResponse(org.kie.workbench.common.services.backend.compiler.CompilationResponse) URI(java.net.URI) Git(org.eclipse.jgit.api.Git) WorkspaceCompilationInfo(org.kie.workbench.common.services.backend.compiler.nio.WorkspaceCompilationInfo) DefaultCompilationRequest(org.kie.workbench.common.services.backend.compiler.nio.impl.DefaultCompilationRequest) File(java.io.File) AFCompiler(org.kie.workbench.common.services.backend.compiler.nio.AFCompiler) JGitFileSystem(org.uberfire.java.nio.fs.jgit.JGitFileSystem) CompilationRequest(org.kie.workbench.common.services.backend.compiler.nio.CompilationRequest) DefaultCompilationRequest(org.kie.workbench.common.services.backend.compiler.nio.impl.DefaultCompilationRequest) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Test(org.junit.Test)

Example 77 with RevCommit

use of org.eclipse.jgit.revwalk.RevCommit in project fabric8 by jboss-fuse.

the class GitHelpers method getContentOfObject.

/**
 * Fetches the content of a file from Git repository without checking out the branch
 * @param git
 * @param branch short branch name
 * @param fileName name of the file to fetch
 * @param onlyFromTheCommit if <code>true</code>, return content only if the file is different than in parent commit(s)
 * @return content of file or <code>null</code> if no such file exists
 */
public static byte[] getContentOfObject(Git git, String branch, String fileName, boolean onlyFromTheCommit) throws IOException {
    Ref ref = git.getRepository().getRef("refs/heads/" + branch);
    if (ref == null) {
        return null;
    }
    RevCommit rw = new RevWalk(git.getRepository()).parseCommit(ref.getObjectId());
    ObjectId objectId = objectIdOfResource(git, rw, fileName);
    if (objectId != null) {
        if (!onlyFromTheCommit) {
            ObjectLoader loader = git.getRepository().open(objectId);
            return loader.getBytes();
        } else {
            // if the objectId is the same as in *all* parent commits, than this resource is actually
            // not created in the branch itself - it comes from parent branch (version)
            RevCommit[] parents = rw.getParents();
            boolean change = false;
            if (parents != null && parents.length > 0) {
                for (RevCommit parent : parents) {
                    RevCommit prc = new RevWalk(git.getRepository()).parseCommit(parent.getId());
                    ObjectId parentObjectId = objectIdOfResource(git, prc, fileName);
                    if (parentObjectId == null || !parentObjectId.equals(objectId)) {
                        change = true;
                        break;
                    }
                }
            } else {
                change = true;
            }
            return change ? git.getRepository().open(objectId).getBytes() : null;
        }
    } else {
        return null;
    }
}
Also used : Ref(org.eclipse.jgit.lib.Ref) ObjectId(org.eclipse.jgit.lib.ObjectId) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) RevWalk(org.eclipse.jgit.revwalk.RevWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 78 with RevCommit

use of org.eclipse.jgit.revwalk.RevCommit in project fabric8 by jboss-fuse.

the class GitIT method showContentOfFileFromNotCurrentlyCheckedOutBranch.

@Test
public void showContentOfFileFromNotCurrentlyCheckedOutBranch() throws Exception {
    String content = FileUtils.readFileToString(new File(dir, "version.attributes"));
    assertThat(content, equalTo("1.0"));
    RevCommit rw = new RevWalk(git.getRepository()).parseCommit(git.getRepository().getRef("refs/heads/master").getObjectId());
    TreeWalk tw = new TreeWalk(git.getRepository());
    tw.addTree(rw.getTree());
    tw.setRecursive(false);
    tw.setFilter(PathFilter.create("version.attributes"));
    assertThat(tw.next(), equalTo(true));
    ObjectId objectId = tw.getObjectId(0);
    ObjectLoader loader = git.getRepository().open(objectId);
    assertThat(new String(loader.getBytes()), equalTo("master"));
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) RevWalk(org.eclipse.jgit.revwalk.RevWalk) File(java.io.File) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Test(org.junit.Test)

Example 79 with RevCommit

use of org.eclipse.jgit.revwalk.RevCommit in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceImpl method trackBaselinesForChildContainers.

/**
 * Tracks all baselines for child containers that weren't tracked already. These are looked up inside
 * <code>system/org/apache/karaf/admin/org.apache.karaf.admin.core/**</code>
 * @param fork
 */
private void trackBaselinesForChildContainers(Git fork) throws IOException, GitAPIException {
    if (fork.getRepository().getRef("refs/heads/" + gitPatchRepository.getChildBranchName()) == null) {
        // checkout patches-child branch - it'll track baselines for fabric:container-create-child containers
        String startPoint = "patch-management^{commit}";
        if (fork.getRepository().getRef("refs/remotes/origin/" + gitPatchRepository.getChildBranchName()) != null) {
            startPoint = "refs/remotes/origin/" + gitPatchRepository.getChildBranchName();
        }
        gitPatchRepository.checkout(fork).setName(gitPatchRepository.getChildBranchName()).setStartPoint(startPoint).setCreateBranch(true).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();
    } else {
        gitPatchRepository.checkout(fork).setName(gitPatchRepository.getChildBranchName()).call();
    }
    File systemRepo = getSystemRepository(karafHome, systemContext);
    File[] versionDirs = new File(systemRepo, "org/apache/karaf/admin/org.apache.karaf.admin.core").listFiles();
    Set<Version> versions = new TreeSet<>();
    if (versionDirs != null) {
        for (File version : versionDirs) {
            if (version.isDirectory()) {
                versions.add(Utils.getOsgiVersion(version.getName()));
            }
        }
    }
    for (Version v : versions) {
        String karafVersion = v.toString();
        String tagName = String.format(EnvType.FABRIC_CHILD.getBaselineTagFormat(), karafVersion);
        if (gitPatchRepository.containsTag(fork, tagName)) {
            continue;
        }
        File baselineDistribution = null;
        String location = String.format(systemRepo.getCanonicalPath() + "/org/apache/karaf/admin/org.apache.karaf.admin.core/%1$s/org.apache.karaf.admin.core-%1$s.jar", karafVersion);
        if (new File(location).isFile()) {
            baselineDistribution = new File(location);
            Activator.log(LogService.LOG_INFO, "Found child baseline distribution: " + baselineDistribution.getCanonicalPath());
        }
        if (baselineDistribution != null) {
            try {
                unzipKarafAdminJar(baselineDistribution, fork.getRepository().getWorkTree());
                fork.add().addFilepattern(".").call();
                RevCommit commit = gitPatchRepository.prepareCommit(fork, String.format(MARKER_BASELINE_CHILD_COMMIT_PATTERN, karafVersion)).call();
                // and we'll tag the child baseline
                fork.tag().setName(tagName).setObjectId(commit).call();
            } catch (Exception e) {
                Activator.log(LogService.LOG_ERROR, null, e.getMessage(), e, true);
            }
        }
    }
    gitPatchRepository.push(fork, gitPatchRepository.getChildBranchName());
}
Also used : Version(org.osgi.framework.Version) Artifact.isSameButVersion(io.fabric8.patch.management.Artifact.isSameButVersion) TreeSet(java.util.TreeSet) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) PatchException(io.fabric8.patch.management.PatchException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 80 with RevCommit

use of org.eclipse.jgit.revwalk.RevCommit in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceImpl method trackPatch.

/**
 * <p>This method turns static information about a patch into managed patch - i.e., patch added to git
 * repository.</p>
 *
 * <p>Such patch has its own branch ready to be merged (when patch is installed). Before installation we can verify
 * the patch,
 * examine the content, check the differences, conflicts and perform simulation (merge to temporary branch created
 * from main patch branch)</p>
 *
 * <p>The strategy is as follows:<ul>
 *     <li><em>main patch branch</em> in git repository tracks all changes (from baselines, patch-management
 *     system, patches and user changes)</li>
 *     <li>Initially there are 3 commits: baseline, patch-management bundle installation in etc/startup.properties,
 *     initial user changes</li>
 *     <li>We always <strong>tag the baseline commit</strong></li>
 *     <li>User changes may be applied each time Framework is restarted</li>
 *     <li>When we add a patch, we create <em>named branch</em> from the <strong>latest baseline</strong></li>
 *     <li>When we install a patch, we <strong>merge</strong> the patch branch with the <em>main patch branch</em>
 *     (that may contain additional user changes)</li>
 *     <li>When patch ZIP contains new baseline distribution, after merging patch branch, we tag the merge commit
 *     in <em>main patch branch</em> branch as new baseline</li>
 *     <li>Branches for new patches will then be created from new baseline commit</li>
 * </ul></p>
 * @param patchData
 * @return
 */
@Override
public Patch trackPatch(PatchData patchData) throws PatchException {
    try {
        awaitInitialization();
    } catch (InterruptedException e) {
        throw new PatchException("Patch management system is not ready yet");
    }
    Git fork = null;
    try {
        Git mainRepository = gitPatchRepository.findOrCreateMainGitRepository();
        // prepare single fork for all the below operations
        fork = gitPatchRepository.cloneRepository(mainRepository, true);
        // 1. find current baseline
        RevTag latestBaseline = gitPatchRepository.findCurrentBaseline(fork);
        if (latestBaseline == null) {
            throw new PatchException("Can't find baseline distribution tracked in patch management. Is patch management initialized?");
        }
        // the commit from the patch should be available from main patch branch
        RevCommit commit = new RevWalk(fork.getRepository()).parseCommit(latestBaseline.getObject());
        // create dedicated branch for this patch. We'll immediately add patch content there so we can examine the
        // changes from the latest baseline
        gitPatchRepository.checkout(fork).setCreateBranch(true).setName("patch-" + patchData.getId()).setStartPoint(commit).call();
        // copy patch resources (but not maven artifacts from system/ or repository/) to working copy
        if (patchData.getPatchDirectory() != null) {
            boolean removeTargetDir = patchData.isRollupPatch();
            copyManagedDirectories(patchData.getPatchDirectory(), fork.getRepository().getWorkTree(), removeTargetDir, false, false);
        }
        // add the changes
        fork.add().addFilepattern(".").call();
        // remove the deletes (without touching specially-managed etc/overrides.properties)
        for (String missing : fork.status().call().getMissing()) {
            if (!"etc/overrides.properties".equals(missing)) {
                fork.rm().addFilepattern(missing).call();
            }
        }
        // record information about other "patches" included in added patch (e.g., Fuse patch
        // may contain patches to admin:create based containers in standalone mode)
        StringWriter sw = new StringWriter();
        sw.append("# tags for patches included in \"").append(patchData.getId()).append("\"\n");
        for (String bundle : patchData.getBundles()) {
            // containers that want to patch:install patches added in root containers
            if (bundle.contains("mvn:org.apache.karaf.admin/org.apache.karaf.admin.core/")) {
                Artifact a = Utils.mvnurlToArtifact(bundle, true);
                if (a != null) {
                    sw.append(String.format(EnvType.STANDALONE_CHILD.getBaselineTagFormat(), a.getVersion())).append("\n");
                }
                break;
            }
        }
        FileUtils.write(new File(fork.getRepository().getWorkTree(), "patch-info.txt"), sw.toString());
        fork.add().addFilepattern(".").call();
        // commit the changes (patch vs. baseline) to patch branch
        gitPatchRepository.prepareCommit(fork, String.format("[PATCH] Tracking patch %s", patchData.getId())).call();
        // push the patch branch
        gitPatchRepository.push(fork, "patch-" + patchData.getId());
        // track other kinds of baselines found in the patch
        if (env.isFabric()) {
            trackBaselinesForRootContainer(fork);
            trackBaselinesForChildContainers(fork);
            trackBaselinesForSSHContainers(fork);
        } else {
            // for admin:create child containers
            trackBaselinesForChildContainers(fork);
        }
        return new Patch(patchData, gitPatchRepository.getManagedPatch(patchData.getId()));
    } catch (IOException | GitAPIException e) {
        throw new PatchException(e.getMessage(), e);
    } finally {
        if (fork != null) {
            gitPatchRepository.closeRepository(fork, true);
        }
    }
}
Also used : RevTag(org.eclipse.jgit.revwalk.RevTag) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Artifact(io.fabric8.patch.management.Artifact) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.eclipse.jgit.api.Git) StringWriter(java.io.StringWriter) PatchException(io.fabric8.patch.management.PatchException) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) ManagedPatch(io.fabric8.patch.management.ManagedPatch) Patch(io.fabric8.patch.management.Patch) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Aggregations

RevCommit (org.eclipse.jgit.revwalk.RevCommit)1302 Test (org.junit.Test)650 RevWalk (org.eclipse.jgit.revwalk.RevWalk)333 ObjectId (org.eclipse.jgit.lib.ObjectId)295 Repository (org.eclipse.jgit.lib.Repository)273 IOException (java.io.IOException)222 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)190 Ref (org.eclipse.jgit.lib.Ref)174 File (java.io.File)134 ArrayList (java.util.ArrayList)134 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)133 Git (org.eclipse.jgit.api.Git)133 PersonIdent (org.eclipse.jgit.lib.PersonIdent)105 Change (com.google.gerrit.entities.Change)87 TestRepository (org.eclipse.jgit.junit.TestRepository)72 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)70 ObjectReader (org.eclipse.jgit.lib.ObjectReader)64 ChangeInfo (com.google.gerrit.extensions.common.ChangeInfo)61 List (java.util.List)61 HashMap (java.util.HashMap)57