#!/usr/bin/env --split-string=${JDK_HOME}/bin/java @Makeshift/java_arguments @Makeshift/java_javac_arguments \c [SS]

// This command runs directly from the present source file, it needs no compiling.

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

import static java.nio.file.FileVisitResult.CONTINUE;
import static java.lang.System.out;


/** A shell command to remove all impermanent state and output files.
  *
  *     @see <a href='http://reluk.ca/project/Makeshift/bin/clean.brec.xht'>
  *       The `clean` command</a>
  */
public final class CleanCommand extends SimpleFileVisitor<Path> { // [AFN]



    private CleanCommand() {}



    /** Takes a `clean` command from the shell and executes it.
      */
    public static void main( final String[] arguments ) throws IOException {
        if( arguments.length != 0 ) {
            System.err.println( "Usage: clean" );
            System.exit( 1 ); }
        new CleanCommand().run(); }



   // ━━━  F i l e   V i s i t o r  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━


    public @Override FileVisitResult visitFile( final Path file, BasicFileAttributes _a )
          throws IOException {
        return delete( file ); }



    public @Override FileVisitResult postVisitDirectory( final Path directory, final IOException x )
          throws IOException {
        if( x != null ) throw x;
        return delete( directory ); }



////  P r i v a t e  ////////////////////////////////////////////////////////////////////////////////////


    private int count; // Of files deleted.



    private FileVisitResult delete( final Path path ) throws IOException {
        Files.delete( path );
        ++count;
        return CONTINUE; }



    private void run() throws IOException {
        final Path projectOutputDirectory = Path.of( System.getProperty("java.io.tmpdir"),
          "Makeshift" );
        if( !Files.isDirectory( projectOutputDirectory )) return;
        Files.walkFileTree( projectOutputDirectory, CleanCommand.this );
        if( count > 0 ) {
            out.print( count );
            out.print( " intermediate output file" );
            if( count > 1 ) out.print( 's' );
            out.println( " deleted" ); }}}



// NOTES
// ─────
//   AFN  Atypical file naming is allowed here, as explained in `./build`.
//
//   SS · Long-form option `--split-string` is for Emacs, as explained in `./build`.



                                            // Copyright © 2020, 2022, 2024  Michael Allan.  Licence MIT.