简体   繁体   English

从Java Project的命令行运行NPM DiffChecker

[英]Run NPM DiffChecker from Command Line from Java Project

I am trying to write a straightforward application which packages all of the Salesforce ANT files I download. 我正在尝试编写一个简单的应用程序,该程序打包我下载的所有Salesforce ANT文件。 I download them into a folder structure like this 我将它们下载到这样的文件夹结构中

main\\source\\file1.js 主\\源\\ file1.js

main\\target\\file1.js 主\\目标\\ file1.js

source in my salesforce org is almost no different than a dev branch in Git. 我的salesforce组织中的源代码几乎与Git中的dev分支相同。 The target folder is the file I will be overwriting. 目标文件夹是我将要覆盖的文件。 I built the following program to simplify my life and strecth my legs in Java again. 我构建了以下程序来简化我的生活,并再次用Java锻炼腿部。 When I run the command, I get this error: 当我运行命令时,出现以下错误:

    java.io.IOException: Cannot run program "diffchecker": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at main.Main.callDiffCheckerCLI(Main.java:168)
    at main.Main.main(Main.java:81)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    ... 6 more

Main.java: Main.java:

/**
 * MIT License
 *
 * Copyright (c) 2018 Alexander Miller
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * 
 * I do not claim any rights or anything else to DiffChecker.com. This is only meant to be
 * a public tool to assist with large product development.
 */
package main;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author Alexander Miller
 * @version 10/20/2018
 */
public class Main {

    /** sourceDirectoryPath - String containing the system-specific path to source directory */
    private static String sourceDirectoryPath;

    /** targetDirectoryPath - String containing the system-specific path to target directory */
    private static String targetDirectoryPath;

    /** ignoreMetadataFiles - boolean to describe whether the metadata files should be diff'ed as well */
    @SuppressWarnings("unused")
    private static Boolean ignoreMetadataFiles;

    private static String configFileLocation = "C:\\Users\\alexa\\OneDrive\\Desktop\\DiffCheckMe.properties";

    /**
     * Main
     * 
     * @param args - String[]
     */
    public static void main(String[] args) 
    {       
        // 1. init
        init();

        // 2. Read config file and set parameters accordingly
        readConfigurationFile();

        // 3. Look at configuration resource for source folder
        sourceDirectoryPath = "C:\\\\Users\\\\alexa\\\\OneDrive\\\\Desktop\\source";
        ArrayList<File> sourceFiles = getFilesInDirectory(sourceDirectoryPath);

        // 4. Look at configuration resource for target folder
        targetDirectoryPath = "C:\\\\Users\\\\alexa\\\\OneDrive\\\\Desktop\\target";
        ArrayList<File> targetFiles = getFilesInDirectory(targetDirectoryPath);

        // 5. Marry files of the same name together
        Map<String, String> mapOfMarriedFiles = getMapOfFileMarraiges(sourceFiles, targetFiles);

        // 6. Call DiffChecker CLI on all files
        callDiffCheckerCLI(mapOfMarriedFiles);
    }

    /**
     * init
     * 
     * function to run every time the program starts up
     */
    public static void init()
    {
        sourceDirectoryPath = new String();
        targetDirectoryPath = new String();
        ignoreMetadataFiles = false;
    }

    /**
     * readConfigurationFile
     * 
     * Function which sets all of the global parameters 
     * based on what the config files says
     */
    public static void readConfigurationFile()
    {
        Properties prop = new Properties();

        InputStream input = null;

        try 
        {
            input = new FileInputStream(configFileLocation);

            // load a properties file
            prop.load(input);

            sourceDirectoryPath = prop.getProperty("sourceDirectory");      

            targetDirectoryPath = prop.getProperty("targetDirectory");

            String ignoreMetadataFilesString = prop.getProperty("ignoreMetadataFiles");
            if(ignoreMetadataFilesString.equalsIgnoreCase("true"))
            {
                ignoreMetadataFiles = true;
            }
            else
            {
                ignoreMetadataFiles = false;
            }

            System.out.println("sourceDirectoryPath: " + sourceDirectoryPath);
            System.out.println("targetDirectoryPath: " + targetDirectoryPath);
            System.out.println("ignoreMetadataFilesString: " + ignoreMetadataFilesString);
        } 
        catch (IOException ex) 
        {
            ex.printStackTrace();
        } 
        finally 
        {
            if (input != null) 
            {
                try 
                {
                    input.close();
                } 
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }
        }       
    }

