private static void transformTestFile(@NotNull Project project, int toSubtaskIndex, VirtualFile taskDir) { String subtaskTestFileName = getTestFileName(project, toSubtaskIndex); if (subtaskTestFileName == null) { return; } String nameWithoutExtension = FileUtil.getNameWithoutExtension(subtaskTestFileName); String extension = FileUtilRt.getExtension(subtaskTestFileName); VirtualFile subtaskTestFile = taskDir.findChild(nameWithoutExtension + ".txt"); if (subtaskTestFile != null) { ApplicationManager.getApplication().runWriteAction(() -> { try { subtaskTestFile.rename(project, nameWithoutExtension + "." + extension); } catch (IOException e) { LOG.error(e); } }); } }
private static void transformFiles(Course course, Project project) { List<VirtualFile> files = getAllAnswerTaskFiles(course, project); for (VirtualFile answerFile : files) { ApplicationManager.getApplication().runWriteAction(() -> { String answerName = answerFile.getName(); String nameWithoutExtension = FileUtil.getNameWithoutExtension(answerName); String name = FileUtil.getNameWithoutExtension(nameWithoutExtension) + "." + FileUtilRt.getExtension(answerName); VirtualFile parent = answerFile.getParent(); VirtualFile file = parent.findChild(name); try { if (file != null) { file.delete(CCProjectComponent.class); } VirtualFile windowsDescrFile = parent.findChild(FileUtil.getNameWithoutExtension(name) + EduNames.WINDOWS_POSTFIX); if (windowsDescrFile != null) { windowsDescrFile.delete(CCProjectComponent.class); } answerFile.rename(CCProjectComponent.class, name); } catch (IOException e) { LOG.error(e); } }); } }
private static List<VirtualFile> getAllAnswerTaskFiles(@NotNull Course course, @NotNull Project project) { List<VirtualFile> result = new ArrayList<>(); for (Lesson lesson : course.getLessons()) { for (Task task : lesson.getTaskList()) { for (Map.Entry<String, TaskFile> entry : task.getTaskFiles().entrySet()) { String name = entry.getKey(); String answerName = FileUtil.getNameWithoutExtension(name) + CCUtils.ANSWER_EXTENSION_DOTTED + FileUtilRt.getExtension(name); String taskPath = FileUtil.join(project.getBasePath(), EduNames.LESSON + lesson.getIndex(), EduNames.TASK + task.getIndex()); VirtualFile taskFile = LocalFileSystem.getInstance().findFileByPath(FileUtil.join(taskPath, answerName)); if (taskFile == null) { taskFile = LocalFileSystem.getInstance().findFileByPath(FileUtil.join(taskPath, EduNames.SRC, answerName)); } if (taskFile != null) { result.add(taskFile); } } } } return result; }
@Nullable @Override public AbstractTreeNode modifyChildNode(AbstractTreeNode childNode) { AbstractTreeNode node = super.modifyChildNode(childNode); if (node != null) { return node; } if (childNode instanceof PsiFileNode) { VirtualFile virtualFile = ((PsiFileNode)childNode).getVirtualFile(); if (virtualFile == null) { return null; } if (FileUtilRt.getExtension(virtualFile.getName()).equals("iml")) { return null; } return new CCStudentInvisibleFileNode(myProject, ((PsiFileNode)childNode).getValue(), myViewSettings); } return null; }
@Nullable @Override protected VirtualFile getTestsFile() { String testFileName = EduJavaPluginConfigurator.TEST_JAVA; if (myTask instanceof TaskWithSubtasks) { int activeSubtaskIndex = ((TaskWithSubtasks) myTask).getActiveSubtaskIndex(); testFileName = FileUtil.getNameWithoutExtension(testFileName) + EduNames.SUBTASK_MARKER + activeSubtaskIndex + "." + FileUtilRt.getExtension(EduJavaPluginConfigurator.TEST_JAVA); } VirtualFile taskDir = myTask.getTaskDir(myProject); if (taskDir == null) { return null; } VirtualFile srcDir = taskDir.findChild(EduNames.SRC); if (srcDir != null) { taskDir = srcDir; } VirtualFile virtualFile = taskDir.findChild(testFileName); if (virtualFile != null) { return virtualFile; } return null; }
public static File copyClass(final String targetPath, @NonNls final String className, final boolean deleteOnExit) throws IOException{ final File targetDir = new File(targetPath).getAbsoluteFile(); final File file = new File(targetDir, className + ".class"); FileUtil.createParentDirs(file); if (deleteOnExit) { for (File f = file; f != null && !FileUtil.filesEqual(f, targetDir); f = FileUtilRt.getParentFile(f)) { f.deleteOnExit(); } } @NonNls final String resourceName = "/" + className + ".class"; final InputStream stream = CopyResourcesUtil.class.getResourceAsStream(resourceName); if (stream == null) { throw new IOException("cannot load " + resourceName); } return copyStreamToFile(stream, file); }
@Override public Collection<BuildTarget<?>> getTargetsByOutputFile(@NotNull File file) { File current = file; Collection<BuildTarget<?>> result = null; while (current != null) { List<BuildTarget<?>> targets = myOutputToTargets.get(current); if (targets != null) { if (result == null) { result = targets; } else { result = new ArrayList<BuildTarget<?>>(result); result.addAll(targets); } } current = FileUtilRt.getParentFile(current); } return result != null ? result : Collections.<BuildTarget<?>>emptyList(); }
@Override @Nullable public String deduplicate(@NotNull Parameter parameter, @Nullable String value) { if (StringUtil.isEmpty(value) || !parameter.constraints.contains(Parameter.Constraint.UNIQUE)) { return value; } String suggested = value; String extension = FileUtilRt.getExtension(value); boolean hasExtension = !extension.isEmpty(); int extensionOffset = value.length() - extension.length(); //noinspection ForLoopThatDoesntUseLoopVariable for (int i = 2; !parameter.uniquenessSatisfied(project, module, provider, packageName, suggested); i++) { if (hasExtension) { suggested = value.substring(0, extensionOffset) + i + value.substring(extensionOffset); } else { suggested = value + i; } } return suggested; }
@Nullable @Override protected PsiType getClosureParameterType(GrClosableBlock closure, int index) { PsiFile file = closure.getContainingFile(); if (file == null || !FileUtilRt.extensionEquals(file.getName(), GradleConstants.EXTENSION)) return null; PsiType psiType = super.getClosureParameterType(closure, index); if (psiType instanceof PsiWildcardType) { PsiWildcardType wildcardType = (PsiWildcardType)psiType; if (wildcardType.isSuper() && wildcardType.getBound() != null && wildcardType.getBound().equalsToText(GradleCommonClassNames.GRADLE_API_SOURCE_SET)) { return wildcardType.getBound(); } if (wildcardType.isSuper() && wildcardType.getBound() != null && wildcardType.getBound().equalsToText(GradleCommonClassNames.GRADLE_API_DISTRIBUTION)) { return wildcardType.getBound(); } } return null; }
@Override public boolean isExcluded(File file) { if (myFiles.contains(file)) { return true; } if (!myDirectories.isEmpty() || !myRecursivelyExcludedDirectories.isEmpty()) { // optimization File parent = FileUtilRt.getParentFile(file); if (myDirectories.contains(parent)) { return true; } while (parent != null) { if (myRecursivelyExcludedDirectories.contains(parent)) { return true; } parent = FileUtilRt.getParentFile(parent); } } return false; }
private static void collectArchives(File file, boolean recursively, List<String> result) { final File[] children = file.listFiles(); if (children != null) { for (File child : children) { final String extension = FileUtilRt.getExtension(child.getName()); if (child.isDirectory()) { if (recursively) { collectArchives(child, recursively, result); } } // todo [nik] get list of extensions mapped to Archive file type from IDE settings else if (AR_EXTENSIONS.contains(extension)) { result.add(JpsPathUtil.getLibraryRootUrl(child)); } } } }
@Nullable @Override public OCLanguageKind getLanguageByExtension(Project project, String name) { if (Blaze.isBlazeProject(project)) { String extension = FileUtilRt.getExtension(name); if (CFileExtensions.C_FILE_EXTENSIONS.contains(extension)) { return OCLanguageKind.C; } if (CFileExtensions.CXX_FILE_EXTENSIONS.contains(extension)) { return OCLanguageKind.CPP; } if (CFileExtensions.CXX_ONLY_HEADER_EXTENSIONS.contains(extension)) { return OCLanguageKind.CPP; } } return null; }
private void addPathPatterns(MyExecutor executor, JpsSdk<JpsSimpleElement<JpsAndroidSdkProperties>> androidSdk) { final String tempDirectory = FileUtilRt.getTempDirectory(); executor.addPathPrefix("PROJECT_DIR", getOrCreateProjectDir().getPath()); executor.addPathPrefix("ANDROID_SDK_DIR", androidSdk.getHomePath()); executor.addPathPrefix("DATA_STORAGE_ROOT", myDataStorageRoot.getPath()); executor.addRegexPathPatternPrefix("AAPT_OUTPUT_TMP", FileUtil.toSystemIndependentName(tempDirectory) + "/android_apt_output\\d*tmp"); executor.addRegexPathPatternPrefix("COMBINED_ASSETS_TMP", FileUtil.toSystemIndependentName(tempDirectory) + "/android_combined_assets\\d*tmp"); executor.addRegexPathPatternPrefix("COMBINED_RESOURCES_TMP", FileUtil.toSystemIndependentName(tempDirectory) + "/android_combined_resources\\d*tmp"); executor.addRegexPathPatternPrefix("CLASSPATH_TMP", FileUtil.toSystemIndependentName(tempDirectory) + "/classpath\\d*\\.jar"); executor.addRegexPathPattern("JAVA_PATH", ".*/java"); executor.addRegexPathPattern("IDEA_RT_PATH", ".*/idea_rt.jar"); executor.addRegexPathPattern("PROGUARD_INPUT_JAR", ".*/proguard_input\\S*\\.jar"); // for running on buildserver executor.addRegexPathPattern("IDEA_RT_PATH", ".*/production/java-runtime"); AndroidBuildTestingManager.startBuildTesting(executor); }
private static void walk(File root, MultiMap<Couple<Integer>, String> dimToPath, File file) throws IOException { if (file.isDirectory()) { for (File child : file.listFiles()) { walk(root, dimToPath, child); } } else { if (IMAGE_EXTENSIONS.contains(FileUtilRt.getExtension(file.getName()))) { String relativePath = file.getAbsolutePath().substring(root.getAbsolutePath().length() + 1); Image image = loadImage(file); File target; int width = image.getWidth(null); int height = image.getHeight(null); if (height != width && (height > 100 || width > 100)) { target = new File("/Users/max/images/other", relativePath); } else { target = new File("/Users/max/images/icons", relativePath); dimToPath.putValue(new Couple<Integer>(width, height), relativePath); } FileUtil.copy(file, target); } } }
private static boolean containsDependencyOnApklibFile(@NotNull LibraryOrderEntry libraryOrderEntry, @NotNull IdeModifiableModelsProvider modelsProvider) { final Library library = libraryOrderEntry.getLibrary(); if (library == null) { return false; } final Library.ModifiableModel libraryModel = modelsProvider.getModifiableLibraryModel(library); final String[] urls = libraryModel.getUrls(OrderRootType.CLASSES); for (String url : urls) { final String fileName = PathUtil.getFileName(PathUtil.toPresentableUrl(url)); if (FileUtilRt.extensionEquals(fileName, "apklib")) { return true; } } return false; }
@NotNull @Override public DirectoryProcessingResult detectRoots(@NotNull File dir, @NotNull File[] children, @NotNull File base, @NotNull List<DetectedProjectRoot> result) { final String fileExtension = getFileExtension(); for (File child : children) { if (child.isFile()) { if (FileUtilRt.extensionEquals(child.getName(), fileExtension)) { Pair<File, String> root = CommonSourceRootDetectionUtil.IO_FILE.suggestRootForFileWithPackageStatement(child, base, getPackageNameFetcher(), true); if (root != null) { result.add(new JavaModuleSourceRoot(root.getFirst(), root.getSecond(), getLanguageName())); return DirectoryProcessingResult.skipChildrenAndParentsUpTo(root.getFirst()); } else { return DirectoryProcessingResult.SKIP_CHILDREN; } } } } return DirectoryProcessingResult.PROCESS_CHILDREN; }
@NotNull @Override public List<String> getAdditionalParameters() { if (myCommandLineOptions == null) { if (myUseCustomProfile && myUserDataDirectoryPath != null) { return Collections.singletonList(USER_DATA_DIR_ARG + FileUtilRt.toSystemDependentName(myUserDataDirectoryPath)); } else { return Collections.emptyList(); } } List<String> cliOptions = ParametersListUtil.parse(myCommandLineOptions); if (myUseCustomProfile && myUserDataDirectoryPath != null) { cliOptions.add(USER_DATA_DIR_ARG + FileUtilRt.toSystemDependentName(myUserDataDirectoryPath)); } return cliOptions; }
public static void collectNativeLibraries(@NotNull File file, @NotNull List<File> result, boolean debugBuild) { if (!file.isDirectory()) { // some users store jars and *.so libs in the same directory. Do not pack JARs to APKs "lib" folder! if (FileUtilRt.extensionEquals(file.getName(), EXT_NATIVE_LIB) || (debugBuild && !(FileUtilRt.extensionEquals(file.getName(), "jar")))) { result.add(file); } } else if (JavaResourceFilter.checkFolderForPackaging(file.getName())) { final File[] children = file.listFiles(); if (children != null) { for (File child : children) { collectNativeLibraries(child, result, debugBuild); } } } }
@Override public void update(@NotNull AnActionEvent e) { final Project project = getEventProject(e); boolean visible = false; if (project != null && ModuleManager.getInstance(project).getModules().length > 0) { final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); for (VirtualFile root : getRoots(e)) { if (!root.isInLocalFileSystem() && FileUtilRt.extensionEquals(root.getName(), "jar") && !fileIndex.isInLibraryClasses(root)) { visible = true; break; } } } Presentation presentation = e.getPresentation(); presentation.setVisible(visible); presentation.setEnabled(visible); }
private static String readProjectName(@NotNull String path) { final File file = new File(path); if (file.isDirectory()) { final File nameFile = new File(new File(path, Project.DIRECTORY_STORE_FOLDER), ProjectImpl.NAME_FILE); if (nameFile.exists()) { try { final BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(nameFile), CharsetToolkit.UTF8_CHARSET)); try { String name = in.readLine(); if (!StringUtil.isEmpty(name)) { return name.trim(); } } finally { in.close(); } } catch (IOException ignored) { } } return file.getName(); } else { return FileUtilRt.getNameWithoutExtension(file.getName()); } }
@Nullable public static JarMemoryLoader load(ZipFile zipFile, URL baseUrl, Map<Resource.Attribute, String> attributes) throws IOException { Enumeration<? extends ZipEntry> entries = zipFile.entries(); if (!entries.hasMoreElements()) return null; ZipEntry sizeEntry = entries.nextElement(); if (sizeEntry == null || !sizeEntry.getName().equals(SIZE_ENTRY)) return null; byte[] bytes = FileUtilRt.loadBytes(zipFile.getInputStream(sizeEntry), 2); int size = ((bytes[1] & 0xFF) << 8) + (bytes[0] & 0xFF); JarMemoryLoader loader = new JarMemoryLoader(); for (int i = 0; i < size && entries.hasMoreElements(); i++) { ZipEntry entry = entries.nextElement(); MemoryResource resource = MemoryResource.load(baseUrl, zipFile, entry, attributes); loader.myResources.put(entry.getName(), resource); } return loader; }
private static boolean filenameMatchesPrefixOrType(final String fileName, final String prefix, final FileType[] suitableFileTypes, final int invocationCount) { final boolean prefixMatched = prefix.length() == 0 || StringUtil.startsWithIgnoreCase(fileName, prefix); if (prefixMatched && (suitableFileTypes.length == 0 || invocationCount > 2)) return true; if (prefixMatched) { final String extension = FileUtilRt.getExtension(fileName); if (extension.length() == 0) return false; for (final FileType fileType : suitableFileTypes) { for (final FileNameMatcher matcher : FileTypeManager.getInstance().getAssociations(fileType)) { if (FileNameMatcherEx.acceptsCharSequence(matcher, fileName)) return true; } } } return false; }
/** * Gets working copy internal format. Works for 1.7 and 1.8. * * @param path * @return */ @NotNull public static WorkingCopyFormat getFormat(final File path) { WorkingCopyFormat result = null; File dbFile = resolveDatabase(path); if (dbFile != null) { result = FileUtilRt.doIOOperation(new WorkingCopyFormatOperation(dbFile)); if (result == null) { notifyDatabaseError(); } } return result != null ? result : WorkingCopyFormat.UNKNOWN; }
public TestStateStorage(Project project) { myFile = new File(getTestHistoryRoot(project).getPath() + "/testStateMap"); FileUtilRt.createParentDirs(myFile); try { myMap = initializeMap(); } catch (IOException e) { LOG.error(e); } myMapFlusher = FlushingDaemon.everyFiveSeconds(new Runnable() { @Override public void run() { flushMap(); } }); Disposer.register(project, this); }
private void updateExtensionsCombo() { final Object source = getSource(); if (source instanceof LanguageFileType) { final List<String> extensions = getAllExtensions((LanguageFileType)source); if (extensions.size() > 1) { final ExtensionComparator comp = new ExtensionComparator(extensions.get(0)); Collections.sort(extensions, comp); final SortedComboBoxModel<String> model = new SortedComboBoxModel<String>(comp); model.setAll(extensions); myExtensionComboBox.setModel(model); myExtensionComboBox.setVisible(true); myExtensionLabel.setVisible(true); String fileExt = myCurrentFile != null ? FileUtilRt.getExtension(myCurrentFile.getName()) : ""; if (fileExt.length() > 0 && extensions.contains(fileExt)) { myExtensionComboBox.setSelectedItem(fileExt); return; } myExtensionComboBox.setSelectedIndex(0); return; } } myExtensionComboBox.setVisible(false); myExtensionLabel.setVisible(false); }
/** Whether the editor notification should be shown for this file type. */ private static boolean supportedFileType(File file) { LanguageClass languageClass = LanguageClass.fromExtension(FileUtilRt.getExtension(file.getName()).toLowerCase()); if (languageClass != null && !supportedLanguage(languageClass)) { return false; } FileType type = FileTypeManager.getInstance().getFileTypeByFileName(file.getName()); for (Class<? extends FileType> clazz : IGNORED_FILE_TYPES) { if (clazz.isInstance(type)) { return false; } } return true; }
@NotNull @Override public DirectoryProcessingResult detectRoots(@NotNull File dir, @NotNull File[] children, @NotNull File base, @NotNull List<DetectedProjectRoot> result) { LOG.info("Detecting roots under " + dir); for (File child : children) { final String name = child.getName(); if (FileUtilRt.extensionEquals(name, "py")) { LOG.info("Found Python file " + child.getPath()); result.add(new DetectedContentRoot(dir, "Python", PythonModuleTypeBase.getInstance(), WebModuleType.getInstance())); return DirectoryProcessingResult.SKIP_CHILDREN; } if ("node_modules".equals(name)) { return DirectoryProcessingResult.SKIP_CHILDREN; } } return DirectoryProcessingResult.PROCESS_CHILDREN; }
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed") private static Control[] loadControls() { Document document; try { // use temporary bytes stream because otherwise inputStreamSkippingBOM will fail // on ZipFileInputStream used in jar files final InputStream stream = HTMLControls.class.getResourceAsStream("HtmlControls.xml"); final byte[] bytes = FileUtilRt.loadBytes(stream); stream.close(); final UnsyncByteArrayInputStream bytesStream = new UnsyncByteArrayInputStream(bytes); document = JDOMUtil.loadDocument(CharsetToolkit.inputStreamSkippingBOM(bytesStream)); bytesStream.close(); } catch (Exception e) { LOG.error(e); return new Control[0]; } if (!document.getRootElement().getName().equals("htmlControls")) { LOG.error("HTMLControls storage is broken"); return new Control[0]; } return XmlSerializer.deserialize(document, Control[].class); }
public static void processClassFilesAndJarsRecursively(@NotNull File root, @NotNull final Processor<File> processor) { FileUtil.processFilesRecursively(root, new Processor<File>() { @Override public boolean process(File file) { if (file.isFile()) { String fileName = file.getName(); // NOTE: we should ignore apklib dependencies (IDEA-82976) if (FileUtilRt.extensionEquals(fileName, "jar") || FileUtilRt.extensionEquals(fileName, "class")) { if (!processor.process(file)) { return false; } } } return true; } }); }
public static String fileNameToModuleName(String filename) { String nameWithoutExtension = FileUtilRt.getNameWithoutExtension(filename); if (nameWithoutExtension.isEmpty()) { return ""; } return nameWithoutExtension.substring(0, 1).toUpperCase(Locale.getDefault()) + nameWithoutExtension.substring(1); }
@NotNull public static String getSubtaskTestsFileName(int index) { return index == 0 ? TESTS_PY : FileUtil.getNameWithoutExtension(TESTS_PY) + EduNames.SUBTASK_MARKER + index + "." + FileUtilRt.getExtension(TESTS_PY); }
Process createCheckProcess(@NotNull final Project project, @NotNull final String executablePath) throws ExecutionException { final Sdk sdk = PythonSdkType.findPythonSdk(ModuleManager.getInstance(project).getModules()[0]); PyEduPluginConfigurator configurator = new PyEduPluginConfigurator(); String testsFileName = configurator.getTestFileName(); if (myTask instanceof TaskWithSubtasks) { testsFileName = FileUtil.getNameWithoutExtension(testsFileName); int index = ((TaskWithSubtasks)myTask).getActiveSubtaskIndex(); testsFileName += EduNames.SUBTASK_MARKER + index + "." + FileUtilRt.getExtension(configurator.getTestFileName()); } final File testRunner = new File(myTaskDir.getPath(), testsFileName); myCommandLine = new GeneralCommandLine(); myCommandLine.withWorkDirectory(myTaskDir.getPath()); final Map<String, String> env = myCommandLine.getEnvironment(); final VirtualFile courseDir = project.getBaseDir(); if (courseDir != null) { env.put(PYTHONPATH, courseDir.getPath()); } if (sdk != null) { String pythonPath = sdk.getHomePath(); if (pythonPath != null) { myCommandLine.setExePath(pythonPath); myCommandLine.addParameter(testRunner.getPath()); myCommandLine.addParameter(FileUtil.toSystemDependentName(executablePath)); return myCommandLine.createProcess(); } } return null; }
protected void setCompilerOutput(@NotNull Project project) { CompilerProjectExtension compilerProjectExtension = CompilerProjectExtension.getInstance(project); String basePath = project.getBasePath(); if (compilerProjectExtension != null && basePath != null) { compilerProjectExtension.setCompilerOutputUrl(VfsUtilCore.pathToUrl(FileUtilRt.toSystemDependentName(basePath))); } }
@Nullable private static String getTestFileName(@NotNull Project project, int subtaskIndex) { Course course = StudyTaskManager.getInstance(project).getCourse(); if (course == null) { return null; } EduPluginConfigurator configurator = EduPluginConfigurator.INSTANCE.forLanguage(course.getLanguageById()); if (configurator == null) { return null; } String defaultTestFileName = configurator.getTestFileName(); String nameWithoutExtension = FileUtil.getNameWithoutExtension(defaultTestFileName); String extension = FileUtilRt.getExtension(defaultTestFileName); return nameWithoutExtension + EduNames.SUBTASK_MARKER + subtaskIndex + "." + extension; }
private static boolean isTaskDescriptionFile(@NotNull final String fileName) { if (TASK_HTML.equals(fileName) || TASK_MD.equals(fileName)) { return true; } String extension = FileUtilRt.getExtension(fileName); if (!extension.equals(FileUtilRt.getExtension(TASK_HTML)) && !extension.equals(FileUtilRt.getExtension(TASK_MD))) { return false; } return fileName.contains(EduNames.TASK) && fileName.contains(EduNames.SUBTASK_MARKER); }
private static void replaceWithSubtask(JsonObject fileWrapper) { final String file = fileWrapper.get(NAME).getAsString(); final String extension = FileUtilRt.getExtension(file); final String name = FileUtil.getNameWithoutExtension(file); if (!name.contains(EduNames.SUBTASK_MARKER)) { fileWrapper.remove(NAME); fileWrapper.add(NAME, new JsonPrimitive(name + "_subtask0." + extension)); } }
/** * @param fromIndex -1 if task converted to TaskWithSubtasks, -2 if task converted from TaskWithSubtasks */ public static void renameFiles(VirtualFile taskDir, Project project, int fromIndex) { ApplicationManager.getApplication().runWriteAction(() -> { Map<VirtualFile, String> newNames = new HashMap<>(); for (VirtualFile virtualFile : taskDir.getChildren()) { int subtaskIndex = getSubtaskIndex(project, virtualFile); if (subtaskIndex == -1) { continue; } if (subtaskIndex > fromIndex) { String index; if (fromIndex == -1) { // add new subtask index = "0"; } else { // remove subtask index = fromIndex == -2 ? "" : Integer.toString(subtaskIndex - 1); } String fileName = virtualFile.getName(); String nameWithoutExtension = FileUtil.getNameWithoutExtension(fileName); String extension = FileUtilRt.getExtension(fileName); int subtaskMarkerIndex = nameWithoutExtension.indexOf(EduNames.SUBTASK_MARKER); String newName = subtaskMarkerIndex == -1 ? nameWithoutExtension : nameWithoutExtension.substring(0, subtaskMarkerIndex); newName += index.isEmpty() ? "" : EduNames.SUBTASK_MARKER; newName += index + "." + extension; newNames.put(virtualFile, newName); } } for (Map.Entry<VirtualFile, String> entry : newNames.entrySet()) { try { entry.getKey().rename(project, entry.getValue()); } catch (IOException e) { LOG.info(e); } } }); }
@Override public void loadState(Element state) { try { Element courseElement = getChildWithName(state, COURSE).getChild(COURSE_TITLED); for (Element lesson : getChildList(courseElement, LESSONS, true)) { int lessonIndex = getAsInt(lesson, INDEX); for (Element task : getChildList(lesson, TASK_LIST, true)) { int taskIndex = getAsInt(task, INDEX); Map<String, Element> taskFiles = getChildMap(task, TASK_FILES, true); for (Map.Entry<String, Element> entry : taskFiles.entrySet()) { Element taskFileElement = entry.getValue(); String name = entry.getKey(); String answerName = FileUtil.getNameWithoutExtension(name) + CCUtils.ANSWER_EXTENSION_DOTTED + FileUtilRt.getExtension(name); Document document = StudyUtils.getDocument(myProject.getBasePath(), lessonIndex, taskIndex, answerName); if (document == null) { document = StudyUtils.getDocument(myProject.getBasePath(), lessonIndex, taskIndex, name); if (document == null) { continue; } } for (Element placeholder : getChildList(taskFileElement, ANSWER_PLACEHOLDERS, true)) { Element lineElement = getChildWithName(placeholder, LINE, true); int line = lineElement != null ? Integer.valueOf(lineElement.getAttributeValue(VALUE)) : 0; Element startElement = getChildWithName(placeholder, START, true); int start = startElement != null ? Integer.valueOf(startElement.getAttributeValue(VALUE)) : 0; int offset = document.getLineStartOffset(line) + start; addChildWithName(placeholder, OFFSET, offset); addChildWithName(placeholder, "useLength", "false"); } } } } XmlSerializer.deserializeInto(this, state); } catch (StudyUnrecognizedFormatException e) { LOG.error(e); } }
public static void copyProperties(final String targetPath, final String fileName) throws IOException { final File targetDir = new File(targetPath).getAbsoluteFile(); final File file = new File(targetDir, fileName); FileUtil.createParentDirs(file); for (File f = file; f != null && !FileUtil.filesEqual(f, targetDir); f = FileUtilRt.getParentFile(f)) { f.deleteOnExit(); } final String resourceName = "/" + fileName; final InputStream stream = CopyResourcesUtil.class.getResourceAsStream(resourceName); if (stream == null) { return; } copyStreamToFile(stream, file); }
private Map<JpsModule, Set<String>> computeModuleCharsetMap() { final Map<JpsModule, Set<String>> map = new THashMap<JpsModule, Set<String>>(); final Iterable<JavaBuilderExtension> builderExtensions = JpsServiceManager.getInstance().getExtensions(JavaBuilderExtension.class); for (Map.Entry<String, String> entry : myUrlToCharset.entrySet()) { final String fileUrl = entry.getKey(); final String charset = entry.getValue(); File file = JpsPathUtil.urlToFile(fileUrl); if (charset == null || (!file.isDirectory() && !shouldHonorEncodingForCompilation(builderExtensions, file))) continue; final JavaSourceRootDescriptor rootDescriptor = myRootsIndex.findJavaRootDescriptor(null, file); if (rootDescriptor == null) continue; final JpsModule module = rootDescriptor.target.getModule(); Set<String> set = map.get(module); if (set == null) { set = new LinkedHashSet<String>(); map.put(module, set); final File sourceRoot = rootDescriptor.root; File current = FileUtilRt.getParentFile(file); String parentCharset = null; while (current != null) { final String currentCharset = myUrlToCharset.get(FileUtil.toSystemIndependentName(current.getAbsolutePath())); if (currentCharset != null) { parentCharset = currentCharset; } if (FileUtil.filesEqual(current, sourceRoot)) { break; } current = FileUtilRt.getParentFile(current); } if (parentCharset != null) { set.add(parentCharset); } } set.add(charset); } return map; }