Monday, November 26, 2018

Java and JGit

The Jgit library makes it REALLY easy to work with Git repositories.

Here a log of examples https://github.com/centic9/jgit-cookbook

https://www.baeldung.com/jgit

Just create a basic Spring boot application, add dependency

<dependency>
 <groupId>org.eclipse.jgit</groupId>
 <artifactId>org.eclipse.jgit</artifactId>
 <version>5.1.3.201810200350-r</version>
</dependency>


and use this code

package com.example.jgittest;

import java.io.File;
import java.io.PrintWriter;

import org.eclipse.jgit.api.AddCommand;
import org.eclipse.jgit.api.CommitCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Repository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class JgittestApplication  implements CommandLineRunner {

 public static void main(String[] args) {
  SpringApplication.run(JgittestApplication.class, args);
 }
 @Override
 public void run(String... args) throws Exception {
  File directory1 = new File("c:\\temp\\one");
  Git git1 = Git.init().setDirectory(directory1).call();
  File newFile = new File(directory1, "pippo.txt");
  PrintWriter out = new PrintWriter(newFile);
  out.println("hello pippo");
  out.close();
  Repository rep1 = git1.getRepository();
  AddCommand add = git1.add();
  add.addFilepattern("pippo.txt");
  System.out.println("adding pippo.txt");
  add.call();
  CommitCommand commit = git1.commit();
  System.out.println("committing pippo.txt");
  commit.setMessage("initial commit").call();
  
  File directory2 = new File("c:\\temp\\two");
  if (!directory2.exists()) {
   Git git2 = Git.cloneRepository().setURI("https://github.com/eclipse/jgit.git").setDirectory(directory2).call();
  }
  
  
 }
}



No comments: