Java Code Examples for org.codehaus.plexus.util.DirectoryScanner#scan()

The following examples show how to use org.codehaus.plexus.util.DirectoryScanner#scan() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ThemeBuilderUtils.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Retrieves a list of file names that are in the given directory, possibly filtered by the list of include
 * patterns or exclude patterns
 *
 * @param baseDirectory directory to retrieve file names from
 * @param includes list of patterns to match against for file names to include, can include Ant patterns
 * @param excludes list of patterns to match for excluded file names, can include Ant patterns
 * @return list of file names within the directory that match all given patterns
 */
public static List<String> getDirectoryFileNames(File baseDirectory, String[] includes, String[] excludes) {
    List<String> files = new ArrayList<String>();

    DirectoryScanner scanner = new DirectoryScanner();

    if (includes != null) {
        scanner.setIncludes(includes);
    }

    if (excludes != null) {
        scanner.setExcludes(excludes);
    }

    scanner.setCaseSensitive(false);
    scanner.addDefaultExcludes();
    scanner.setBasedir(baseDirectory);

    scanner.scan();

    for (String includedFilename : scanner.getIncludedFiles()) {
        files.add(includedFilename);
    }

    return files;
}
 
Example 2
Source File: ProjectScanner.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the list of packages from {@literal src/test/java}. This method scans for ".class" files in {@literal
 * target/test-classes}.
 *
 * @return the list of packages, empty if none.
 */
public Set<String> getPackagesFromTestSources() {
    Set<String> packages = new LinkedHashSet<>();
    File classes = new File(basedir, "target/test-classes");
    if (classes.isDirectory()) {
        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir(classes);
        scanner.setIncludes(new String[]{"**/*.class"});
        scanner.addDefaultExcludes();
        scanner.scan();

        for (int i = 0; i < scanner.getIncludedFiles().length; i++) {
            packages.add(Packages.getPackageName(scanner.getIncludedFiles()[i]));
        }
    }

    return packages;
}
 
Example 3
Source File: AbstractRunMojo.java    From vertx-maven-plugin with Apache License 2.0 6 votes vote down vote up
private File lookForConfiguration(String filename) {
    File confBaseDir = new File(project.getBasedir(), DEFAULT_CONF_DIR);
    if (!confBaseDir.isDirectory()) {
        return null;
    }
    DirectoryScanner directoryScanner = new DirectoryScanner();
    directoryScanner.setBasedir(confBaseDir);
    String[] includes = Stream.concat(Stream.of(JSON_EXTENSION), YAML_EXTENSIONS.stream())
        .map(ext -> filename + ext)
        .toArray(String[]::new);
    directoryScanner.setIncludes(includes);
    directoryScanner.scan();
    return Arrays.stream(directoryScanner.getIncludedFiles())
        .map(found -> new File(confBaseDir, found))
        .findFirst()
        .orElse(null);
}
 
Example 4
Source File: AbstractImpSortMojo.java    From impsort-maven-plugin with Apache License 2.0 6 votes vote down vote up
private Stream<File> searchDir(File dir, boolean warnOnBadDir) {
  if (dir == null || !dir.exists() || !dir.isDirectory()) {
    if (warnOnBadDir && dir != null) {
      getLog().warn("Directory does not exist or is not a directory: " + dir);
    }
    return Stream.empty();
  }
  getLog().debug("Adding directory " + dir);
  DirectoryScanner ds = new DirectoryScanner();
  ds.setBasedir(dir);
  ds.setIncludes(includes != null && includes.length > 0 ? includes : DEFAULT_INCLUDES);
  ds.setExcludes(excludes);
  ds.addDefaultExcludes();
  ds.setCaseSensitive(false);
  ds.setFollowSymlinks(false);
  ds.scan();
  return Stream.of(ds.getIncludedFiles()).map(filename -> new File(dir, filename)).parallel();
}
 
Example 5
Source File: ValidationSet.java    From yaml-json-validator-maven-plugin with Apache License 2.0 6 votes vote down vote up
public File[] getFiles(final File basedir) {
    final DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(basedir);
    if (includes != null && includes.length > 0) {
        ds.setIncludes(includes);
    }
    if (excludes != null && excludes.length > 0) {
        ds.setExcludes(excludes);
    }
    ds.scan();
    final String[] filePaths = ds.getIncludedFiles();
    final File[] files = new File[filePaths.length];

    for (int i = 0; i < filePaths.length; i++) {
        files[i] = new File(basedir, filePaths[i]);
    }

    return files;
}
 
Example 6
Source File: AbstractXtendCompilerMojo.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
private String scanBootclasspath(String javaHome, String[] includes, String[] excludes) {
	getLog().debug(
			"Scanning bootClassPath:\n" + "\tjavaHome = " + javaHome + "\n" + "\tincludes = "
					+ Arrays.toString(includes) + "\n" + "\texcludes = " + Arrays.toString(excludes));
	DirectoryScanner scanner = new DirectoryScanner();
	scanner.setBasedir(new File(javaHome));
	scanner.setIncludes(includes);
	scanner.setExcludes(excludes);
	scanner.scan();

	StringBuilder bootClassPath = new StringBuilder();
	String[] includedFiles = scanner.getIncludedFiles();
	for (int i = 0; i < includedFiles.length; i++) {
		if (i > 0) {
			bootClassPath.append(File.pathSeparator);
		}
		bootClassPath.append(new File(javaHome, includedFiles[i]).getAbsolutePath());
	}
	return bootClassPath.toString();
}
 
Example 7
Source File: ProjectScanner.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the list of packages from {@literal src/main/java}. This method scans for ".class" files in {@literal
 * target/classes}.
 *
 * @return the list of packages, empty if none.
 */
public Set<String> getPackagesFromMainSources() {
    Set<String> packages = new LinkedHashSet<>();
    File classes = getClassesDirectory();
    if (classes.isDirectory()) {
        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir(classes);
        scanner.setIncludes(new String[]{"**/*.class"});
        scanner.addDefaultExcludes();
        scanner.scan();

        for (int i = 0; i < scanner.getIncludedFiles().length; i++) {
            packages.add(Packages.getPackageName(scanner.getIncludedFiles()[i]));
        }
    }

    return packages;
}
 
Example 8
Source File: ThemeBuilderUtils.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Retrieves a list of files and directories that are in the given directory, possibly filtered by the
 * list of include patterns or exclude patterns
 *
 * @param baseDirectory directory to retrieve files and directories from
 * @param includes list of patterns to match against for files to include, can include Ant patterns
 * @param excludes list of patterns to match for excluded files, can include Ant patterns
 * @return list of files within the directory that match all given patterns
 */
public static List<String> getDirectoryContents(File baseDirectory, String[] includes, String[] excludes) {
    List<String> contents = new ArrayList<String>();

    DirectoryScanner scanner = new DirectoryScanner();

    if (includes != null) {
        scanner.setIncludes(includes);
    }

    if (excludes != null) {
        scanner.setExcludes(excludes);
    }

    scanner.setCaseSensitive(false);
    scanner.addDefaultExcludes();
    scanner.setBasedir(baseDirectory);

    scanner.scan();

    for (String includedDirectory : scanner.getIncludedDirectories()) {
        contents.add(includedDirectory);
    }

    for (String includedFilename : scanner.getIncludedFiles()) {
        contents.add(includedFilename);
    }

    return contents;
}
 
Example 9
Source File: CompileMojo.java    From twirl-maven-plugin with Apache License 2.0 5 votes vote down vote up
private static String[] findFiles(File dir, Set<String> includes, Set<String> excludes) {
  if (!dir.exists()) {
    return new String[0];
  }

  DirectoryScanner scanner = new DirectoryScanner();
  scanner.setBasedir(dir);
  scanner.setIncludes(includes.toArray(new String[includes.size()]));
  scanner.setExcludes(excludes.toArray(new String[excludes.size()]));
  scanner.addDefaultExcludes();
  scanner.scan();
  return scanner.getIncludedFiles();
}
 
Example 10
Source File: TcasesMojoTest.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the set of paths relative to the given base directory matching any of the given patterns.
 */
private String[] findPathsMatching( File baseDir, String... patterns)
  {
  DirectoryScanner scanner = new DirectoryScanner();
  scanner.setBasedir( baseDir);
  scanner.setIncludes( patterns);
  scanner.scan();
  return scanner.getIncludedFiles();
  }
 
Example 11
Source File: ApiMojoTest.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the set of paths relative to the given base directory matching any of the given patterns.
 */
private String[] findPathsMatching( File baseDir, String... patterns)
  {
  DirectoryScanner scanner = new DirectoryScanner();
  scanner.setBasedir( baseDir);
  scanner.setIncludes( patterns);
  scanner.scan();
  return scanner.getIncludedFiles();
  }
 
Example 12
Source File: ThemeBuilderUtils.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Copies all the contents from the directory given by the source path to the directory given by the
 * target path
 *
 * <p>
 * If source directory does not exist nothing is performed. The target directory will be created if it
 * does not exist. Any hidden directories (directory names that start with ".") will be deleted from the
 * target directory
 * </p>
 *
 * @param sourceDirectoryPath absolute path to the source directory
 * @param targetDirectoryPath absolute path to the target directory
 * @throws IOException
 */
public static void copyDirectory(String sourceDirectoryPath, String targetDirectoryPath)
        throws IOException {
    File sourceDir = new File(sourceDirectoryPath);

    if (!sourceDir.exists()) {
        return;
    }

    File targetDir = new File(targetDirectoryPath);
    if (targetDir.exists()) {
        // force removal so the copy starts clean
        FileUtils.forceDelete(targetDir);
    }

    targetDir.mkdir();

    FileUtils.copyDirectoryStructure(sourceDir, targetDir);

    // remove hidden directories from the target
    DirectoryScanner scanner = new DirectoryScanner();
    scanner.setBasedir(targetDir);

    scanner.scan();

    for (String includedDirectory : scanner.getIncludedDirectories()) {
        File subdirectory = new File(targetDir, includedDirectory);

        if (subdirectory.exists() && subdirectory.isDirectory()) {
            if (subdirectory.getName().startsWith(".")) {
                FileUtils.forceDelete(subdirectory);
            }
        }
    }
}
 
Example 13
Source File: ProjectUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static Set<Path> collectBinaries(IPath projectDir, Set<String> include, Set<String> exclude, IProgressMonitor monitor) throws CoreException {
	Set<Path> binaries = new LinkedHashSet<>();
	Map<IPath, Set<String>> includeByPrefix = groupGlobsByPrefix(projectDir, include);
	Set<IPath> excludeResolved = exclude.stream().map(glob -> resolveGlobPath(projectDir, glob)).collect(Collectors.toSet());
	for (IPath baseDir: includeByPrefix.keySet()) {
		Path base = baseDir.toFile().toPath();
		if (monitor.isCanceled()) {
			return binaries;
		}
		if (Files.isRegularFile(base)) {
			if (isBinary(base))	{
				binaries.add(base);
			}
			continue; // base is a regular file path
		}
		if (!Files.isDirectory(base)) {
			continue; // base does not exist
		}
		Set<String> subInclude = includeByPrefix.get(baseDir);
		Set<String> subExclude = excludeResolved.stream().map(glob -> glob.makeRelativeTo(baseDir).toOSString()).collect(Collectors.toSet());
		DirectoryScanner scanner = new DirectoryScanner();
		try {
			scanner.setIncludes(subInclude.toArray(new String[subInclude.size()]));
			scanner.setExcludes(subExclude.toArray(new String[subExclude.size()]));
			scanner.addDefaultExcludes();
			scanner.setBasedir(base.toFile());
			scanner.scan();
		} catch (IllegalStateException e) {
			throw new CoreException(StatusFactory.newErrorStatus("Unable to collect binaries", e));
		}
		for (String result: scanner.getIncludedFiles()) {
			Path file = base.resolve(result);
			if (isBinary(file))	{
				binaries.add(file);
			}
		}
	}
	return binaries;
}
 
Example 14
Source File: GitHub.java    From opoopress with Apache License 2.0 5 votes vote down vote up
/**
 * Get matching paths found in given base directory
 *
 * @param includes
 * @param excludes
 * @param baseDir
 * @return non-null but possibly empty array of string paths relative to the
 *         base directory
 */
public static String[] getMatchingPaths(final String[] includes,
		final String[] excludes, final String baseDir) {
	DirectoryScanner scanner = new DirectoryScanner();
	scanner.setBasedir(baseDir);
	if (includes != null && includes.length > 0){
		scanner.setIncludes(includes);
	}
	if (excludes != null && excludes.length > 0){
		scanner.setExcludes(excludes);
	}
	scanner.scan();
	return scanner.getIncludedFiles();
}
 
Example 15
Source File: FilteredResourcesCoSSkipper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean hasChangedResources(Resource r, long stamp) {
        String dir = r.getDirectory();
        File dirFile = FileUtil.normalizeFile(new File(dir));
  //      System.out.println("checkresource dirfile =" + dirFile);
        if (dirFile.exists()) {
            List<File> toCopy = new ArrayList<File>();
            DirectoryScanner ds = new DirectoryScanner();
            ds.setBasedir(dirFile);
            //includes/excludes
            String[] incls = r.getIncludes().toArray(new String[0]);
            if (incls.length > 0) {
                ds.setIncludes(incls);
            } else {
                ds.setIncludes(DEFAULT_INCLUDES);
            }
            String[] excls = r.getExcludes().toArray(new String[0]);
            if (excls.length > 0) {
                ds.setExcludes(excls);
            }
            ds.addDefaultExcludes();
            ds.scan();
            String[] inclds = ds.getIncludedFiles();
//            System.out.println("found=" + inclds.length);
            for (String inc : inclds) {
                File f = new File(dirFile, inc);
                if (f.lastModified() >= stamp) { 
                    toCopy.add(FileUtil.normalizeFile(f));
                }
            }
            if (toCopy.size() > 0) {
                    //the case of filtering source roots, here we want to return false
                    //to skip CoS altogether.
                return true;
            }
        }
        return false;
    }
 
Example 16
Source File: RequireEncoding.java    From extra-enforcer-rules with Apache License 2.0 4 votes vote down vote up
public void execute( EnforcerRuleHelper helper )
    throws EnforcerRuleException
{
    try
    {
        if ( StringUtils.isBlank( encoding ) )
        {
            encoding = (String) helper.evaluate( "${project.build.sourceEncoding}" );
        }
        Log log = helper.getLog();

        Set< String > acceptedEncodings = new HashSet< String >( Arrays.asList( encoding ) );
        if ( encoding.equals( StandardCharsets.US_ASCII.name() ) )
        {
            log.warn( "Encoding US-ASCII is hard to detect. Use UTF-8 or ISO-8859-1" );
        }

        if ( acceptAsciiSubset && ( encoding.equals( StandardCharsets.ISO_8859_1.name() ) || encoding.equals( StandardCharsets.UTF_8.name() ) ) )
        {
            acceptedEncodings.add( StandardCharsets.US_ASCII.name() );
        }

        String basedir = (String) helper.evaluate( "${basedir}" );
        DirectoryScanner ds = new DirectoryScanner();
        ds.setBasedir( basedir );
        if ( StringUtils.isNotBlank( includes ) )
        {
            ds.setIncludes( includes.split( "[,\\|]" ) );
        }
        if ( StringUtils.isNotBlank( excludes ) )
        {
            ds.setExcludes( excludes.split( "[,\\|]" ) );
        }
        if ( useDefaultExcludes )
        {
            ds.addDefaultExcludes();
        }
        ds.scan();
        StringBuilder filesInMsg = new StringBuilder();
        for ( String file : ds.getIncludedFiles() )
        {
            String fileEncoding = getEncoding( encoding, new File( basedir, file ), log );
            if ( log.isDebugEnabled() )
            {
                log.debug( file + "==>" + fileEncoding );
            }
            if ( fileEncoding != null && !acceptedEncodings.contains( fileEncoding ) )
            {
                filesInMsg.append( file );
                filesInMsg.append( "==>" );
                filesInMsg.append( fileEncoding );
                filesInMsg.append( "\n" );
                if ( failFast )
                {
                    throw new EnforcerRuleException( filesInMsg.toString() );
                }
            }
        }
        if ( filesInMsg.length() > 0 )
        {
            throw new EnforcerRuleException( "Files not encoded in " + encoding + ":\n" + filesInMsg );
        }
    }
    catch ( IOException ex )
    {
        throw new EnforcerRuleException( "Reading Files", ex );
    }
    catch ( ExpressionEvaluationException e )
    {
        throw new EnforcerRuleException( "Unable to lookup an expression " + e.getLocalizedMessage(), e );
    }
}
 
Example 17
Source File: ApiMojo.java    From tcases with MIT License 4 votes vote down vote up
public void execute() throws MojoExecutionException
{
try
  {
  // Gather API spec files
  DirectoryScanner inputScanner = new DirectoryScanner();
  Set<String> apiDefPatterns = getApiDefs();
  if( !apiDefPatterns.isEmpty())
    {
    // Use all specified API spec patterns.
    }
  else if( !StringUtils.isBlank( getProject()))
    {
    // Use API spec(s) for specified project name.
    apiDefPatterns.add( "**/" + getProject() + ".json");
    apiDefPatterns.add( "**/" + getProject() + ".yaml");
    apiDefPatterns.add( "**/" + getProject() + ".yml");
    }
  else if( !StringUtils.isBlank( getApiDef())) 
    {
    // Use specified API spec pattern.
    apiDefPatterns.add( getApiDef());
    }
  else
    {
    // Use default patterns
    apiDefPatterns.add( "**/*.json");
    apiDefPatterns.add( "**/*.yaml");
    apiDefPatterns.add( "**/*.yml");
    }
  inputScanner.setIncludes( apiDefPatterns.toArray( new String[0]));

  File inputRootDir = getInputDirFile();
  inputScanner.setBasedir( inputRootDir);
  inputScanner.scan();

  // Generate requested models for each API spec
  String[] apiDefs = inputScanner.getIncludedFiles();
  for( int i = 0; i < apiDefs.length; i++)
    {
    // Define input path for this API spec.
    String inputFile = apiDefs[i];
    File apiDef = new File( inputRootDir, inputFile);

    // Set generator options for this API spec.
    Options options = new Options();
    options.setApiSpec( apiDef);
    options.setContentType( getContentType());
    options.setOutDir( new File( getOutDirFile(), getPath( inputFile)));
    if( isJunit())
      {
      options.setTransformType( TransformType.JUNIT);
      }
    if( isHtml())
      {
      options.setTransformType( TransformType.HTML);
      }
    if( getTransformDef() != null)
      {
      options.setTransformType( TransformType.CUSTOM);
      options.setTransformParams( getTransformParams());
      }
    options.setTests( !isInputModels());
    options.setOnModellingCondition( "log".equals( getOnModellingCondition())? getOnCondition() : getOnModellingCondition());
    options.setReadOnlyEnforced( isReadOnlyEnforced());
    options.setWriteOnlyEnforced( isWriteOnlyEnforced());
    
    // Generate requested request test models for this API spec
    if( isRequestCases())
      {
      options.setRequestCases( true);
      options.setOnResolverCondition( getOnResolverCondition());
      options.setMaxTries( getMaxTries());
      options.setRandomSeed( getRandom());
      }
    else
      {
      options.setServerTest( true);
      options.setTransformDef( resolveTransformDefFile( apiDef, options.isServerTest()));
      options.setOutFile( resolveTransformOutFile( apiDef, options.isServerTest()));
      }
    ApiCommand.run( options);

    // Generate requested response test models for this API spec
    options.setServerTest( false);
    options.setTransformDef( resolveTransformDefFile( apiDef, options.isServerTest()));
    options.setOutFile( resolveTransformOutFile( apiDef, options.isServerTest()));
    ApiCommand.run( options);
    }
  }
catch( Exception e)
  {
  throw new MojoExecutionException( "Can't generate requested models", e);
  }
}
 
