JGit - --- Git 을 응용 프로그램 에 끼 워 넣 기
                                            
 13561 단어  자바
                    
의존 추가
JGit 을 프로젝트 에 의존 하고 코드 를 쓸 수 있 는 여러 가지 방법 이 있 습 니 다.가장 쉬 운 방법 은 아마도 Maven 을 사용 하 는 것 일 것 이다.pom. xml 파일 의 탭 에 아래 와 같은 세 션 을 추가 하여 통합 을 완성 할 수 있 습 니 다.
    
        org.eclipse.jgit 
        org.eclipse.jgit 
        5.5.1.201910021850-r 
       이 글 을 읽 었 을 때 version 이 업데이트 되 었 을 가능성 이 높 습 니 다. 최신 창고 정 보 를 얻 기 위해 서 http://mvnrepository.com/arti... 를 찾 아 보 세 요.이 단계 가 완료 되면 Maven 은 필요 한 JGit 라 이브 러 리 를 자동 으로 가 져 와 사용 합 니 다.
프로젝트 실천
구축 내 블 로그 과정 에서 이 블 로 그 는 자신의 서버 에 배치 되 어 있 기 때문에 ci 자동 컴 파일 이 완 료 된 후에 제 서버 에 자동 으로 배치 되 어야 합 니 다.
다음은 주로 pull 추출 방법 을 사용 하 였 습 니 다.
package com.easy.jGit.controller;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jgit.api.*;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
@RestController
@Slf4j
public class JGitController {
    /**
     * git   
     */
    final String patch = "/opt/webapps/blog/.git";
    /**
     *     
     */
    final String branch = "origin/gh-pages";
    /**
     *   
     *
     * @return
     */
    @RequestMapping("/pull")
    public String pull() {
        String result;
        Repository repo = null;
        try {
            repo = new FileRepository(new File(patch));
            Git git = new Git(repo);
            log.info("    ");
            //  
            git.reset()
                    .setMode(ResetCommand.ResetType.HARD)
                    .setRef(branch).call();
            log.info("    ");
            //  
            git.pull()
                    .setRemote("origin")
                    .setRemoteBranchName("gh-pages")
                    .call();
            result = "    !";
            log.info(result);
        } catch (Exception e) {
            result = e.getMessage();
        } finally {
            if (repo != null) {
                repo.close();
            }
        }
        return result;
    }
    /**
     *   
     *
     * @return
     */
    @RequestMapping("/reset")
    public String reset() {
        String result;
        Repository repo = null;
        try {
            repo = new FileRepository(new File(patch));
            Git git = new Git(repo);
            git.reset().setMode(ResetCommand.ResetType.HARD).setRef(branch).call();
            result = "    !";
        } catch (Exception e) {
            result = e.getMessage();
        } finally {
            if (repo != null) {
                repo.close();
            }
        }
        return result;
    }
    /**
     *   
     */
    @RequestMapping("/revert")
    public String revert() {
        String result;
        Repository repo = null;
        try {
            repo = new FileRepository(new File(patch));
            Git git = new Git(repo);
            git.revert().call();
            result = "    !";
        } catch (Exception e) {
            result = e.getMessage();
        } finally {
            if (repo != null) {
                repo.close();
            }
        }
        return result;
    }
    /**
     *   
     *
     * @return
     */
    @RequestMapping("/clone")
    public String clone() {
        String result;
        try {
            Git.cloneRepository()
                    .setURI("https://github.com/smltq/blog.git")
                    .setDirectory(new File("/blog"))
                    .call();
            result = "     !";
        } catch (GitAPIException e) {
            result = e.getMessage();
            e.printStackTrace();
        }
        return result;
    }
    /**
     *   
     */
    @RequestMapping("/status")
    public static void status() {
        File RepoGitDir = new File("/blog/.git");
        Repository repo = null;
        try {
            repo = new FileRepository(RepoGitDir.getAbsolutePath());
            Git git = new Git(repo);
            Status status = git.status().call();
            log.info("Git Change: " + status.getChanged());
            log.info("Git Modified: " + status.getModified());
            log.info("Git UncommittedChanges: " + status.getUncommittedChanges());
            log.info("Git Untracked: " + status.getUntracked());
        } catch (Exception e) {
            log.info(e.getMessage());
        } finally {
            if (repo != null) {
                repo.close();
            }
        }
    }
}  . travis. yml 원본 파일
language: node_js #     
node_js: stable   #       
cache:
  apt: true
  directories:
    - node_modules #           
