void saveRemainingPatches(
      final ShelvedChangeList changeList,
      final List<FilePatch> remainingPatches,
      final List<ShelvedBinaryFile> remainingBinaries,
      CommitContext commitContext) {
    final File newPath = getPatchPath(changeList.DESCRIPTION);
    try {
      FileUtil.copy(new File(changeList.PATH), newPath);
    } catch (IOException e) {
      // do not delete if cannot recycle
      return;
    }
    final ShelvedChangeList listCopy =
        new ShelvedChangeList(
            newPath.getAbsolutePath(),
            changeList.DESCRIPTION,
            new ArrayList<ShelvedBinaryFile>(changeList.getBinaryFiles()));
    listCopy.DATE = (changeList.DATE == null) ? null : new Date(changeList.DATE.getTime());

    writePatchesToFile(myProject, changeList.PATH, remainingPatches, commitContext);

    changeList.getBinaryFiles().retainAll(remainingBinaries);
    changeList.clearLoadedChanges();
    recycleChangeList(listCopy, changeList);
    notifyStateChanged();
  }
  public static void rename(@NotNull File source, @NotNull File target) throws IOException {
    if (source.renameTo(target)) return;
    if (!source.exists()) return;

    copy(source, target);
    delete(source);
  }
 private void copyFileOrDir(File src, File dst) throws IOException {
   if (src.isDirectory()) {
     FileUtil.copyDir(src, dst);
   } else {
     FileUtil.copy(src, dst);
   }
 }
 public List<ShelvedChangeList> importChangeLists(
     final Collection<VirtualFile> files, final Consumer<VcsException> exceptionConsumer) {
   final List<ShelvedChangeList> result = new ArrayList<ShelvedChangeList>(files.size());
   try {
     final FilesProgress filesProgress = new FilesProgress(files.size(), "Processing ");
     for (VirtualFile file : files) {
       filesProgress.updateIndicator(file);
       final String description = file.getNameWithoutExtension().replace('_', ' ');
       final File patchPath = getPatchPath(description);
       final ShelvedChangeList list =
           new ShelvedChangeList(
               patchPath.getPath(),
               description,
               new SmartList<ShelvedBinaryFile>(),
               file.getTimeStamp());
       try {
         final List<TextFilePatch> patchesList =
             loadPatches(myProject, file.getPath(), new CommitContext());
         if (!patchesList.isEmpty()) {
           FileUtil.copy(new File(file.getPath()), patchPath);
           // add only if ok to read patch
           myShelvedChangeLists.add(list);
           result.add(list);
         }
       } catch (IOException e) {
         exceptionConsumer.consume(new VcsException(e));
       } catch (PatchSyntaxException e) {
         exceptionConsumer.consume(new VcsException(e));
       }
     }
   } finally {
     notifyStateChanged();
   }
   return result;
 }
 public static void copyDir(
     @NotNull File fromDir, @NotNull File toDir, @Nullable final FileFilter filter)
     throws IOException {
   ensureExists(toDir);
   if (isAncestor(fromDir, toDir, true)) {
     LOG.error(fromDir.getAbsolutePath() + " is ancestor of " + toDir + ". Can't copy to itself.");
     return;
   }
   File[] files = fromDir.listFiles();
   if (files == null)
     throw new IOException(
         CommonBundle.message("exception.directory.is.invalid", fromDir.getPath()));
   if (!fromDir.canRead())
     throw new IOException(
         CommonBundle.message("exception.directory.is.not.readable", fromDir.getPath()));
   for (File file : files) {
     if (filter != null && !filter.accept(file)) {
       continue;
     }
     if (file.isDirectory()) {
       copyDir(file, new File(toDir, file.getName()), filter);
     } else {
       copy(file, new File(toDir, file.getName()));
     }
   }
 }
  public static void extractEntry(
      ZipEntry entry, final InputStream inputStream, File outputDir, boolean overwrite)
      throws IOException {
    final boolean isDirectory = entry.isDirectory();

    String entryName = entry.getName();
    String relativeName = entryName.substring(JAVASCRIPT_GEN_DIR.length() + 1, entryName.length());

    final File file = new File(outputDir, relativeName);
    if (file.exists() && !overwrite) return;

    FileUtil.createParentDirs(file);
    if (isDirectory) {
      file.mkdir();
    } else {
      final BufferedInputStream is = new BufferedInputStream(inputStream);
      final BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));
      try {
        FileUtil.copy(is, os);
      } finally {
        os.close();
        is.close();
      }
    }
  }
 private static void copyFile(@NotNull final File from, @NotNull final File to) {
   if (from.exists()) {
     try {
       FileUtil.copy(from, to);
     } catch (IOException e) {
       LOG.warn("Failed to copy " + from.getName());
     }
   }
 }
 /**
  * Copies content of {@code fromDir} to {@code toDir}. It's equivalent to "cp -r fromDir/* toDir"
  * unix command.
  *
  * @param fromDir source directory
  * @param toDir destination directory
  * @throws IOException in case of any IO troubles
  */
 public static void copyDirContent(@NotNull File fromDir, @NotNull File toDir) throws IOException {
   File[] children = ObjectUtils.notNull(fromDir.listFiles(), ArrayUtil.EMPTY_FILE_ARRAY);
   for (File child : children) {
     File target = new File(toDir, child.getName());
     if (child.isFile()) {
       copy(child, target);
     } else {
       copyDir(child, target, true);
     }
   }
 }
 public void testExtractDirectoryFromExcludedJar() throws IOException {
   String jarPath = createFile("dir/lib/j.jar");
   FileUtil.copy(new File(getJUnitJarPath()), new File(jarPath));
   JpsModule module = addModule("m");
   String libDir = PathUtil.getParentPath(jarPath);
   module.getContentRootsList().addUrl(JpsPathUtil.pathToUrl(PathUtil.getParentPath(libDir)));
   module.getExcludeRootsList().addUrl(JpsPathUtil.pathToUrl(libDir));
   final JpsArtifact a = addArtifact("a", root().extractedDir(jarPath, "/junit/textui/"));
   buildAll();
   assertOutput(a, fs().file("ResultPrinter.class").file("TestRunner.class"));
 }
 protected String copyToProject(String relativeSourcePath, String relativeTargetPath) {
   File source = findFindUnderProjectHome(relativeSourcePath);
   String fullTargetPath = getAbsolutePath(relativeTargetPath);
   File target = new File(fullTargetPath);
   try {
     if (source.isDirectory()) {
       FileUtil.copyDir(source, target);
     } else {
       FileUtil.copy(source, target);
     }
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
   return fullTargetPath;
 }
 public static File copyResourceFile(
     String sourceName, String copyName, Project project, Task task) throws IOException {
   StudyTaskManager taskManager = StudyTaskManager.getInstance(project);
   Course course = taskManager.getCourse();
   int taskNum = task.getIndex() + 1;
   int lessonNum = task.getLesson().getIndex() + 1;
   assert course != null;
   String pathToResource =
       FileUtil.join(
           new File(course.getResourcePath()).getParent(),
           Lesson.LESSON_DIR + lessonNum,
           Task.TASK_DIR + taskNum);
   File resourceFile = new File(pathToResource, copyName);
   FileUtil.copy(new File(pathToResource, sourceName), resourceFile);
   return resourceFile;
 }
Esempio n. 12
0
 private static void writeRuntimeToJar(final JarOutputStream stream) throws IOException {
   final File unpackedRuntimePath = getUnpackedRuntimePath();
   if (unpackedRuntimePath != null) {
     FileUtil.processFilesRecursively(
         unpackedRuntimePath,
         new Processor<File>() {
           @Override
           public boolean process(File file) {
             if (file.isDirectory()) return true;
             final String relativePath = FileUtil.getRelativePath(unpackedRuntimePath, file);
             try {
               stream.putNextEntry(new JarEntry(FileUtil.toSystemIndependentName(relativePath)));
               FileInputStream fis = new FileInputStream(file);
               try {
                 FileUtil.copy(fis, stream);
               } finally {
                 fis.close();
               }
             } catch (IOException e) {
               throw new RuntimeException(e);
             }
             return true;
           }
         });
   } else {
     File runtimeJarPath = getRuntimeJarPath();
     if (runtimeJarPath != null) {
       JarInputStream jis = new JarInputStream(new FileInputStream(runtimeJarPath));
       try {
         while (true) {
           JarEntry e = jis.getNextJarEntry();
           if (e == null) {
             break;
           }
           if (FileUtil.getExtension(e.getName()).equals("class")) {
             stream.putNextEntry(e);
             FileUtil.copy(jis, stream);
           }
         }
       } finally {
         jis.close();
       }
     } else {
       throw new CompileEnvironmentException("Couldn't find runtime library");
     }
   }
 }
  private static void performCopy(
      @NotNull File fromFile, @NotNull File toFile, final boolean syncTimestamp)
      throws IOException {
    final FileOutputStream fos;
    try {
      fos = openOutputStream(toFile);
    } catch (IOException e) {
      if (SystemInfo.isWindows
          && e.getMessage() != null
          && e.getMessage().contains("denied")
          && WinUACTemporaryFix.nativeCopy(fromFile, toFile, syncTimestamp)) {
        return;
      }
      throw e;
    }

    try {
      final FileInputStream fis = new FileInputStream(fromFile);
      try {
        copy(fis, fos);
      } finally {
        fis.close();
      }
    } finally {
      fos.close();
    }

    if (syncTimestamp) {
      final long timeStamp = fromFile.lastModified();
      if (timeStamp < 0) {
        LOG.warn("Invalid timestamp " + timeStamp + " of '" + fromFile + "'");
      } else if (!toFile.setLastModified(timeStamp)) {
        LOG.warn("Unable to set timestamp " + timeStamp + " to '" + toFile + "'");
      }
    }

    if (SystemInfo.isUnix && fromFile.canExecute()) {
      FileSystemUtil.clonePermissions(fromFile.getPath(), toFile.getPath());
    }
  }
Esempio n. 14
0
  @NotNull
  private File copyToMirror(@NotNull File original, @NotNull File mirror) {
    ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
    if (progress != null) {
      progress.pushState();
      progress.setText(VfsBundle.message("jar.copy.progress", original.getPath()));
      progress.setFraction(0);
    }

    try {
      FileUtil.copy(original, mirror);
    } catch (final IOException e) {
      reportIOErrorWithJars(original, mirror, e);
      return original;
    }

    if (progress != null) {
      progress.popState();
    }

    return mirror;
  }
 private static void ensureLogConfigExists(File workDirectory) {
   final File logConfig = new File(workDirectory, LOGGER_CONFIG);
   if (!logConfig.exists()) {
     FileUtil.createIfDoesntExist(logConfig);
     try {
       final InputStream in = Server.class.getResourceAsStream("/" + DEFAULT_LOGGER_CONFIG);
       if (in != null) {
         try {
           final FileOutputStream out = new FileOutputStream(logConfig);
           try {
             FileUtil.copy(in, out);
           } finally {
             out.close();
           }
         } finally {
           in.close();
         }
       }
     } catch (IOException e) {
       LOG.error(e);
     }
   }
 }
  private static void copy(
      @NotNull File src,
      @NotNull File dest,
      ConfigImportSettings settings,
      File oldInstallationHome)
      throws IOException {
    src = src.getCanonicalFile();
    dest = dest.getCanonicalFile();
    if (!src.isDirectory()) {
      throw new IOException(
          ApplicationBundle.message(
              "config.import.invalid.directory.error", src.getAbsolutePath()));
    }
    if (!dest.isDirectory()) {
      throw new IOException(
          ApplicationBundle.message(
              "config.import.invalid.directory.error", dest.getAbsolutePath()));
    }
    if (FileUtil.filesEqual(src, dest)) {
      return;
    }

    FileUtil.ensureExists(dest);

    File[] childFiles =
        src.listFiles(
            new FilenameFilter() {
              @Override
              public boolean accept(@NotNull File dir, @NotNull String name) {
                // Don't copy plugins just imported. They're most probably incompatible with newer
                // idea version.
                return !StringUtil.startsWithChar(name, '.') && !name.equals(PLUGINS_PATH);
              }
            });

    if (childFiles == null || childFiles.length == 0) {
      return;
    }

    for (File from : childFiles) {
      File to = new File(dest, from.getName());
      if (from.isDirectory()) {
        FileUtil.copyDir(from, to, false);
      } else {
        FileUtil.copy(from, to);
      }
    }

    File plugins = new File(src, PLUGINS_PATH);
    if (!loadOldPlugins(plugins, dest) && SystemInfo.isMac) {
      File oldPluginsDir =
          getOldPath(
              oldInstallationHome,
              settings,
              PathManager.PROPERTY_PLUGINS_PATH,
              new Function<String, String>() {
                @Override
                public String fun(String pathSelector) {
                  return PathManager.getDefaultPluginPathFor(pathSelector);
                }
              });
      if (oldPluginsDir == null) {
        // e.g. installation home referred to config home. Try with default selector, same as config
        // name
        oldPluginsDir = new File(PathManager.getDefaultPluginPathFor(src.getName()));
      }
      loadOldPlugins(oldPluginsDir, dest);
    }
  }
  @Nullable
  private Pair<String, String> moveToRealLocation(
      String tempOutputDir,
      String pathToClass,
      VirtualFile sourceFile,
      final List<File> filesToRefresh) {
    final Module module = myCompileContext.getModuleByFile(sourceFile);
    if (module == null) {
      final String message =
          "Cannot determine module for source file: "
              + sourceFile.getPresentableUrl()
              + ";\nCorresponding output file: "
              + pathToClass;
      LOG.info(message);
      myCompileContext.addMessage(
          CompilerMessageCategory.WARNING, message, sourceFile.getUrl(), -1, -1);
      // do not move: looks like source file has been invalidated, need recompilation
      return new Pair<String, String>(tempOutputDir, pathToClass);
    }
    final String realOutputDir;
    if (myCompileContext.isInTestSourceContent(sourceFile)) {
      realOutputDir = getTestsOutputDir(module);
      LOG.assertTrue(realOutputDir != null);
    } else {
      realOutputDir = getOutputDir(module);
      LOG.assertTrue(realOutputDir != null);
    }

    if (FileUtil.pathsEqual(tempOutputDir, realOutputDir)) { // no need to move
      filesToRefresh.add(new File(pathToClass));
      return new Pair<String, String>(realOutputDir, pathToClass);
    }

    final String realPathToClass = realOutputDir + pathToClass.substring(tempOutputDir.length());
    final File fromFile = new File(pathToClass);
    final File toFile = new File(realPathToClass);

    boolean success = fromFile.renameTo(toFile);
    if (!success) {
      // assuming cause of the fail: intermediate dirs do not exist
      FileUtil.createParentDirs(toFile);
      // retry after making non-existent dirs
      success = fromFile.renameTo(toFile);
    }
    if (!success) { // failed to move the file: e.g. because source and destination reside on
                    // different mountpoints.
      try {
        FileUtil.copy(fromFile, toFile);
        FileUtil.delete(fromFile);
        success = true;
      } catch (IOException e) {
        LOG.info(e);
        success = false;
      }
    }
    if (success) {
      filesToRefresh.add(toFile);
      return new Pair<String, String>(realOutputDir, realPathToClass);
    }
    return null;
  }