All Downloads are FREE. Search and download functionalities are using the official Maven repository.

eu.cedarsoft.devtools.DirectorySupport Maven / Gradle / Ivy

The newest version!
package eu.cedarsoft.devtools;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;

/**
 * Utility methods for several directory related things
 */
@Singleton
public class DirectorySupport {
  @NotNull
  protected final File projectRoot;

  /**
   * Creates a new directory support
   *
   * @param projectRoot the project root
   */
  @Inject
  public DirectorySupport( @ProjectRoot @NotNull File projectRoot ) {
    this.projectRoot = projectRoot;
  }

  /**
   * Returns the root directory for all projects
   *
   * @return the project root
   */
  @NotNull
  public File getProjectRoot() {
    if ( !projectRoot.exists() ) {
      throw new IllegalStateException( "ProjectRoot does not exist: " + projectRoot.getAbsolutePath() );
    }

    if ( !projectRoot.isDirectory() ) {
      throw new IllegalStateException( "ProjectRoot is not a directory: " + projectRoot.getAbsolutePath() );
    }
    return projectRoot;
  }

  /**
   * Returns whether the given file is within the project root
   *
   * @param file the directory that is checked
   * @return whether the file is within the project root
   *
   * @throws IOException
   */
  public boolean isInProjectRoot( @NotNull File file ) throws IOException {
    return file.getCanonicalPath().startsWith( getProjectRoot().getCanonicalPath() );
  }

  /**
   * Returns the project root path
   *
   * @return the project root path
   */
  @NotNull
  String getProjectRootPath() {
    return projectRoot.getAbsolutePath();
  }

  /**
   * Returns the sub path within the project root
   *
   * @param current the directory
   * @return the sub path
   *
   * @throws IOException
   */
  @NotNull
  public String getProjectSubPath( @NotNull File current ) throws IOException {
    if ( !isInProjectRoot( current ) ) {
      throw new IllegalArgumentException( "Is not in project path: " + current.getCanonicalPath() );
    }
    String currentPath = current.getCanonicalPath();
    String projectRootPath = getProjectRoot().getCanonicalPath();

    return currentPath.substring( projectRootPath.length() + 1, currentPath.length() );
  }

  /**
   * Returns the home dir
   *
   * @return the home dir
   */
  @NotNull
  public static File getHomeDir() {
    return new File( System.getProperty( "user.home" ) );
  }

  /**
   * Returns the temp dir
   *
   * @return the temp dir
   */
  @NotNull
  public static File getTempDir() {
    return new File( System.getProperty( "java.io.tmpdir" ) );
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy