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    
017    package org.jetbrains.k2js.config;
018    
019    import com.google.common.collect.Lists;
020    import com.intellij.openapi.diagnostic.Logger;
021    import com.intellij.openapi.project.Project;
022    import com.intellij.openapi.util.Key;
023    import com.intellij.openapi.util.io.FileUtil;
024    import com.intellij.openapi.util.text.StringUtil;
025    import com.intellij.openapi.vfs.*;
026    import com.intellij.psi.PsiFile;
027    import com.intellij.psi.PsiManager;
028    import org.jetbrains.annotations.NotNull;
029    import org.jetbrains.jet.lang.psi.JetFile;
030    
031    import java.io.IOException;
032    import java.io.InputStream;
033    import java.util.ArrayList;
034    import java.util.Collections;
035    import java.util.Enumeration;
036    import java.util.List;
037    import java.util.zip.ZipEntry;
038    import java.util.zip.ZipFile;
039    
040    import static org.jetbrains.jet.lang.psi.PsiPackage.JetPsiFactory;
041    
042    public class LibrarySourcesConfig extends Config {
043        @NotNull
044        public static final Key<String> EXTERNAL_MODULE_NAME = Key.create("externalModule");
045        @NotNull
046        public static final String UNKNOWN_EXTERNAL_MODULE_NAME = "<unknown>";
047    
048        @NotNull
049        private static final Logger LOG = Logger.getInstance("#org.jetbrains.k2js.config.LibrarySourcesConfig");
050    
051        @NotNull
052        private final List<String> files;
053    
054        public LibrarySourcesConfig(
055                @NotNull Project project,
056                @NotNull String moduleId,
057                @NotNull List<String> files,
058                @NotNull EcmaVersion ecmaVersion,
059                boolean sourcemap
060        ) {
061            super(project, moduleId, ecmaVersion, sourcemap);
062            this.files = files;
063        }
064    
065        @NotNull
066        @Override
067        protected List<JetFile> generateLibFiles() {
068            if (files.isEmpty()) {
069                return Collections.emptyList();
070            }
071    
072            List<JetFile> jetFiles = new ArrayList<JetFile>();
073            String moduleName = UNKNOWN_EXTERNAL_MODULE_NAME;
074            VirtualFileSystem fileSystem = VirtualFileManager.getInstance().getFileSystem(StandardFileSystems.FILE_PROTOCOL);
075            PsiManager psiManager = PsiManager.getInstance(getProject());
076    
077            for (String path : files) {
078                if (path.charAt(0) == '@') {
079                    moduleName = path.substring(1);
080                }
081                else if (path.endsWith(".jar") || path.endsWith(".zip")) {
082                    try {
083                        jetFiles.addAll(readZip(path));
084                    }
085                    catch (IOException e) {
086                        LOG.error(e);
087                    }
088                }
089                else {
090                    VirtualFile file = fileSystem.findFileByPath(path);
091                    if (file == null) {
092                        LOG.error("File '" + path + "not found.'");
093                    }
094                    else if (file.isDirectory()) {
095                        JetFileCollector jetFileCollector = new JetFileCollector(jetFiles, moduleName, psiManager);
096                        VfsUtilCore.visitChildrenRecursively(file, jetFileCollector);
097                    }
098                    else {
099                        jetFiles.add(getJetFileByVirtualFile(file, moduleName, psiManager));
100                    }
101                }
102            }
103    
104            return jetFiles;
105        }
106    
107        private List<JetFile> readZip(String file) throws IOException {
108            ZipFile zipFile = new ZipFile(file);
109            try {
110                return traverseArchive(zipFile);
111            }
112            finally {
113                zipFile.close();
114            }
115        }
116    
117        @NotNull
118        private List<JetFile> traverseArchive(@NotNull ZipFile file) throws IOException {
119            List<JetFile> result = Lists.newArrayList();
120            Enumeration<? extends ZipEntry> zipEntries = file.entries();
121            while (zipEntries.hasMoreElements()) {
122                ZipEntry entry = zipEntries.nextElement();
123                if (!entry.isDirectory() && entry.getName().endsWith(".kt")) {
124                    InputStream stream = file.getInputStream(entry);
125                    String text = StringUtil.convertLineSeparators(FileUtil.loadTextAndClose(stream));
126                    JetFile jetFile = JetPsiFactory(getProject()).createFile(entry.getName(), text);
127                    jetFile.putUserData(EXTERNAL_MODULE_NAME, UNKNOWN_EXTERNAL_MODULE_NAME);
128                    result.add(jetFile);
129                }
130            }
131            return result;
132        }
133    
134        private static JetFile getJetFileByVirtualFile(VirtualFile file, String moduleName, PsiManager psiManager) {
135            PsiFile psiFile = psiManager.findFile(file);
136            assert psiFile != null;
137            psiFile.putUserData(EXTERNAL_MODULE_NAME, moduleName);
138            return (JetFile) psiFile;
139        }
140    
141        private static class JetFileCollector extends VirtualFileVisitor {
142            private final List<JetFile> jetFiles;
143            private final String moduleName;
144            private final PsiManager psiManager;
145    
146            private JetFileCollector(List<JetFile> files, String name, PsiManager manager) {
147                moduleName = name;
148                psiManager = manager;
149                jetFiles = files;
150            }
151    
152            @Override
153            public boolean visitFile(@NotNull VirtualFile file) {
154                if (file.getName().endsWith(".kt")) {
155                    jetFiles.add(getJetFileByVirtualFile(file, moduleName, psiManager));
156                    return false;
157                }
158                return true;
159            }
160        }
161    }