Java tutorial
/* * 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 plumber.core.git; import com.jcraft.jsch.Session; import org.eclipse.jgit.api.*; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import org.eclipse.jgit.transport.*; import java.io.File; import java.io.IOException; public class GitWorker { private static final SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() { @Override protected void configure(OpenSshConfig.Host host, Session session) { } }; private static final TransportConfigCallback sshTransportConfigCallback = transport -> { SshTransport sshTransport = (SshTransport) transport; sshTransport.setSshSessionFactory(sshSessionFactory); }; private String gitUrl; private String gitPath; private Git git; public GitWorker(String url, String path) { gitUrl = url; gitPath = path; } public Git getGit() { return git; } public void init() throws IOException, GitAPIException { File gitFolder = new File(gitPath); File gitDB = new File(gitFolder, ".git"); if (gitDB.exists() && gitDB.isDirectory()) { FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(gitDB).readEnvironment().findGitDir().build(); git = new Git(repository); } else { CloneCommand cloneCommand = Git.cloneRepository(); cloneCommand.setURI(gitUrl); cloneCommand.setDirectory(gitFolder); cloneCommand.setTransportConfigCallback(sshTransportConfigCallback); git = cloneCommand.call(); } } public PullResult pull() throws GitAPIException { PullCommand pullCommand = git.pull(); pullCommand.setTransportConfigCallback(sshTransportConfigCallback); return pullCommand.call(); } }