<commit_before>/*
 * Copyright 2000-2012 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jetbrains.jps.cabal;


import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.ModuleChunk;
import org.jetbrains.jps.builders.DirtyFilesHolder;
import org.jetbrains.jps.builders.java.JavaSourceRootDescriptor;
import org.jetbrains.jps.incremental.*;
import org.jetbrains.jps.incremental.messages.BuildMessage;
import org.jetbrains.jps.incremental.messages.CompilerMessage;
import org.jetbrains.jps.incremental.messages.ProgressMessage;
import org.jetbrains.jps.model.module.JpsModule;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class CabalBuilder extends ModuleLevelBuilder {


    public CabalBuilder() {
        super(BuilderCategory.TRANSLATOR);
    }


    public ExitCode build(final CompileContext context,
                          final ModuleChunk chunk,
                          final DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget> dirtyFilesHolder,
                          final OutputConsumer outputConsumer) throws ProjectBuildException {
        try {
            for (JpsModule module : chunk.getModules()) {
                File cabalFile = getCabalFile(module);
                if (cabalFile == null) {
                    //context.processMessage(new CompilerMessage("cabal", BuildMessage.Kind.ERROR,
                    //        "Can't find cabal file in " + getContentRootPath(module)));
                    continue;
                }
                CabalJspInterface cabal = new CabalJspInterface(cabalFile);

                if (runConfigure(context, module, cabal)) return ExitCode.ABORT;
                if (runBuild(context, module, cabal)) return ExitCode.ABORT;
            }
            return ExitCode.OK;
        } catch (InterruptedException e) {
            e.printStackTrace();
            context.processMessage(new CompilerMessage("cabal", BuildMessage.Kind.ERROR, e.getMessage()));
        } catch (IOException e) {
            e.printStackTrace();
            context.processMessage(new CompilerMessage("cabal", BuildMessage.Kind.ERROR, e.getMessage()));
        }
        return ExitCode.ABORT;
    }

    private boolean runBuild(CompileContext context, JpsModule module, CabalJspInterface cabal) throws IOException, InterruptedException {
        context.processMessage(new ProgressMessage("cabal build"));
        context.processMessage(new CompilerMessage("ghc", BuildMessage.Kind.INFO, "Start build"));
        Process buildProcess = cabal.build();
        processOut(context, buildProcess, module);

        if (buildProcess.waitFor() != 0) {
            context.processMessage(new CompilerMessage("cabal", BuildMessage.Kind.ERROR, "build errors."));
            return true;
        }
        return false;
    }

    private boolean runConfigure(CompileContext context, JpsModule module, CabalJspInterface cabal) throws IOException, InterruptedException {
        context.processMessage(new CompilerMessage("cabal", BuildMessage.Kind.INFO, "Start configure"));

        Process configureProcess = cabal.configure();

        processOut(context, configureProcess, module);

        if (configureProcess.waitFor() != 0) {
            context.processMessage(new CompilerMessage(
                    "cabal",
                    BuildMessage.Kind.ERROR,
                    "configure failed."));
            return true;
        }
        return false;
    }

    private void processOut(CompileContext context, Process process, JpsModule module) throws IOException {
        Iterator<String> processOut = collectOutput(process);

        while (processOut.hasNext()) {
            String line = processOut.next();
            String warningPrefix = "Warning: ";
            Matcher matcher = Pattern.compile("(.*):(\\d+):(\\d+):(.*)").matcher(line);
            if (line.startsWith(warningPrefix)) {
                String text = line.substring(warningPrefix.length()) + "\n" + processOut.next();
                context.processMessage(new CompilerMessage("cabal", BuildMessage.Kind.WARNING, text));
            } else if (matcher.find()) {
                String file = matcher.group(1);
                long lineNum = Long.parseLong(matcher.group(2));
                long colNum = Long.parseLong(matcher.group(3));
                String msg = matcher.group(4);
                while (processOut.hasNext()) {
                    String msgLine = processOut.next();
                    msg += msgLine + "\n";
                    if (msgLine.trim().length() == 0) {
                        break;
                    }
                }

                String sourcePath = getContentRootPath(module) + "/" + file.replace('\\', '/');
                BuildMessage.Kind kind;
                if (msg.trim().startsWith("warning")) {
                    kind = BuildMessage.Kind.WARNING;
                } else {
                    kind = BuildMessage.Kind.ERROR;
                }

                context.processMessage(new CompilerMessage(
                        "ghc",
                        kind,
                        msg.trim(),
                        sourcePath,
                        -1L, -1L, -1L,
                        lineNum, colNum));
            } else {
                context.processMessage(new CompilerMessage("cabal", BuildMessage.Kind.INFO, line));
            }
        }
    }

    private Iterator<String> collectOutput(Process process) throws IOException {
        final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        return new Iterator<String>() {

            String line = null;
<commit_msg>Fix warning parsing on compilation<commit_after>/*
 * Copyright 2000-2012 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jetbrains.jps.cabal;


import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.ModuleChunk;
import org.jetbrains.jps.builders.DirtyFilesHolder;
import org.jetbrains.jps.builders.java.JavaSourceRootDescriptor;
import org.jetbrains.jps.incremental.*;
import org.jetbrains.jps.incremental.messages.BuildMessage;
import org.jetbrains.jps.incremental.messages.CompilerMessage;
import org.jetbrains.jps.incremental.messages.ProgressMessage;
import org.jetbrains.jps.model.module.JpsModule;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class CabalBuilder extends ModuleLevelBuilder {


    public CabalBuilder() {
        super(BuilderCategory.TRANSLATOR);
    }


    public ExitCode build(final CompileContext context,
                          final ModuleChunk chunk,
                          final DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget> dirtyFilesHolder,
                          final OutputConsumer outputConsumer) throws ProjectBuildException {
        try {
            for (JpsModule module : chunk.getModules()) {
                File cabalFile = getCabalFile(module);
                if (cabalFile == null) {
                    //context.processMessage(new CompilerMessage("cabal", BuildMessage.Kind.ERROR,
                    //        "Can't find cabal file in " + getContentRootPath(module)));
                    continue;
                }
                CabalJspInterface cabal = new CabalJspInterface(cabalFile);

                if (runConfigure(context, module, cabal)) return ExitCode.ABORT;
                if (runBuild(context, module, cabal)) return ExitCode.ABORT;
            }
            return ExitCode.OK;
        } catch (InterruptedException e) {
            e.printStackTrace();
            context.processMessage(new CompilerMessage("cabal", BuildMessage.Kind.ERROR, e.getMessage()));
        } catch (IOException e) {
            e.printStackTrace();
            context.processMessage(new CompilerMessage("cabal", BuildMessage.Kind.ERROR, e.getMessage()));
        }
        return ExitCode.ABORT;
    }

    private boolean runBuild(CompileContext context, JpsModule module, CabalJspInterface cabal) throws IOException, InterruptedException {
        context.processMessage(new ProgressMessage("cabal build"));
        context.processMessage(new CompilerMessage("ghc", BuildMessage.Kind.INFO, "Start build"));
        Process buildProcess = cabal.build();
        processOut(context, buildProcess, module);

        if (buildProcess.waitFor() != 0) {
            context.processMessage(new CompilerMessage("cabal", BuildMessage.Kind.ERROR, "build errors."));
            return true;
        }
        return false;
    }

    private boolean runConfigure(CompileContext context, JpsModule module, CabalJspInterface cabal) throws IOException, InterruptedException {
        context.processMessage(new CompilerMessage("cabal", BuildMessage.Kind.INFO, "Start configure"));

        Process configureProcess = cabal.configure();

        processOut(context, configureProcess, module);

        if (configureProcess.waitFor() != 0) {
            context.processMessage(new CompilerMessage(
                    "cabal",
                    BuildMessage.Kind.ERROR,
                    "configure failed."));
            return true;
        }
        return false;
    }

    private void processOut(CompileContext context, Process process, JpsModule module) throws IOException {
        Iterator<String> processOut = collectOutput(process);

        while (processOut.hasNext()) {
            String line = processOut.next();
            String warningPrefix = "Warning: ";
            Matcher matcher = Pattern.compile("(.*):(\\d+):(\\d+):(.*)").matcher(line);
            if (line.startsWith(warningPrefix)) {
                String text = line.substring(warningPrefix.length()) + "\n" + processOut.next();
                context.processMessage(new CompilerMessage("cabal", BuildMessage.Kind.WARNING, text));
            } else if (matcher.find()) {
                String file = matcher.group(1);
                long lineNum = Long.parseLong(matcher.group(2));
                long colNum = Long.parseLong(matcher.group(3));
                String msg = matcher.group(4);
                while (processOut.hasNext()) {
                    String msgLine = processOut.next();

                    if (msgLine.endsWith("warning generated.")) {
                        break;
                    }
                    if (msgLine.trim().length() == 0) {
                        break;
                    }
                    msg += msgLine + "\n";
                }

                String sourcePath = getContentRootPath(module) + "/" + file.replace('\\', '/');
                BuildMessage.Kind kind;
                if (msg.trim().startsWith("warning")) {
                    kind = BuildMessage.Kind.WARNING;
                } else {
                    kind = BuildMessage.Kind.ERROR;
                }

                context.processMessage(new CompilerMessage(
                        "ghc",
                        kind,
                        msg.trim(),
                        sourcePath,
                        -1L, -1L, -1L,
                        lineNum, colNum));
            } else {
                context.processMessage(new CompilerMessage("cabal", BuildMessage.Kind.INFO, line));
            }
        }
    }

    private Iterator<String> collectOutput(Process process) throws IOException {
        final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        return new Iterator<String>() {

            String line = null;

{'fraction_non_alphanumeric': 0.10054788178100162, 'fraction_numerical': 0.003395323713249479, 'mean_word_length': 2.2111000991080276, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6268602', 'n_tokens_mistral': 3392, 'n_tokens_neox': 3208, 'n_words': 776}