001/*
002 * Copyright 2010-2013 JetBrains s.r.o.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.jetbrains.jet.cli.common.messages;
018
019import com.intellij.openapi.util.text.StringUtil;
020import com.intellij.util.containers.ContainerUtil;
021import org.jetbrains.annotations.NotNull;
022import org.jetbrains.annotations.Nullable;
023
024import java.io.File;
025import java.util.Collection;
026
027public class OutputMessageUtil {
028    private static final String SOURCE_FILES_PREFIX = "Sources:";
029    private static final String OUTPUT_FILES_PREFIX = "Output:";
030
031    public static String formatOutputMessage(Collection<File> sourceFiles, File outputFile) {
032        return OUTPUT_FILES_PREFIX + "\n" + outputFile.getPath() + "\n" +
033               SOURCE_FILES_PREFIX + "\n" + StringUtil.join(sourceFiles, "\n");
034    }
035
036    @Nullable
037    public static Output parseOutputMessage(@NotNull String message) {
038        String[] strings = message.split("\n");
039
040        // Must have at least one line per prefix
041        if (strings.length <= 2) return null;
042
043        if (!OUTPUT_FILES_PREFIX.equals(strings[0])) return null;
044
045        if (SOURCE_FILES_PREFIX.equals(strings[1])) {
046            // Output:
047            // Sources:
048            // ...
049            return new Output(parseSourceFiles(strings, 2), null);
050        }
051        else {
052            File outputFile = new File(strings[1]);
053
054            if (!SOURCE_FILES_PREFIX.equals(strings[2])) return null;
055
056            return new Output(parseSourceFiles(strings, 3), outputFile);
057        }
058    }
059
060    private static Collection<File> parseSourceFiles(String[] strings, int start) {
061        Collection<File> sourceFiles = ContainerUtil.newArrayList();
062        for (int i = start; i < strings.length; i++) {
063            sourceFiles.add(new File(strings[i]));
064        }
065        return sourceFiles;
066    }
067
068    public static class Output {
069        @NotNull
070        public final Collection<File> sourceFiles;
071        @Nullable
072        public final File outputFile;
073
074        public Output(@NotNull Collection<File> sourceFiles, @Nullable File outputFile) {
075            this.sourceFiles = sourceFiles;
076            this.outputFile = outputFile;
077        }
078    }
079}