DBILITY

java svn log export to excel ( svn 로그 엑셀 저장, svnログエクセル保存 ) 본문

java/basic

java svn log export to excel ( svn 로그 엑셀 저장, svnログエクセル保存 )

DBILITY 2022. 9. 6. 17:38
반응형

보고용으로 커밋로그를 옮길 일이 있는데 너무 많은 경우 답이 없다.

쉽게 되던게 있었던 것으로 기억이 나는데 intellij IDEA에서 못찾겠다ㅎㅎ

친절하게도 svnkit에서 다음을 찾았다.

https://wiki.svnkit.com/Printing_Out_Repository_History

 

Printing_Out_Repository_History - SVNKit Wiki

Main Getting A Repository History In this example we'll demonstarte how you may get the history of changes made to a repository (i.e perform a log operation) starting with the very first revision and up to the very last one. 1 ... 2 3 public class History

wiki.svnkit.com

열심히 보고 베껴 테스트해 보니 되기는 한다.

엑셀저장은 apache-poi를 사용했다. 물론 원래 시스템에서 사용하던 코드를 또 베겼다.ㅎㅎ

머리 아프다. 동작만 하면 되니 마구 작성했다. 오류만 안나면 그냥 쓰는거다. 가끔 혼자 쓰는건데

커밋할때 메시지를 아주 자세히 적어야겠다. 

command line에서 args가 6개까지 필요하다. 순서대로 svn_url, svn_id, svn_pwd, 시작rev, 끝rev,  excel_save_path다.
시작rev부터는 없어도 된다.처음부터 HEAD까지 실행경로의 temp아래에 생성된다.

import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tmatesoft.svn.core.SVNLogEntry;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class GetSvnHistory {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetSvnHistory.class);

    public static void main(String[] args) {

        DAVRepositoryFactory.setup();
        String url = args[0];
        String user = args[1];
        char[] passwd = args[2].toCharArray();
        long startRev = args.length < 4 ? 0 : Long.parseLong(args[3]);
        long endRev = args.length < 5 ? -1 : Long.parseLong(args[4]);// HEAD
        String xlsPath = (args.length < 6 ? System.getProperty("user.dir") + File.separator + "temp" : args[5])+File.separator;
        LOGGER.info("{}", xlsPath);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TimeZone tz = TimeZone.getDefault();
        //LOGGER.info("{}",tz);

        SVNRepository repository = null;
        try {
            repository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(url));
            ISVNAuthenticationManager authenticationManager = SVNWCUtil.createDefaultAuthenticationManager(user, passwd);
            repository.setAuthenticationManager(authenticationManager);

            Collection logEntries = null;
            logEntries = repository.log(new String[]{""}, null, startRev, endRev, true, true);

            List<Map<String, Object>> historyList = new ArrayList<>();
            Map<String, Object> headerMap = new HashMap<>();
            headerMap.put("rev", "버전");
            headerMap.put("date", "업로드일");
            headerMap.put("count", "파일수");
            headerMap.put("author", "업로드계정");
            headerMap.put("message", "업로드내용");
            historyList.add(headerMap);
            LOGGER.info("{}, {}, {}, {}, {}", "버전", "업로드일", "파일수", "업로드계정", "업로드내용");
            for (Object obj : logEntries) {
                SVNLogEntry entry = (SVNLogEntry) obj;
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("rev", entry.getRevision());
                dataMap.put("date", FastDateFormat.getInstance("yyyy-MM-dd a HH:mm:ss",tz).format(entry.getDate()));
                dataMap.put("count", entry.getChangedPaths().size());
                dataMap.put("author", entry.getAuthor());
                dataMap.put("message", entry.getMessage());
                historyList.add(dataMap);
                LOGGER.info("{}, {}, {}, {}, {}", entry.getRevision(), FastDateFormat.getInstance("yyyy-MM-dd a HH:mm:ss",tz).format(entry.getDate()), entry.getChangedPaths().size(), entry.getAuthor(), entry.getMessage());
            }
            //LOGGER.info("historyList {}", historyList);

            if (historyList.size() > 1) {
                xlsxWriter(historyList, xlsPath);
            }

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.info("{}", e.getMessage());
        }
    }

    private static void xlsxWriter(List<Map<String, Object>> list, String xlsPath) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();
        XSSFRow row = sheet.createRow(0);
        XSSFCellStyle style = workbook.createCellStyle();
        style.setWrapText(true);
        row.setRowStyle(style);
        XSSFCell cell;
        Map<String, Object> headerMap = list.get(0);
        cell = row.createCell(0);
        cell.setCellValue(headerMap.get("rev").toString());
        cell = row.createCell(1);
        cell.setCellValue(headerMap.get("date").toString());
        cell = row.createCell(2);
        cell.setCellValue(headerMap.get("count").toString());
        cell = row.createCell(3);
        cell.setCellValue(headerMap.get("author").toString());
        cell = row.createCell(4);
        cell.setCellValue(headerMap.get("message").toString());

        for (int i = 1; i < list.size(); i++) {
            Map<String, Object> dataMap = list.get(i);
            row = sheet.createRow(i);
            cell = row.createCell(0);
            cell.setCellValue(dataMap.get("rev").toString());
            cell = row.createCell(1);
            cell.setCellValue(dataMap.get("date").toString());
            cell = row.createCell(2);
            cell.setCellValue(dataMap.get("count").toString());
            cell = row.createCell(3);
            cell.setCellValue(dataMap.get("author").toString());
            cell = row.createCell(4);
            cell.setCellValue(dataMap.get("message").toString());
            row.getCell(4).setCellStyle(style);
        }
        for (int i = 0; i < 5; i++) {
            sheet.autoSizeColumn(i);
        }

        File path = new File(xlsPath);
        if(!path.exists()) {
            path.mkdir();
        }
        File file = new File(xlsPath+"SVNLog.xlsx");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            workbook.write(fos);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {

            try {
                if (workbook != null) workbook = null;
                if (fos != null) fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
반응형
Comments