@Override
  public void compileToDir(
      ScriptSource source,
      ClassLoader classLoader,
      File classesDir,
      File metadataDir,
      CompileOperation<?> extractingTransformer,
      Class<? extends Script> scriptBaseClass,
      Action<? super ClassNode> verifier) {
    Clock clock = new Clock();
    GFileUtils.deleteDirectory(classesDir);
    GFileUtils.mkdirs(classesDir);
    CompilerConfiguration configuration = createBaseCompilerConfiguration(scriptBaseClass);
    configuration.setTargetDirectory(classesDir);
    try {
      compileScript(
          source,
          classLoader,
          configuration,
          classesDir,
          metadataDir,
          extractingTransformer,
          verifier);
    } catch (GradleException e) {
      GFileUtils.deleteDirectory(classesDir);
      GFileUtils.deleteDirectory(metadataDir);
      throw e;
    }

    logger.debug(
        "Timing: Writing script to cache at {} took: {}",
        classesDir.getAbsolutePath(),
        clock.getTime());
  }
    public DefaultFileLock(
        File target, LockMode mode, String displayName, String operationDisplayName)
        throws Throwable {
      if (mode == LockMode.None) {
        throw new UnsupportedOperationException("Locking mode None is not supported.");
      }

      this.target = target;

      this.displayName = displayName;
      this.operationDisplayName = operationDisplayName;
      if (target.isDirectory()) {
        lockFile = new File(target, target.getName() + ".lock");
      } else {
        lockFile = new File(target.getParentFile(), target.getName() + ".lock");
      }

      GFileUtils.mkdirs(lockFile.getParentFile());
      lockFile.createNewFile();
      lockFileAccess = new RandomAccessFile(lockFile, "rw");
      try {
        lock = lock(mode);
        integrityViolated = !getUnlockedCleanly();
      } catch (Throwable t) {
        // Also releases any locks
        lockFileAccess.close();
        throw t;
      }

      this.mode = lock.isShared() ? LockMode.Shared : LockMode.Exclusive;
    }
Example #3
0
  public WorkResult execute(CommandLineToolInvocation invocation) {
    ExecAction compiler = execActionFactory.newExecAction();
    compiler.executable(executable);
    if (invocation.getWorkDirectory() != null) {
      GFileUtils.mkdirs(invocation.getWorkDirectory());
      compiler.workingDir(invocation.getWorkDirectory());
    }

    compiler.args(invocation.getArgs());

    if (!invocation.getPath().isEmpty()) {
      String pathVar = OperatingSystem.current().getPathVar();
      String compilerPath = Joiner.on(File.pathSeparator).join(invocation.getPath());
      compilerPath = compilerPath + File.pathSeparator + System.getenv(pathVar);
      compiler.environment(pathVar, compilerPath);
    }

    compiler.environment(invocation.getEnvironment());

    try {
      compiler.execute();
    } catch (ExecException e) {
      throw new GradleException(
          String.format("%s failed; see the error output for details.", action), e);
    }
    return new SimpleWorkResult(true);
  }
 private <M> void serializeMetadata(
     ScriptSource scriptSource,
     CompileOperation<M> extractingTransformer,
     File metadataDir,
     boolean emptyScript,
     boolean hasMethods) {
   File metadataFile = new File(metadataDir, METADATA_FILE_NAME);
   try {
     GFileUtils.mkdirs(metadataDir);
     KryoBackedEncoder encoder = new KryoBackedEncoder(new FileOutputStream(metadataFile));
     try {
       byte flags = (byte) ((emptyScript ? EMPTY_FLAG : 0) | (hasMethods ? HAS_METHODS_FLAG : 0));
       encoder.writeByte(flags);
       if (extractingTransformer != null && extractingTransformer.getDataSerializer() != null) {
         Serializer<M> serializer = extractingTransformer.getDataSerializer();
         serializer.write(encoder, extractingTransformer.getExtractedData());
       }
     } finally {
       encoder.close();
     }
   } catch (Exception e) {
     throw new GradleException(
         String.format(
             "Failed to serialize script metadata extracted for %s",
             scriptSource.getDisplayName()),
         e);
   }
 }
  private void locateKitsInRegistry(String baseKey) {
    String[] versions = {VERSION_KIT_8, VERSION_KIT_81};
    String[] keys = {REGISTRY_KIT_8, REGISTRY_KIT_81};

    for (int i = 0; i != keys.length; ++i) {
      try {
        File kitDir =
            GFileUtils.canonicalise(
                new File(
                    windowsRegistry.getStringValue(
                        WindowsRegistry.Key.HKEY_LOCAL_MACHINE,
                        baseKey + REGISTRY_ROOTPATH_KIT,
                        keys[i])));
        if (isWindowsSdk(kitDir)) {
          LOGGER.debug("Found Windows Kit {} at {}", versions[i], kitDir);
          addSdk(kitDir, versions[i], NAME_KIT + " " + versions[i]);
        } else {
          LOGGER.debug(
              "Ignoring candidate Windows Kit directory {} as it does not look like a Windows Kit installation.",
              kitDir);
        }
      } catch (MissingRegistryEntryException e) {
        // Ignore the version if the string cannot be read
      }
    }
  }
Example #6
0
  /**
   * Creates the project.
   *
   * @return The project
   */
  public Project build() {
    if (projectDir == null) {
      try {
        projectDir = GFileUtils.canonicalise(File.createTempFile("gradle", "projectDir"));
        projectDir.delete();
        projectDir.mkdir();
        projectDir.deleteOnExit();
      } catch (IOException e) {
        throw new UncheckedIOException(e);
      }
    }

    final File homeDir = new File(projectDir, "gradleHome");

    StartParameter startParameter = new StartParameter();
    startParameter.setGradleUserHomeDir(new File(projectDir, "userHome"));

    ServiceRegistryFactory topLevelRegistry =
        new TestTopLevelBuildServiceRegistry(startParameter, homeDir);
    GradleInternal gradle = new DefaultGradle(null, startParameter, topLevelRegistry);

    DefaultProjectDescriptor projectDescriptor =
        new DefaultProjectDescriptor(
            null, "test", projectDir, new DefaultProjectDescriptorRegistry());
    ProjectInternal project =
        topLevelRegistry.get(IProjectFactory.class).createProject(projectDescriptor, null, gradle);

    gradle.setRootProject(project);
    gradle.setDefaultProject(project);

    return project;
  }
  @Before
  public void setUp() {
    testObj = createTask(GroovyCompile.class);
    groovyCompilerMock = context.mock(Compiler.class);
    testObj.setCompiler(groovyCompilerMock);

    GFileUtils.touch(new File(srcDir, "incl/file.groovy"));
  }
 public File createTemporaryFile(String prefix, @Nullable String suffix, String... path) {
   File dir = new File(baseDir.get(), GUtil.join(path, "/"));
   GFileUtils.createDirectory(dir);
   try {
     return File.createTempFile(prefix, suffix, dir);
   } catch (IOException e) {
     throw new UncheckedIOException(e.getMessage(), e);
   }
 }
Example #9
0
 private void checkWtpFile() throws IOException {
   File wtp =
       new File(
           getProject().getProjectDir(), EclipseWtp.WTP_FILE_DIR + "/" + EclipseWtp.WTP_FILE_NAME);
   assertTrue(wtp.isFile());
   assertThat(
       GFileUtils.readFileToString(wtp),
       Matchers.equalTo(
           IOUtils.toString(this.getClass().getResourceAsStream("expectedWtpFile.txt"))));
 }
Example #10
0
  @Before
  public void setUp() {
    classesDir = tmpDir.createDir("classes");
    File classfile = new File(classesDir, "FileTest.class");
    GFileUtils.touch(classfile);
    resultsDir = tmpDir.createDir("testResults");
    binResultsDir = tmpDir.createDir("binResults");
    reportDir = tmpDir.createDir("report");

    test = createTask(Test.class);
  }
  public DefaultPersistentDirectoryStore open() {
    GFileUtils.mkdirs(dir);
    cacheAccess = createCacheAccess();
    try {
      cacheAccess.open(lockOptions);
    } catch (Throwable e) {
      throw new CacheOpenException(String.format("Could not open %s.", this), e);
    }

    return this;
  }
Example #12
0
 protected LocallyAvailableResource doAdd(
     File destination, String failureDescription, Action<File> action) {
   try {
     GFileUtils.parentMkdirs(destination);
     File inProgressMarkerFile = getInProgressMarkerFile(destination);
     GFileUtils.touch(inProgressMarkerFile);
     try {
       deleteAction.delete(destination);
       action.execute(destination);
     } catch (Throwable t) {
       deleteAction.delete(destination);
       throw t;
     } finally {
       deleteAction.delete(inProgressMarkerFile);
     }
   } catch (Throwable t) {
     throw new GradleException(failureDescription, t);
   }
   return entryAt(destination);
 }
 public <E> PersistentStateCache<E> openStateCache(
     File cacheDir,
     CacheUsage usage,
     CacheValidator validator,
     Map<String, ?> properties,
     FileLockManager.LockMode lockMode,
     Serializer<E> serializer) {
   GFileUtils.mkdirs(cacheDir);
   return new SimpleStateCache<E>(
       new File(cacheDir, "state.bin"), new NoOpFileLock(), new DefaultSerializer<E>());
 }
Example #14
0
 public InputStream open() {
   if (read && file != null) {
     return GFileUtils.openInputStream(file);
   }
   if (read || tar.getCurrent() != entry) {
     throw new UnsupportedOperationException(
         String.format("The contents of %s has already been read.", this));
   }
   read = true;
   return tar;
 }
 private void searchForDependency(
     Set<ResolvedInclude> dependencies, List<File> searchPath, String include) {
   for (File searchDir : searchPath) {
     File candidate = new File(searchDir, include);
     // TODO:DAZ This means that we'll never detect changed files if they are not on the defined
     // include path
     if (candidate.isFile()) {
       dependencies.add(new ResolvedInclude(include, GFileUtils.canonicalise(candidate)));
       return;
     }
   }
 }
Example #16
0
  @Before
  public void setUp() {
    super.setUp();

    File rootDir = getProject().getProjectDir();
    classesDir = new File(rootDir, "testClassesDir");
    File classfile = new File(classesDir, "FileTest.class");
    GFileUtils.touch(classfile);
    resultsDir = new File(rootDir, "resultDir");
    reportDir = new File(rootDir, "report/tests");

    test = createTask(Test.class);
  }
 public void initialize(FileLock fileLock) {
   for (File file : getBaseDir().listFiles()) {
     if (fileLock.isLockFile(file) || file.equals(propertiesFile)) {
       continue;
     }
     GFileUtils.forceDelete(file);
   }
   if (initAction != null) {
     initAction.execute(DefaultPersistentDirectoryCache.this);
   }
   GUtil.saveProperties(properties, propertiesFile);
   didRebuild = true;
 }
  private SearchResult locateUserSpecifiedSdk(File candidate) {
    File sdkDir = GFileUtils.canonicalise(candidate);
    if (!isWindowsSdk(sdkDir)) {
      return new SdkNotFound(
          String.format(
              "The specified installation directory '%s' does not appear to contain a Windows SDK installation.",
              candidate));
    }

    if (!foundSdks.containsKey(sdkDir)) {
      addSdk(sdkDir, VERSION_USER, NAME_USER);
    }
    return new SdkFound(foundSdks.get(sdkDir));
  }
 public PersistentCache open(
     File cacheDir,
     String displayName,
     CacheUsage usage,
     CacheValidator cacheValidator,
     Map<String, ?> properties,
     FileLockManager.LockMode lockMode,
     Action<? super PersistentCache> initializer) {
   GFileUtils.mkdirs(cacheDir);
   InMemoryCache cache = new InMemoryCache(cacheDir);
   if (initializer != null) {
     initializer.execute(cache);
   }
   return cache;
 }