    /**
     * callDiffCheckerCLI
     * 
     * Function which calls Diffchecker's CLI commands
     * 
     * This function assumes you have everything installed correctly: https://www.diffchecker.com/cli
     */
    public static void callDiffCheckerCLI(Map<String, String> mapOfFiles)
    {
        for(String fileName : mapOfFiles.keySet())
        {
            try 
            {
                System.out.println("diffchecker --expires day " + mapOfFiles.get(fileName));
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("diffchecker --expires day " + mapOfFiles.get(fileName));
                System.out.println(proc.toString());
            } 
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
    }

    public static Map<String, String> getMapOfFileMarraiges(ArrayList<File> source, ArrayList<File> target)
    {       
        Map<String, String> mapOfMarriedFiles = new HashMap<String, String>();

        for(File sourceFile : source)
        {
            if(mapOfMarriedFiles.get(sourceFile.getName()) == null)
            {
                mapOfMarriedFiles.put(sourceFile.getName(), sourceFile.getAbsolutePath());
            }
        }

        for(File targetFile : target)
        {
            if(mapOfMarriedFiles.get(targetFile.getName()) == null)
            {
                mapOfMarriedFiles.put(targetFile.getName(), targetFile.getAbsolutePath());
            }
            else
            {
                String originalValue = mapOfMarriedFiles.get(targetFile.getName());
                mapOfMarriedFiles.put(targetFile.getName(), originalValue + " " + targetFile.getAbsolutePath());
            }
        }

        return mapOfMarriedFiles;
    }

    /**
     * getFilesInDirectory
     * 
     * Given a directory via String parameter, 
     * return all of the file names found
     * 
     * @param directory - String of the system directory where the files should be pulled from
     * 
     * @return ArrayList<File> - ArrayList of all files found in given directory
     */
    public static ArrayList<File> getFilesInDirectory(String directory)
    {   
        /** folder - initialize all of the folder's contents */
        File folder = new File(directory);

        /** listOfFilesToEvaluate - array of all files, both files and directories in the given location */
        File[] listOfFilesToEvaluate = folder.listFiles();

        /** listOfFilesToReturn - ArrayList containing all of the files, not directories, chosen in the filtering */
        ArrayList<File> listOfFilesToReturn = new ArrayList<>();

        for (int i = 0; i < listOfFilesToEvaluate.length; i++) 
        {
            if (listOfFilesToEvaluate[i].isFile()) 
            {
                System.out.println(listOfFilesToEvaluate[i].getAbsolutePath());
                listOfFilesToReturn.add(listOfFilesToEvaluate[i]);
            }
        }

        return listOfFilesToReturn;
    }
}

Property file: 属性文件:

#Fri Jan 17 22:37:45 MYT 2014
sourceDirectory = ./source
targetDirectory = ./target
ignoreMetadataFiles = false
expires = day

When I run the command I'm generating manually in my command line prompt, I don't get any errors. 当我运行在命令行提示符下手动生成的命令时,没有收到任何错误。 I'm rerencing the NPM library from DiffChecker. 我正在从DiffChecker恢复NPM库

在此处输入图片说明

Found out the answer resided in this post's answer. 找出答案存在于此帖子的答案中。

public static void main(String[] args) throws IOException, InterruptedException{
        String destFolder="E:\\TestScript";
        /*
        *  Location where the Nodejs Project is Present
        */
        System.out.println(destFolder);

        String cmdPrompt="cmd";
        String path="/c";
        String npmUpdate="npm update";
        String npm="npm";
        String update="update";

        File jsFile=new File(destFolder);
        List<String> updateCommand=new ArrayList<String>();
        updateCommand.add(cmdPrompt);
        updateCommand.add(path);
        updateCommand.add(npmUpdate);

        runExecution(updateCommand,jsFile);

    }
    public static void runExecution(List<String> command, File navigatePath) throws IOException, InterruptedException{

        System.out.println(command);

        ProcessBuilder executeProcess=new ProcessBuilder(command);
        executeProcess.directory(navigatePath);
        Process resultExecution=executeProcess.start();

        BufferedReader br=new BufferedReader(new InputStreamReader(resultExecution.getInputStream()));
        StringBuffer sb=new StringBuffer();

        String line;
        while((line=br.readLine())!=null){
            sb.append(line+System.getProperty("line.separator"));
        }
        br.close();
        int resultStatust=resultExecution.waitFor();
        System.out.println("Result of Execution"+(resultStatust==0?"\tSuccess":"\tFailure"));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM