package hudson.plugins.emailext.plugins.content;

import hudson.EnvVars;
import hudson.model.AbstractBuild;
import hudson.model.TaskListener;
import hudson.plugins.emailext.plugins.EmailToken;
import java.io.IOException;
import org.codehaus.plexus.util.StringUtils;
import org.jenkinsci.plugins.tokenmacro.DataBoundTokenMacro;
import org.jenkinsci.plugins.tokenmacro.MacroEvaluationException;


/**
 * Content token that includes a file in the workspace.
 *
 * @author Kohsuke Kawaguchi
 */
@EmailToken
public class WorkspaceFileContent extends DataBoundTokenMacro  {
    @Parameter(required=true)
    public String path = "";
    @Parameter
    public String fileNotFoundMessage = "";

    public static final String MACRO_NAME = "FILE";

    @Override
    public boolean acceptsMacroName(String macroName) {
        return macroName.equals(MACRO_NAME);
    }

    @Override
    public String evaluate(AbstractBuild<?, ?> context, TaskListener listener, String macroName)
            throws MacroEvaluationException, IOException, InterruptedException {
        if(!context.getWorkspace().child(path).exists()) {
            return StringUtils.isNotBlank(fileNotFoundMessage) ? String.format(fileNotFoundMessage, path) : "ERROR: File '" + path + "' does not exist";
        }
        
        // do some environment variable substitution
        try {
            EnvVars env = context.getEnvironment(listener);
            path = env.expand(path);
        } catch(Exception e) {
            listener.error("Error retrieving environment");
        }

        try {
            return context.getWorkspace().child(path).readToString();
        } catch (IOException e) {
            return "ERROR: File '" + path + "' could not be read";
        }
    }

    @Override
    public boolean hasNestedContent() {
        return true;
    }
}

@@ -676,18 +676,54 @@
 sage = %22
-%22;
+ERROR: File '%25s' does not exist%22;%0A    
 %0A%0A    pu
@@ -1086,231 +1086,8 @@
 on %7B
-%0A        if(!context.getWorkspace().child(path).exists()) %7B%0A            return StringUtils.isNotBlank(fileNotFoundMessage) ? String.format(fileNotFoundMessage, path) : %22ERROR: File '%22 + path + %22' does not exist%22;%0A        %7D%0A
     
@@ -1351,24 +1351,163 @@
 );%0A        %7D
+%0A        %0A        if(!context.getWorkspace().child(path).exists()) %7B%0A            return String.format(fileNotFoundMessage, path);%0A        %7D
 %0A%0A        tr

Fix JENKINS-20982