Example #20
0
 private FileInfo copyIntoCache(
     Factory<File> baseDirFactory,
     File source,
     long lastModified,
     long length,
     HashValue hashValue) {
   File baseDir = baseDirFactory.create();
   File cachedFile = new File(baseDir, hashValue.asCompactString() + '/' + source.getName());
   if (!cachedFile.isFile()) {
     // Has previously been added to the cache directory
     GFileUtils.copyFile(source, cachedFile);
   }
   FileInfo fileInfo = new FileInfo(lastModified, length, hashValue, cachedFile);
   cachedFiles.put(source, fileInfo);
   return fileInfo;
 }
 public File createTemporaryDirectory(
     @Nullable String prefix, @Nullable String suffix, @Nullable String... path) {
   File dir = new File(baseDir.get(), GUtil.join(path, "/"));
   GFileUtils.createDirectory(dir);
   try {
     // TODO: This is not a great paradigm for creating a temporary directory.
     // See
     // http://guava-libraries.googlecode.com/svn/tags/release08/javadoc/com/google/common/io/Files.html#createTempDir%28%29 for an alternative.
     File tmpDir = File.createTempFile("gradle", "projectDir", dir);
     tmpDir.delete();
     tmpDir.mkdir();
     return tmpDir;
   } catch (IOException e) {
     throw new UncheckedIOException(e.getMessage(), e);
   }
 }
 private byte[] hash(
     List<String> visitedFilePaths, Set<File> visitedDirs, byte[] combinedHash, File[] toHash) {
   for (File file : toHash) {
     file = GFileUtils.canonicalise(file);
     if (file.isDirectory()) {
       if (visitedDirs.add(file)) {
         // in theory, awkward symbolic links can lead to recursion problems.
         // TODO - figure out a way to test it. I only tested it 'manually' and the feature is
         // needed.
         combinedHash = hash(visitedFilePaths, visitedDirs, combinedHash, file.listFiles());
       }
     } else {
       visitedFilePaths.add(file.getAbsolutePath());
       combinedHash = Bytes.concat(combinedHash, hasher.hash(file));
     }
   }
   return combinedHash;
 }
 public FileLock lock(
     File target, LockMode mode, String targetDisplayName, String operationDisplayName) {
   if (mode == LockMode.None) {
     throw new UnsupportedOperationException(
         String.format("No %s mode lock implementation available.", mode));
   }
   File canonicalTarget = GFileUtils.canonicalise(target);
   if (!lockedFiles.add(canonicalTarget)) {
     throw new IllegalStateException(
         String.format(
             "Cannot lock %s as it has already been locked by this process.", targetDisplayName));
   }
   try {
     return new DefaultFileLock(canonicalTarget, mode, targetDisplayName, operationDisplayName);
   } catch (Throwable t) {
     lockedFiles.remove(canonicalTarget);
     throw UncheckedException.throwAsUncheckedException(t);
   }
 }
  protected void transformArgs(List<String> input, List<String> output, File tempDir) {
    GFileUtils.mkdirs(tempDir);
    File optionsFile = new File(tempDir, "options.txt");
    try {
      PrintWriter writer = new PrintWriter(optionsFile);
      try {
        ArgWriter argWriter = argWriterFactory.transform(writer);
        argWriter.args(input);
      } finally {
        IOUtils.closeQuietly(writer);
      }
    } catch (IOException e) {
      throw new UncheckedIOException(
          String.format(
              "Could not write compiler options file '%s'.", optionsFile.getAbsolutePath()),
          e);
    }

    output.add(String.format("@%s", optionsFile.getAbsolutePath()));
  }
  private void locateSdkInPath() {
    File resourceCompiler = os.findInPath(RESOURCE_FILENAME);
    if (resourceCompiler == null) {
      LOGGER.debug("Could not find Windows resource compiler in system path.");
      return;
    }
    File sdkDir = GFileUtils.canonicalise(resourceCompiler.getParentFile().getParentFile());
    if (!isWindowsSdk(sdkDir)) {
      sdkDir = sdkDir.getParentFile();
      if (!isWindowsSdk(sdkDir)) {
        LOGGER.debug(
            "Ignoring candidate Windows SDK for {} as it does not look like a Windows SDK installation.",
            resourceCompiler);
      }
    }
    LOGGER.debug("Found Windows SDK {} using system path", sdkDir);

    if (!foundSdks.containsKey(sdkDir)) {
      addSdk(sdkDir, "path", "Path-resolved Windows SDK");
    }
    pathSdk = foundSdks.get(sdkDir);
  }
