<commit_before>package org.popkit.leap.elpa.utils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.popkit.core.config.LeapConfigLoader;
import org.popkit.leap.elpa.constents.EnvEnum;
import org.popkit.leap.elpa.entity.DepsItem;
import org.popkit.leap.elpa.entity.RecipeDo;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * Created by <NAME>
 * Mail <EMAIL>
 * 2016-05-14:06:59
 */
public class PelpaUtils {
    private static final String WORKING_DIR_KEY = "elpa_working_path";
    public static final String RECIPE_FILE_PATH_KEY = "elpa_recipes_path";
    private static final String HTML_DIR_KEY = "elpa_html_path";
    private static final String LOG_FILE_KEY = "elpa_log_file";

    private PelpaUtils() {
    }

    public static String getStaticsPath() {
        return LeapConfigLoader.get("elpa_statics_path");
    }

    public static String getLogFileName() {
        return LeapConfigLoader.get(LOG_FILE_KEY);
    }

    public static String getRecipeFilePath() {
        return LeapConfigLoader.get(RECIPE_FILE_PATH_KEY);
    }

    public static String getWorkingPath(String pkgName) {
        return LeapConfigLoader.get(WORKING_DIR_KEY) + pkgName;
    }

    public static String getWorkingRootDir() {
        return LeapConfigLoader.get(WORKING_DIR_KEY);
    }

    public static String getPkgElispFileName(String pkgName) {
        return getWorkingPath(pkgName) +  "/" + pkgName + "-pkg.el";
    }

    /**
     (define-package "ztree" "20150703.113" "Text mode directory tree" 'nil :keywords
     '("files" "tools")
     :url "https://github.com/fourier/ztree")
     * @param pkgName
     * @return
     */
    public static boolean generatePkgElispFileContent(String pkgName, String version,
                                                      String shortInfo, List<String> keywords,
                                                      List<DepsItem> deps, String url,
                                                      File destPkgDescFile, File originPkgFile) {
        String resultContent = null;
        if (originPkgFile != null && originPkgFile.exists() && originPkgFile.isFile()) {
            try {
                String originContent = RecipeParser.readFileToStringWithoutComments(originPkgFile);
                String[] originContentArr = originContent.split("\\s+");
                String originPkgName = PelpaUtils.unwrap(originContentArr[1]);
                if (originContentArr.length > 2 && pkgName.equalsIgnoreCase(originPkgName)) {
                    String versionOrigin = originContentArr[2];
                    resultContent = originContent.replace(versionOrigin, PelpaUtils.wrap(version));
                    if (!pkgName.equals(originPkgName)) {
                        resultContent = resultContent.replace(originPkgName, pkgName);
                    }
                }
            } catch (Exception e) {
                //
            }
        } else {
            StringBuilder stringBuilder = new StringBuilder("");
            stringBuilder.append("(define-package ").append(wrap(pkgName)).append(" ")
                    .append(wrap(version)).append(" ").append(wrap(shortInfo))
                    .append(" ").append(deps(deps))
                    .append(" ").append(url(url))
                    .append(" ").append(keywords(keywords));

            stringBuilder.append(")");
            resultContent = stringBuilder.toString();
        }

        try {
            if (StringUtils.isNotBlank(resultContent)) {
                FileUtils.writeStringToFile(destPkgDescFile, resultContent);
            } else {
                return false;
            }
        } catch (IOException e) {
            return false;
        }

        return true;
    }