before_install:
  - export TZ='Asia/Shanghai' #     
  - npm install hexo-cli -g
  #- chmod +x ./publish-to-gh-pages.sh  #  shell         
install:
  - npm install #   hexo   
script:
  - hexo clean  #   
  - hexo g      #   
after_script:
  - git clone https://${GH_REF} .deploy_git
  - cd .deploy_git
  - git checkout master:gh-pages
  - cd ../
  - mv .deploy_git/.git/ ./public/
  - cd ./public
  - git config user.name  "tqlin"
  - git config user.email "[email protected]"
  # add commit timestamp
  - git add .
  - git commit -m "Travis CI Auto Builder at `date +"%Y-%m-%d %H:%M"`"
  - git push --force --quiet "https://${GH_TOKEN}@${GH_REF}" master:gh-pages && curl http://49.235.170.100:8787/pull
  - curl http://49.235.170.100:8787/pull   #             
branches:
  only:
    - master #    master  
env:
  global:
    - GH_REF: github.com/smltq/blog.git #  GH_REF  기본 개념
대부분의 JGit 세 션 은 Repository 클래스 를 시작 으로 합 니 다. 먼저 해 야 할 일 은 인 스 턴 스 를 만 드 는 것 입 니 다.파일 시스템 기반 창고 의 경우 (JGit 은 다른 저장 모델 을 허용 합 니 다) FileRepository Builder 로 완성 합 니 다.
//        
Repository newlyCreatedRepo = FileRepositoryBuilder.create(
    new File("/tmp/new_repo/.git"));
newlyCreatedRepo.create();
//          
Repository existingRepo = new FileRepositoryBuilder()
    .setGitDir(new File("my_repo/.git"))
    .build();  Repository 인 스 턴 스 를 가지 고 있 으 면 여러 가지 일 을 할 수 있 습 니 다.예 를 들 면:
//     
Ref master = repo.getRef("master");
//            
ObjectId masterTip = master.getObjectId();
// Rev-parse
ObjectId obj = repo.resolve("HEAD^{tree}");
//         
ObjectLoader loader = repo.open(masterTip);
loader.copyTo(System.out);
//     
RefUpdate createBranch1 = repo.updateRef("refs/heads/branch1");
createBranch1.setNewObjectId(masterTip);
createBranch1.update();
//     
RefUpdate deleteBranch1 = repo.updateRef("refs/heads/branch1");
deleteBranch1.setForceUpdate(true);
deleteBranch1.delete();
//   
Config cfg = repo.getConfig();
String name = cfg.getString("user", null, "name");  명령 을 제출 하 다
AddCommand 는 작업 영역의 내용 을 임시 저장 소 에 추가 할 수 있 습 니 다.
Git git = Git.open(new File("D:\\source-code\\temp\\.git"));
git.add().addFilepattern(".").call(); //    git add -A         git.add().addFilepattern("*.java")         
git.add().addFilepattern("src/main/java/").call(); //     ,                
//jgit             ,  *.java  CommitCommand 는 제출 작업 에 사 용 됩 니 다.
Git git =Git.open(new File("D:\\source-code\\temp\\user1\\.git"));
CommitCommand commitCommand = git.commit().setMessage("master 23 commit").setAllowEmpty(true);
commitCommand.call();  status 명령
    Git git = Git.open(new File("D:\\source-code\\temp-1\\.git"));
    Status status = git.status().call();        //              ,       
    status.getAdded().forEach(it -> System.out.println("Add File :" + it));      //git add        
    status.getRemoved().forEach(it -> System.out.println("Remove File :" + it));  ///git rm       ,           
    status.getModified().forEach(it -> System.out.println("Modified File :" + it));  //       
    status.getUntracked().forEach(it -> System.out.println("Untracked File :" + it)); //          
    status.getConflicting().forEach(it -> System.out.println("Conflicting File :" + it)); //       
    status.getMissing().forEach(it -> System.out.println("Missing File :" + it));    //            로그 명령