Example 18
Source File: ApiTestMojo.java    From tcases with MIT License 4 votes vote down vote up
public void execute() throws MojoExecutionException
{
try
  {
  // Gather API spec files
  DirectoryScanner inputScanner = new DirectoryScanner();
  Set<String> apiDefPatterns = getApiDefs();
  if( !apiDefPatterns.isEmpty())
    {
    // Use all specified API spec patterns.
    }
  else if( !StringUtils.isBlank( getProject()))
    {
    // Use API spec(s) for specified project name.
    apiDefPatterns.add( "**/" + getProject() + ".json");
    apiDefPatterns.add( "**/" + getProject() + ".yaml");
    apiDefPatterns.add( "**/" + getProject() + ".yml");
    }
  else if( !StringUtils.isBlank( getApiDef())) 
    {
    // Use specified API spec pattern.
    apiDefPatterns.add( getApiDef());
    }
  else
    {
    // Use default patterns
    apiDefPatterns.add( "**/*.json");
    apiDefPatterns.add( "**/*.yaml");
    apiDefPatterns.add( "**/*.yml");
    }
  inputScanner.setIncludes( apiDefPatterns.toArray( new String[0]));

  File inputRootDir = getInputDirFile();
  inputScanner.setBasedir( inputRootDir);
  inputScanner.scan();

  // Generate a test for each API spec
  String[] apiDefs = inputScanner.getIncludedFiles();
  for( int i = 0; i < apiDefs.length; i++)
    {
    // Define input path for this API spec.
    String inputFile = apiDefs[i];
    File apiDef = new File( inputRootDir, inputFile);

    // Set generator options for this API spec.
    Options options = new Options();
    options.setApiSpec( apiDef);
    options.setTestType( getTestType());
    options.setExecType( getExecType());
    options.setTestName( getTestName());
    options.setTestPackage( getTestPackage());
    options.setBaseClass( getBaseClass());
    options.setMocoTestConfig( getMocoTestConfigFile());
    options.setPaths( getPaths());
    options.setOperations( getOperations());
    options.setContentType( getContentType());
    options.setOutDir( new File( getOutDirFile(), getPath( inputFile)));
    options.setOnModellingCondition( getOnModellingCondition());
    options.setOnResolverCondition( getOnResolverCondition());
    options.setReadOnlyEnforced( isReadOnlyEnforced());
    options.setMaxTries( getMaxTries());
    options.setRandomSeed( getRandom());

    ApiTestCommand.run( options);
    }
  }
catch( Exception e)
  {
  throw new MojoExecutionException( "Can't generate requested tests", e);
  }
}
 
