Example usage for org.eclipse.jgit.api Git Git

List of usage examples for org.eclipse.jgit.api Git Git

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git Git.

Prototype

public Git(Repository repo) 

Source Link

Document

Construct a new org.eclipse.jgit.api.Git object which can interact with the specified git repository.

Usage

From source file:org.alex73.osm.monitors.export.GitClient.java

License:Open Source License

public synchronized void commit(String user, String email, String commitMessage, boolean amend)
        throws Exception {
    System.out.println(new Date() + " Commit: " + commitMessage);
    new Git(repository).commit().setAuthor(user, email).setMessage(commitMessage).setAmend(amend).call();
}

From source file:org.alex73.osm.monitors.export.GitClient.java

License:Open Source License

public synchronized boolean hasCommit(String messagePart) throws Exception {
    for (RevCommit commit : new Git(repository).log().call()) {
        if (commit.getShortMessage().contains(messagePart)) {
            return true;
        }/*  w  w w .j  ava  2s. co  m*/
    }
    return false;
}

From source file:org.alex73.osm.monitors.export.GitClient.java

License:Open Source License

public synchronized RevCommit getPrevCommit() throws Exception {
    for (RevCommit commit : new Git(repository).log().call()) {
        return commit;
    }//from ww  w.  j  av a 2  s.  co m
    return null;
}

From source file:org.alex73.osm.monitors.export.GitClient.java

License:Open Source License

public synchronized void reset() throws Exception {
    new Git(repository).reset().setMode(ResetType.HARD).call();
}

From source file:org.apache.nifi.registry.provider.flow.git.GitFlowMetaData.java

License:Apache License

@SuppressWarnings("unchecked")
public void loadGitRepository(File gitProjectRootDir) throws IOException, GitAPIException {
    gitRepo = openRepository(gitProjectRootDir);

    try (final Git git = new Git(gitRepo)) {

        // Check if remote exists.
        if (!isEmpty(remoteToPush)) {
            final List<RemoteConfig> remotes = git.remoteList().call();
            final boolean isRemoteExist = remotes.stream()
                    .anyMatch(remote -> remote.getName().equals(remoteToPush));
            if (!isRemoteExist) {
                final List<String> remoteNames = remotes.stream().map(RemoteConfig::getName)
                        .collect(Collectors.toList());
                throw new IllegalArgumentException(
                        format("The configured remote '%s' to push does not exist. Available remotes are %s",
                                remoteToPush, remoteNames));
            }//w  w w .j a  v a2  s  .  com
        }

        boolean isLatestCommit = true;
        try {
            for (RevCommit commit : git.log().call()) {
                final String shortCommitId = commit.getId().abbreviate(7).name();
                logger.debug("Processing a commit: {}", shortCommitId);
                final RevTree tree = commit.getTree();

                try (final TreeWalk treeWalk = new TreeWalk(gitRepo)) {
                    treeWalk.addTree(tree);

                    // Path -> ObjectId
                    final Map<String, ObjectId> bucketObjectIds = new HashMap<>();
                    final Map<String, ObjectId> flowSnapshotObjectIds = new HashMap<>();
                    while (treeWalk.next()) {
                        if (treeWalk.isSubtree()) {
                            treeWalk.enterSubtree();
                        } else {
                            final String pathString = treeWalk.getPathString();
                            // TODO: what is this nth?? When does it get grater than 0? Tree count seems to be always 1..
                            if (pathString.endsWith("/" + BUCKET_FILENAME)) {
                                bucketObjectIds.put(pathString, treeWalk.getObjectId(0));
                            } else if (pathString.endsWith(GitFlowPersistenceProvider.SNAPSHOT_EXTENSION)) {
                                flowSnapshotObjectIds.put(pathString, treeWalk.getObjectId(0));
                            }
                        }
                    }

                    if (bucketObjectIds.isEmpty()) {
                        // No bucket.yml means at this point, all flows are deleted. No need to scan older commits because those are already deleted.
                        logger.debug("Tree at commit {} does not contain any " + BUCKET_FILENAME
                                + ". Stop loading commits here.", shortCommitId);
                        return;
                    }

                    loadBuckets(gitRepo, commit, isLatestCommit, bucketObjectIds, flowSnapshotObjectIds);
                    isLatestCommit = false;
                }
            }
        } catch (NoHeadException e) {
            logger.debug("'{}' does not have any commit yet. Starting with empty buckets.", gitProjectRootDir);
        }

    }
}

From source file:org.apache.nifi.registry.provider.flow.git.GitFlowMetaData.java

License:Apache License