Example #26
0
  StateFileUtil(
      File projectRootDirectory,
      File directoryToProcess,
      File dotGradleStatesDirectory,
      DigesterFactory shaDigesterFactory,
      IoFactory ioFactory) {
    this.projectRootDirectory = projectRootDirectory;
    this.absoluteProjectRootPath = projectRootDirectory.getAbsolutePath();
    this.ioFactory = ioFactory;

    this.directoryToProcess = directoryToProcess;
    this.absoluteDirectoryToProcessPath = directoryToProcess.getAbsolutePath();
    this.shaDigesterFactory = shaDigesterFactory;

    final String relativePathToProjectRoot = getRelativePathToProjectRoot(directoryToProcess);
    final String directoryStateId = getStringDigest(relativePathToProjectRoot);

    directoryStateDir = new File(dotGradleStatesDirectory, directoryStateId);
    oldDirectoryStateDir = new File(directoryStateDir, "old");
    newDirectoryStateDir = new File(directoryStateDir, "new");

    if (newDirectoryStateDir.exists()) {
      try {
        FileUtils.deleteDirectory(newDirectoryStateDir);
      } catch (IOException e) {
        throw new GradleException(
            "failed to clear new state directory " + newDirectoryStateDir.getAbsolutePath(), e);
      }
    }

    if (!GFileUtils.createDirectoriesWhenNotExistent(oldDirectoryStateDir, newDirectoryStateDir)) {
      throw new GradleException(
          "failed to create one or more of the state directories ["
              + oldDirectoryStateDir.getAbsolutePath()
              + ", "
              + newDirectoryStateDir.getAbsolutePath()
              + "]");
    }
  }
  protected void doBuild(DaemonCommandExecution execution, Build build) {
    Properties originalSystemProperties = new Properties();
    originalSystemProperties.putAll(System.getProperties());
    File currentDir = GFileUtils.canonicalise(new File("."));

    Properties clientSystemProperties = new Properties();
    clientSystemProperties.putAll(build.getParameters().getSystemProperties());
    System.setProperties(clientSystemProperties);

    Map<String, String> originalEnv = System.getenv();
    processEnvironment.setenv(build.getParameters().getEnvVariables());

    processEnvironment.setProcessDir(build.getParameters().getCurrentDir());

    try {
      execution.proceed();
    } finally {
      System.setProperties(originalSystemProperties);
      processEnvironment.setenv(originalEnv);
      processEnvironment.setProcessDir(currentDir);
    }
  }
  private DaemonStartupInfo startProcess(List<String> args, File workingDir, InputStream stdInput) {
    LOGGER.info("Starting daemon process: workingDir = {}, daemonArgs: {}", workingDir, args);
    Clock clock = new Clock();
    try {
      GFileUtils.mkdirs(workingDir);

      DaemonOutputConsumer outputConsumer = new DaemonOutputConsumer(stdInput);
      ExecHandle handle = new DaemonExecHandleBuilder().build(args, workingDir, outputConsumer);

      handle.start();
      LOGGER.debug("Gradle daemon process is starting. Waiting for the daemon to detach...");
      handle.waitForFinish();
      LOGGER.debug("Gradle daemon process is now detached.");

      return daemonGreeter.parseDaemonOutput(outputConsumer.getProcessOutput());
    } catch (GradleException e) {
      throw e;
    } catch (Exception e) {
      throw new GradleException("Could not start Gradle daemon.", e);
    } finally {
      LOGGER.info("An attempt to start the daemon took {}.", clock.getTime());
    }
  }
  private void locateSdksInRegistry(String baseKey) {
    try {
      List<String> subkeys =
          windowsRegistry.getSubkeys(
              WindowsRegistry.Key.HKEY_LOCAL_MACHINE, baseKey + REGISTRY_ROOTPATH_SDK);
      for (String subkey : subkeys) {
        try {
          String basePath = baseKey + REGISTRY_ROOTPATH_SDK + "\\" + subkey;
          File sdkDir =
              GFileUtils.canonicalise(
                  new File(
                      windowsRegistry.getStringValue(
                          WindowsRegistry.Key.HKEY_LOCAL_MACHINE, basePath, REGISTRY_FOLDER)));
          String version =
              formatVersion(
                  windowsRegistry.getStringValue(
                      WindowsRegistry.Key.HKEY_LOCAL_MACHINE, basePath, REGISTRY_VERSION));
          String name =
              windowsRegistry.getStringValue(
                  WindowsRegistry.Key.HKEY_LOCAL_MACHINE, basePath, REGISTRY_NAME);

          if (isWindowsSdk(sdkDir)) {
            LOGGER.debug("Found Windows SDK {} at {}", version, sdkDir);
            addSdk(sdkDir, version, name);
          } else {
            LOGGER.debug(
                "Ignoring candidate Windows SDK directory {} as it does not look like a Windows SDK installation.",
                sdkDir);
          }
        } catch (MissingRegistryEntryException e) {
          // Ignore the subkey if it doesn't have a folder and version
        }
      }
    } catch (MissingRegistryEntryException e) {
      // No SDK information available in the registry
    }
  }
 public void contributeCommandLineOptions(ExecSpec execHandleBuilder) {
   execHandleBuilder
       .args(GUtil.prefix("-J", jFlags)) // J flags can not be set in the option file
       .args(GUtil.prefix("@", GFileUtils.toPaths(optionFiles))); // add additional option files
 }