2020-09-24

idea 插件  转换 proto 文件 为 java文件

注意插件需要 protoc.exe 打进jar中 

有问题联系 qq :56798405

 

plugin.xml

<idea-plugin>
  <id>com.wangyuan.plugin.protoc</id>
  <name>protoc</name>
  <version>1.0</version>
  <vendor email="18568263560@163.com" url="http://www.wangyuan.com">网元圣唐</vendor>

  <description>protocol to java </description>

  <change-notes><![CDATA[
      Add change notes here.<br>
      <em>most HTML tags may be used</em>
    ]]>
  </change-notes>

  <!-- please see http://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/build_number_ranges.html for description -->
  <idea-version since-build="145.0"/>

  <!-- please see http://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/plugin_compatibility.html
       on how to target different products -->
  <!-- uncomment to enable plugin in all products
  <depends>com.intellij.modules.lang</depends>
  -->

  <extensions defaultExtensionNs="com.intellij">
    <!-- Add your extensions here -->
  </extensions>

  <actions>
    <action id="ProtocAction" class="ProtocAction" text="Protoc" description="右键Action"  >
      <add-to-group group-id="ProjectViewPopupMenu" anchor="after" relative-to-action="ReplaceInPath"/>
    </action>
  </actions>

</idea-plugin>

 

 

import com.intellij.openapi.ui.Messages;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class FileUtils {
    

    /**
     * 解压到指定目录
     */
    public static void unZipFiles(String zipPath,String descDir)throws IOException
    {
        unZipFiles(new File(zipPath), descDir);
    }
    /**
     * 解压文件到指定目录
     */
    @SuppressWarnings("rawtypes")
    public static void unZipFiles(File zipFile,String descDir)throws IOException
    {
        File pathFile = new File(descDir);
        if(!pathFile.exists())
        {
            pathFile.mkdirs();
        }
        //解决zip文件中有中文目录或者中文文件
        ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
        for(Enumeration entries = zip.entries(); entries.hasMoreElements();)
        {
            ZipEntry entry = (ZipEntry)entries.nextElement();
            String zipEntryName = entry.getName();
            InputStream in = zip.getInputStream(entry);
            String outPath = (descDir+zipEntryName).replaceAll("\\*", "/");;
            //判断路径是否存在,不存在则创建文件路径
            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if(!file.exists())
            {
                file.mkdirs();
            }
            //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
            if(new File(outPath).isDirectory())
            {
                continue;
            }
            //输出文件路径信息
            System.out.println(outPath);
            OutputStream out = new FileOutputStream(outPath);
            byte[] buf1 = new byte[1024];
            int len;
            while((len=in.read(buf1))>0)
            {
                out.write(buf1,0,len);
            }
            in.close();
            out.close();
        }
        System.out.println("******************解压完毕********************");
    }

}
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.vfs.VirtualFile;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.swing.Icon;

public class ProtocAction extends AnAction {
    public static final Icon PROTO_ICON = IconLoader.getIcon("/icon.png");
    public static final Icon ERROR_ICON = IconLoader.getIcon("/error.png");
    public static final Icon PASS_ICON = IconLoader.getIcon("/passed.png");


    public ProtocAction() {
        super(null,null,PROTO_ICON);
    }

    public ProtocAction(String text, String desc,Icon icon){
        super(text,desc, PROTO_ICON);
    }

    @Override
    public void actionPerformed(AnActionEvent event) {
        VirtualFile[] files = event.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY);
        int succNum = 0;
        String path = this.getClass().getClassLoader().getResource("protoc.exe").getPath();
        path = path.replace("!","");
        String jarPath = path.substring(6, path.lastIndexOf("/"));
        String lastPath = jarPath.substring(0, jarPath.lastIndexOf("/")+1);
        String exePath = lastPath + "protoc.exe";
        File exeFile = new File(exePath);
        if (!exeFile.exists()){
            try {
                FileUtils.unZipFiles(new File(jarPath), lastPath);
            }catch (Exception e){
                Messages.showMessageDialog(e.getMessage()+ e.getClass().getName(), "Exception", ERROR_ICON);
            }
        }
        for (VirtualFile file:files){
           int status =  run(file, exePath);
           if (status == 0){
               succNum++;
           }
        }
        if(succNum  == files.length){
            Messages.showMessageDialog("protoc succ!!", "protoc", PASS_ICON);
        }
    }

    private int run(VirtualFile data, String exePath){
        if ("proto".equals(data.getExtension())) {//根据扩展名判定是否进行下面的处理
            String url = data.getUrl();
            url = url.split("//")[1];

//            String[] filePath = url.split("/");
            String out = calOutPath(url);
            String protoPath = calProtoPath(url);
            String cmd = String.format("%s -I=%s --java_out=%s %s", new Object[] {  exePath, protoPath.substring(0,protoPath.length()-1), out,  url});
            try {
                int status = execCmd(cmd);
                return status;
            }catch (Exception e){
                Messages.showMessageDialog(e.getMessage(), "protoc", ERROR_ICON);
                Messages.showMessageDialog(cmd, "protoc", ERROR_ICON);
                e.printStackTrace();
                return -1;
            }

        }else {
            Messages.showMessageDialog("only support proto files", "protoc", ERROR_ICON);
            return -1;
        }
    }


    private String calProtoPath(String filePath){
       return  filePath.substring(0,filePath.lastIndexOf("/")+1);
//        StringBuilder tempPath = new StringBuilder();
//        for (int i=0;i<filePath.length - 1;i++){
//            tempPath.append(filePath[i]);
//            tempPath.append("/");
//        }
//        return tempPath.toString();
    }

    private String calOutPath(String filePath){
        StringBuilder out = new StringBuilder();
        out.append(filePath.substring(0, filePath.lastIndexOf("src")));
//        for (int i=0;i<filePath.length;i++){
//            String str = filePath[i];
//            if (str.equals("src")){
//                break;
//            }
//            out.append(str);
//            out.append("/");
//        }
        out.append("target/generated-sources/protobuf/java");
        File dir = new File(out.toString());
        if (!dir.exists()){
            dir.mkdirs();
        }
        return out.toString();
    }



    private int execCmd(String cmd) throws IOException, InterruptedException {
        Process pr = Runtime.getRuntime().exec(cmd);
        BufferedReader reader = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
        pr.waitFor();
        int status = pr.exitValue();
        StringBuilder sb = (new StringBuilder(status)).append("\n");
        for (; reader.ready(); sb.append(reader.readLine()).append("\n"));
        reader.close();
       if (status != 0){
           Messages.showMessageDialog(sb.toString(), "protoc", ERROR_ICON);
        }
        pr.destroy();
        return status;
    }
}

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值