void startPushThread() {
    // If successfully loaded, start pushing thread if necessary.
    if (isEmpty(remoteToPush)) {
        return;//w w w . j  a  v  a 2  s  .  co  m
    }

    final ThreadFactory threadFactory = new BasicThreadFactory.Builder().daemon(true)
            .namingPattern(getClass().getSimpleName() + " Push thread").build();

    // Use scheduled fixed delay to control the minimum interval between push activities.
    // The necessity of executing push is controlled by offering messages to the pushQueue.
    // If multiple commits are made within this time window, those are pushed by a single push execution.
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(threadFactory);
    executorService.scheduleWithFixedDelay(() -> {

        final Long offeredTimestamp;
        try {
            offeredTimestamp = pushQueue.take();
        } catch (InterruptedException e) {
            logger.warn("Waiting for push request has been interrupted due to {}", e.getMessage(), e);
            return;
        }

        logger.debug("Took a push request sent at {} to {}...", offeredTimestamp, remoteToPush);
        final PushCommand pushCommand = new Git(gitRepo).push().setRemote(remoteToPush);
        if (credentialsProvider != null) {
            pushCommand.setCredentialsProvider(credentialsProvider);
        }

        try {
            final Iterable<PushResult> pushResults = pushCommand.call();
            for (PushResult pushResult : pushResults) {
                logger.debug(pushResult.getMessages());
            }
        } catch (GitAPIException e) {
            logger.error(format("Failed to push commits to %s due to %s", remoteToPush, e), e);
        }

    }, 10, 10, TimeUnit.SECONDS);
}

From source file:org.apache.nifi.registry.provider.flow.git.GitFlowMetaData.java

License:Apache License

boolean isGitDirectoryClean() throws GitAPIException {
    final Status status = new Git(gitRepo).status().call();
    return status.isClean() && !status.hasUncommittedChanges();
}

From source file:org.apache.nifi.registry.provider.flow.git.GitFlowMetaData.java

License:Apache License

/**
 * Create a Git commit./* w  w  w .  jav a  2s .  c o m*/
 * @param author The name of a NiFi Registry user who created the snapshot. It will be added to the commit message.
 * @param message Commit message.
 * @param bucket A bucket to commit.
 * @param flowPointer A flow pointer for the flow snapshot which is updated.
 *                    After a commit is created, new commit rev id and flow snapshot file object id are set to this pointer.
 *                    It can be null if none of flow content is modified.
 */
void commit(String author, String message, Bucket bucket, Flow.FlowPointer flowPointer)
        throws GitAPIException, IOException {
    try (final Git git = new Git(gitRepo)) {
        // Execute add command for newly added files (if any).
        git.add().addFilepattern(".").call();

        // Execute add command again for deleted files (if any).
        git.add().addFilepattern(".").setUpdate(true).call();

        final String commitMessage = isEmpty(author) ? message
                : format("%s\n\nBy NiFi Registry user: %s", message, author);
        final RevCommit commit = git.commit().setMessage(commitMessage).call();

        if (flowPointer != null) {
            final RevTree tree = commit.getTree();
            final String bucketDirName = bucket.getBucketDirName();
            final String flowSnapshotPath = new File(bucketDirName, flowPointer.getFileName()).getPath();
            try (final TreeWalk treeWalk = new TreeWalk(gitRepo)) {
                treeWalk.addTree(tree);

                while (treeWalk.next()) {
                    if (treeWalk.isSubtree()) {
                        treeWalk.enterSubtree();
                    } else {
                        final String pathString = treeWalk.getPathString();
                        if (pathString.equals(flowSnapshotPath)) {
                            // Capture updated object id.
                            final String flowSnapshotObjectId = treeWalk.getObjectId(0).getName();
                            flowPointer.setObjectId(flowSnapshotObjectId);
                            break;
                        }
                    }
                }
            }

            flowPointer.setGitRev(commit.getName());
        }

        // Push if necessary.
        if (!isEmpty(remoteToPush)) {
            // Use different thread since it takes longer.
            final long offeredTimestamp = System.currentTimeMillis();
            if (pushQueue.offer(offeredTimestamp)) {
                logger.debug("New push request is offered at {}.", offeredTimestamp);
            }
        }

    }
}

From source file:org.apache.stratos.cartridge.agent.artifact.deployment.synchronizer.git.impl.GitBasedArtifactRepository.java

License:Apache License

/**
 * initializes and populates the git context with relevant data
 *
 * @param repositoryInformation id of the tenant
 *//*  www.  j  a v  a  2s  . com*/