LogCommand 는 git log 명령 에 해당 합 니 다.
//         ,       
Git git = Git.open(new File("D:\\source-code\\temp-1\\.git"));
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Iterable results = git.log().setRevFilter(new RevFilter() {
    @Override
    public boolean include(RevWalk walker, RevCommit cmit)
       throws StopWalkException, MissingObjectException, IncorrectObjectTypeException, IOException {
        return cmit.getAuthorIdent().getName().equals("xxxxx dsd");
    }
    @Override
    public RevFilter clone() {
    return this;
            }
        }).call();
results.forEach(commit -> {
    PersonIdent authoIdent = commit.getAuthorIdent();
    System.out.println("   :  " + authoIdent.getName() + "     ");
    System.out.println("  SHA1:  " + commit.getId().name());
    System.out.println("    :  " + commit.getShortMessage());
    System.out.println("    :  " + format.format(authoIdent.getWhen()));
});   fetch 명령
fetch 명령
Repository rep = new FileRepository("D:\\source-code\\temp-1\\.git");
Git git = new Git(rep);
git.pull().setRemote("origin").call();
//fetch     setRefSpecs  , pull       ,  pull    fetch     
git.fetch().setRefSpecs("refs/heads/*:refs/heads/*").call();  push 명령
PushCommand 는 git push 와 마찬가지 로 사용자 이름과 비밀 번 호 를 제공 해 야 합 니 다. Credentials Provider 클래스 를 사용 해 야 합 니 다.
Repository rep = new FileRepository("D:\\source-code\\temp-1\\.git");
Git git = new Git(rep);
git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider("myname", "password")).call();  클론 명령
Clone Command 등가 와 git clone 명령
Git.cloneRepository().setURI("https://admin@localhost:8443/r/game-of-life.git")
                .setDirectory(new File("D:\\source-code\\temp-1")).call();  RevWalk API
다음 코드 는 이러한 기능 을 실현 하여 특정한 파일 의 역사 기록 을 찾 고 제출 한 모든 파일 내용 을 인쇄 합 니 다.
 DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 Repository repository = new RepositoryBuilder().setGitDir(new File("D:\\source-code\\temp-1\\.git")).build();
 try (RevWalk walk = new RevWalk(repository)) {
     Ref head = repository.findRef("HEAD");
     walk.markStart(walk.parseCommit(head.getObjectId())); //  HEAD    ,
     for (RevCommit commit : walk) {
         RevTree tree = commit.getTree();
         TreeWalk treeWalk = new TreeWalk(repository, repository.newObjectReader());
         PathFilter f = PathFilter.create("pom.xml");
         treeWalk.setFilter(f);
         treeWalk.reset(tree);
         treeWalk.setRecursive(false);
         while (treeWalk.next()) {
             PersonIdent authoIdent = commit.getAuthorIdent();
             System.out.println("   : " + authoIdent.getName() + " ");
             System.out.println("  SHA1: " + commit.getId().name());
             System.out.println("    : " + commit.getShortMessage());
             System.out.println("    : " + format.format(authoIdent.getWhen()));
             ObjectId objectId = treeWalk.getObjectId(0);
             ObjectLoader loader = repository.open(objectId);
             loader.copyTo(System.out);              //  blob     
         }
     }
 }  기타 더 많은 명령 참조 홈 페이지
자료.
Spring Boot, 클 라 우 드 학습 프로젝트
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.