    private static String deps(List<DepsItem> depsItems) {
        if (CollectionUtils.isNotEmpty(depsItems)) {
            StringBuilder sb = new StringBuilder();
            sb.append(" '(");
            for (DepsItem item : depsItems) {
                if (CollectionUtils.isEmpty(depsItems)) {
                    continue;
                }
                sb.append("(");
                sb.append(item.getName()).append(" ").append(wrap(item.getVersionString()));
                sb.append(") ");
            }<commit_msg>fix buf for pkgname not provided<commit_after>package org.popkit.leap.elpa.utils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.popkit.core.config.LeapConfigLoader;
import org.popkit.leap.elpa.constents.EnvEnum;
import org.popkit.leap.elpa.entity.DepsItem;
import org.popkit.leap.elpa.entity.RecipeDo;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * Created by <NAME>
 * Mail <EMAIL>
 * 2016-05-14:06:59
 */
public class PelpaUtils {
    private static final String WORKING_DIR_KEY = "elpa_working_path";
    public static final String RECIPE_FILE_PATH_KEY = "elpa_recipes_path";
    private static final String HTML_DIR_KEY = "elpa_html_path";
    private static final String LOG_FILE_KEY = "elpa_log_file";

    private PelpaUtils() {
    }

    public static String getStaticsPath() {
        return LeapConfigLoader.get("elpa_statics_path");
    }

    public static String getLogFileName() {
        return LeapConfigLoader.get(LOG_FILE_KEY);
    }

    public static String getRecipeFilePath() {
        return LeapConfigLoader.get(RECIPE_FILE_PATH_KEY);
    }

    public static String getWorkingPath(String pkgName) {
        return LeapConfigLoader.get(WORKING_DIR_KEY) + pkgName;
    }

    public static String getWorkingRootDir() {
        return LeapConfigLoader.get(WORKING_DIR_KEY);
    }

    public static String getPkgElispFileName(String pkgName) {
        return getWorkingPath(pkgName) +  "/" + pkgName + "-pkg.el";
    }

    /**
     (define-package "ztree" "20150703.113" "Text mode directory tree" 'nil :keywords
     '("files" "tools")
     :url "https://github.com/fourier/ztree")
     * @param pkgName
     * @return
     */
    public static boolean generatePkgElispFileContent(String pkgName, String version,
                                                      String shortInfo, List<String> keywords,
                                                      List<DepsItem> deps, String url,
                                                      File destPkgDescFile, File originPkgFile) {
        String resultContent = null;
        if (originPkgFile != null && originPkgFile.exists() && originPkgFile.isFile()) {
            try {
                String originContent = RecipeParser.readFileToStringWithoutComments(originPkgFile);
                String[] originContentArr = originContent.split("\\s+");
                String originPkgName = PelpaUtils.unwrap(originContentArr[1]);
                if (originContentArr.length < 2) {
                    return false;
                }
                if (pkgName.equalsIgnoreCase(originPkgName)) {
                    String versionOrigin = originContentArr[2];
                    resultContent = originContent.replace(versionOrigin, PelpaUtils.wrap(version));
                    if (!pkgName.equals(originPkgName)) {
                        resultContent = resultContent.replace(originPkgName, pkgName);
                    }
                } else {
                    List<String> unwrapOriginContentList = splitSmartSpace(originContent);
                    if (unwrapOriginContentList.size() > 2) {
                        String orgPkgName = PelpaUtils.unwrap(unwrapOriginContentList.get(1));
                        String versionOrigin = PelpaUtils.unwrap(unwrapOriginContentList.get(2));
                        resultContent = originContent.replace(orgPkgName, pkgName).replace(versionOrigin, version);
                    }
                }
            } catch (Exception e) {
                //
            }
        } else {
            StringBuilder stringBuilder = new StringBuilder("");
            stringBuilder.append("(define-package ").append(wrap(pkgName)).append(" ")
                    .append(wrap(version)).append(" ").append(wrap(shortInfo))
                    .append(" ").append(deps(deps))
                    .append(" ").append(url(url))
                    .append(" ").append(keywords(keywords));

            stringBuilder.append(")");
            resultContent = stringBuilder.toString();
        }

        try {
            if (StringUtils.isNotBlank(resultContent)) {
                FileUtils.writeStringToFile(destPkgDescFile, resultContent);
            } else {
                return false;
            }
        } catch (IOException e) {
            return false;
        }

        return true;
    }

    /**
     * 将这种转成List<String>
     * (define-package "Chinese Wubi Input Method" "0.1"   "Enable Wubi Input Method in Emacs.")
      */
    private static List<String> splitSmartSpace(String origin) {
        List<String> result = new ArrayList<String>();
        String unwrapResult = origin;
        if (origin.trim().startsWith("(")) {
            unwrapResult = RecipeParser.extraPairContent(origin);
        }
        int start = 0;
        int record = 0;
        for (int i=0; i<unwrapResult.length(); i++) {
            if (unwrapResult.charAt(i) == ' ') {
                if (record == 0 && i>0) {
                    String current = unwrapResult.substring(start, i).trim();
                    start = i;
                    if (StringUtils.isNotBlank(current)) {
                        result.add(current);
                    }
                    continue;
                }
            }

            if (unwrapResult.charAt(i) == '"') {
                if (record == 0) {
                    record ++;
                } else {
                    record --;
                }
            }
        }
        return result;
    }

    private static String deps(List<DepsItem> depsItems) {
        if (CollectionUtils.isNotEmpty(depsItems)) {
            StringBuilder sb = new StringBuilder();
            sb.append(" '(");
            for (DepsItem item : depsItems) {
                if (CollectionUtils.isEmpty(depsItems)) {
                    continue;
                }
                sb.append("(");
                sb.append(item.getName()).append(" ").append(wrap(item.getVersionString()));
                sb.append(") ");
            }
{'fraction_non_alphanumeric': 0.10659186535764376, 'fraction_numerical': 0.006077606358111267, 'mean_word_length': 1.9392690299532838, 'pattern_counts': {'":': 0, '<': 20, '<?xml version=': 0, '>': 21, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2404508', 'n_tokens_mistral': 2987, 'n_tokens_neox': 2833, 'n_words': 553}