美文网首页
java git diff

java git diff

作者: 西三旗靓仔 | 来源:发表于2019-07-07 10:21 被阅读0次

    文本比对

    最近项目上需要对比用户对配置的修改,用到了git的比对功能,在这里写一个demo实验一下

    maven依赖

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

    Demo

    
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import org.eclipse.jgit.diff.DiffAlgorithm;
    import org.eclipse.jgit.diff.DiffAlgorithm.SupportedAlgorithm;
    import org.eclipse.jgit.diff.DiffFormatter;
    import org.eclipse.jgit.diff.Edit;
    import org.eclipse.jgit.diff.EditList;
    import org.eclipse.jgit.diff.HashedSequence;
    import org.eclipse.jgit.diff.HashedSequenceComparator;
    import org.eclipse.jgit.diff.LowLevelDiffAlgorithm;
    import org.eclipse.jgit.diff.MyersDiff;
    import org.eclipse.jgit.diff.RawText;
    import org.eclipse.jgit.diff.RawTextComparator;
    import org.eclipse.jgit.diff.Sequence;
    import org.eclipse.jgit.internal.JGitText;
    
    /**
     * @ClassName TestDiff
     * @Description 对比文件
     * @Author ccm
     * @Date 2019/7/3 下午1:52
     * @Version 1.0
        **/
        public class TestDiff {
    
    
    
      public static void main(String[] args) {
        args = new String[]{"/users/didi/desktop/补充数据.sh","/users/didi/desktop/补充数据1.sh"};
        if (args.length != 2) {
          System.err.println(JGitText.get().need2Arguments);
          System.exit(1);
        }
    
        try {
          RawText a = new RawText(new File(args[0]));
          RawText b = new RawText(new File(args[1]));
          EditList r = DiffAlgorithm.getAlgorithm(SupportedAlgorithm.MYERS).diff(RawTextComparator.DEFAULT, a, b);
          System.out.println(r.toString());
        
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          DiffFormatter formatter = new DiffFormatter(out);
          formatter.format(r,a,b);
          System.out.println(new String(out.toByteArray()));
          out.close();
          formatter.close();
        } catch (Exception var4) {
          var4.printStackTrace();
        }
    
      }
    
    }
    

    结果

    EditList[INSERT(2-2,2-4), REPLACE(4-5,6-13)]
    @@ -1,5 +1,13 @@
     for i in {1..5}; do     dt=`date -d "$i day ago" '+%Y-%m-%d'`;   echo $dt  ; sh a.sh $dt; done
     
    +agac
    +
     for i in {1..5}; do     dt=`date -d "$i day ago" '+%Y-%m-%d'`;   echo $dt  ; sh a.sh $dt; done
     
    -for i in {1..5}; do     dt=`date -d "$i day ago" '+%Y-%m-%d'`;   echo $dt  ; sh b.sh $dt; done
    \ No newline at end of file
    +for i in {1..5}; do     dt=`date -d "$i day ago" '+%Y-%m-%d'`;   echo $dt  ; sh b.sh $dt; done
    +
    +abac
    +case word in
    + pattern )
    +  ;;
    +esac
    \ No newline at end of file
    

    相关文章

      网友评论

          本文标题:java git diff

          本文链接:https://www.haomeiwen.com/subject/zqqbhctx.html