private void initGitContext(RepositoryInformation repositoryInformation) {

    log.info("Initializing git context.");

    int tenantId = Integer.parseInt(repositoryInformation.getTenantId());
    String gitLocalRepoPath = repositoryInformation.getRepoPath();
    RepositoryContext gitRepoCtx = new RepositoryContext();
    String gitRemoteRepoUrl = repositoryInformation.getRepoUrl();
    boolean isMultitenant = repositoryInformation.isMultitenant();

    log.info("local path " + gitLocalRepoPath);
    log.info("remote url " + gitRemoteRepoUrl);
    log.info("tenant " + tenantId);

    gitRepoCtx.setTenantId(tenantId);
    gitRepoCtx.setGitLocalRepoPath(getRepoPathForTenantId(tenantId, gitLocalRepoPath, isMultitenant));
    gitRepoCtx.setGitRemoteRepoUrl(gitRemoteRepoUrl);

    gitRepoCtx.setRepoUsername(repositoryInformation.getRepoUsername());
    gitRepoCtx.setRepoPassword(repositoryInformation.getRepoPassword());

    try {
        if (isKeyBasedAuthentication(gitRemoteRepoUrl, tenantId)) {
            gitRepoCtx.setKeyBasedAuthentication(true);
            initSSHAuthentication();
        } else
            gitRepoCtx.setKeyBasedAuthentication(false);
    } catch (Exception e1) {
        log.error("Exception occurred.. " + e1.getMessage(), e1);
    }

    FileRepository localRepo = null;
    try {
        // localRepo = new FileRepository(new File(gitLocalRepoPath + "/.git"));
        // Fixing STRATOS-380
        localRepo = new FileRepository(new File(gitRepoCtx.getGitLocalRepoPath() + "/.git"));

    } catch (IOException e) {
        log.error(e);
    }

    gitRepoCtx.setLocalRepo(localRepo);
    gitRepoCtx.setGit(new Git(localRepo));
    gitRepoCtx.setCloneExists(false);

    cacheGitRepoContext(tenantId, gitRepoCtx);
}

From source file:org.apache.stratos.manager.utils.RepositoryCreator.java

License:Apache License

private void createGitFolderStructure(String tenantDomain, String cartridgeName, String[] dirArray)
        throws Exception {

    if (log.isDebugEnabled()) {
        log.debug("Creating git repo folder structure  ");
    }//from w w  w  .ja  va2  s.c  o  m

    String parentDirName = "/tmp/" + UUID.randomUUID().toString();
    CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(
            System.getProperty(CartridgeConstants.INTERNAL_GIT_USERNAME),
            System.getProperty(CartridgeConstants.INTERNAL_GIT_PASSWORD).toCharArray());
    // Clone
    // --------------------------
    FileRepository localRepo = null;
    try {
        localRepo = new FileRepository(new File(parentDirName + "/.git"));
    } catch (IOException e) {
        log.error("Exception occurred in creating a new file repository. Reason: " + e.getMessage());
        throw e;
    }

    Git git = new Git(localRepo);

    CloneCommand cloneCmd = git.cloneRepository().setURI(System.getProperty(CartridgeConstants.INTERNAL_GIT_URL)
            + "/git/" + tenantDomain + "/" + cartridgeName + ".git").setDirectory(new File(parentDirName));

    cloneCmd.setCredentialsProvider(credentialsProvider);
    try {
        log.debug("Clonning git repo");
        cloneCmd.call();
    } catch (Exception e1) {
        log.error("Exception occurred in cloning Repo. Reason: " + e1.getMessage());
        throw e1;
    }
    // ------------------------------------

    // --- Adding directory structure --------

    File parentDir = new File(parentDirName);
    parentDir.mkdir();

    for (String string : dirArray) {
        String[] arr = string.split("=");
        if (log.isDebugEnabled()) {
            log.debug("Creating dir: " + arr[0]);
        }
        File parentFile = new File(parentDirName + "/" + arr[0]);
        parentFile.mkdirs();

        File filess = new File(parentFile, "README");
        String content = "Content goes here";

        filess.createNewFile();
        FileWriter fw = new FileWriter(filess.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();
    }
    // ----------------------------------------------------------

    // ---- Git status ---------------
    StatusCommand s = git.status();
    Status status = null;
    try {
        log.debug("Getting git repo status");
        status = s.call();
    } catch (Exception e) {
        log.error("Exception occurred in git status check. Reason: " + e.getMessage());
        throw e;
    }
    // --------------------------------

    // ---------- Git add ---------------
    AddCommand addCmd = git.add();
    Iterator<String> it = status.getUntracked().iterator();

    while (it.hasNext()) {
        addCmd.addFilepattern(it.next());
    }

    try {
        log.debug("Adding files to git repo");
        addCmd.call();
    } catch (Exception e) {
        log.error("Exception occurred in adding files. Reason: " + e.getMessage());
        throw e;
    }
    // -----------------------------------------

    // ------- Git commit -----------------------

    CommitCommand commitCmd = git.commit();
    commitCmd.setMessage("Adding directories");

    try {
        log.debug("Committing git repo");
        commitCmd.call();
    } catch (Exception e) {
        log.error("Exception occurred in committing . Reason: " + e.getMessage());
        throw e;
    }
    // --------------------------------------------

    // --------- Git push -----------------------
    PushCommand pushCmd = git.push();
    pushCmd.setCredentialsProvider(credentialsProvider);
    try {
        log.debug("Git repo push");
        pushCmd.call();
    } catch (Exception e) {
        log.error("Exception occurred in Git push . Reason: " + e.getMessage());
        throw e;
    }

    try {
        deleteDirectory(new File(parentDirName));
    } catch (Exception e) {
        log.error("Exception occurred in deleting temp files. Reason: " + e.getMessage());
        throw e;
    }

    log.info(" Folder structure  is created ..... ");

}