Example 19
Source File: ReducerMojo.java    From tcases with MIT License 4 votes vote down vote up
public void execute() throws MojoExecutionException
{
try
  {
  // Gather input definition files
  DirectoryScanner inputScanner = new DirectoryScanner();
  Set<String> inputDefPatterns = getInputDefs();
  if( !inputDefPatterns.isEmpty())
    {
    // Use all specified input definition patterns.
    }
  else if( !StringUtils.isBlank( getProject()))
    {
    // Use input definition(s) for specified project name.
    inputDefPatterns.add( "**/" + getProject() + "-Input.xml");
    inputDefPatterns.add( "**/" + getProject() + ".xml");
    inputDefPatterns.add( "**/" + getProject() + "-Input.json");
    inputDefPatterns.add( "**/" + getProject() + ".json");
    }
  else if( !StringUtils.isBlank( getInputDef())) 
    {
    // Use specified input definition pattern.
    inputDefPatterns.add( getInputDef());
    }
  else
    {
    // Use default patterns
    inputDefPatterns.add( "**/*-Input.xml");
    inputDefPatterns.add( "**/*-Input.json");
    }
  inputScanner.setIncludes( inputDefPatterns.toArray( new String[0]));

  File inputRootDir = getInputDirFile();
  inputScanner.setBasedir( inputRootDir);
  inputScanner.scan();

  // Reduce test cases for each input definition file.
  ReducerCommand reducer = new ReducerCommand();
  String[] inputDefs = inputScanner.getIncludedFiles();
  for( int i = 0; i < inputDefs.length; i++)
    {
    // Define input path for this Tcases project.
    String inputFile = inputDefs[i];
    String inputPath = FileUtils.dirname( inputFile);
    File inputDef = new File( inputRootDir, inputFile);
    File inputDir = new File( inputRootDir, inputPath);

    String projectName = TcasesCommand.getProjectName( inputDef);

    String testDef = getTestDef();
    if( testDef != null && (testDef = getProjectFile( projectName, testDef)) == null)
      {
      throw new IllegalArgumentException( "Invalid testDef pattern='" + getTestDef() + "'");
      }

    String genDef = getGenDef();
    if( genDef != null && (genDef = getProjectFile( projectName, genDef)) == null)
      {
      throw new IllegalArgumentException( "Invalid genDef pattern='" + getGenDef() + "'");
      }
    
    // Set Reducer options for this Tcases project.
    Options options = new Options();
    options.setInputDef( inputDef);
    options.setGenDef( genDef==null? null : new File( inputDir, genDef));
    options.setTestDef( testDef==null? null : new File( inputDir, testDef));
    options.setFunction( getFunction());
    options.setSamples( getSamples());
    options.setResampleFactor( getResampleFactor());
    options.setNewSeed( isNewSeed());
    options.setContentType( getContentType());

    // Reduce test cases for this Tcases project.
    reducer.run( options);
    }
  }
catch( Exception e)
  {
  throw new MojoExecutionException( "Can't reduce test cases", e);
  }
}
 
Example 20
Source File: BasePrepareSources.java    From gradle-golang-plugin with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public void run()  throws  Exception {
    final ProgressLogger progress = startProgress("Prepare sources");

    final GolangSettings settings = getGolang();
    final BuildSettings build = getBuild();
    boolean atLeastOneCopied = false;
    if (!FALSE.equals(build.getUseTemporaryGopath())) {
        final Path gopath = build.getFirstGopath();
        progress.progress("Prepare GOPATH " + gopath + "...");
        LOGGER.info("Prepare GOPATH ({})...", gopath);
        final Path projectBasedir = settings.getProjectBasedir();
        final Path packagePath = settings.packagePathFor(gopath);
        final Path dependencyCachePath = getDependencies().getDependencyCache();
        prepareDependencyCacheIfNeeded(packagePath, dependencyCachePath);

        final DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir(projectBasedir.toFile());
        scanner.setIncludes(build.getIncludes());
        scanner.setExcludes(build.getExcludes());
        scanner.setCaseSensitive(true);
        scanner.scan();
        for (final String file : scanner.getIncludedFiles()) {
            final Path sourceFile = projectBasedir.resolve(file);
            final Path targetFile = packagePath.resolve(file);
            if (!sourceFile.equals(dependencyCachePath)) {
                if (!exists(targetFile)
                    || size(sourceFile) != size(targetFile)
                    || !getLastModifiedTime(sourceFile).equals(getLastModifiedTime(targetFile))) {
                    atLeastOneCopied = true;
                    progress.progress("Prepare source file: " + file + "...");
                    LOGGER.debug("* {}", file);
                    ensureParentOf(targetFile);
                    try (final InputStream is = newInputStream(sourceFile)) {
                        try (final OutputStream os = newOutputStream(targetFile)) {
                            IOUtils.copy(is, os);
                        }
                    }
                    setLastModifiedTime(targetFile, getLastModifiedTime(sourceFile));
                }
            }
        }
        if (!atLeastOneCopied) {
            getState().setOutcome(UP_TO_DATE);
        }
    } else {
        getState().setOutcome(SKIPPED);
    }

    progress.completed();
}