diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..7e10cd8 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,47 @@ +name: 🔨 Build and Check PR 🚀 + +on: + pull_request: + branches: + - main + push: + branches: + - main + +jobs: + build: + runs-on: ubuntu-latest + + steps: + # Step 1: Checkout the repository 📂 + - name: 📥 Checkout repository + uses: actions/checkout@v4 + + # Step 2: Set up Zulu JDK 17 ☕ + - name: ☕ Set up Zulu JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' # Set the desired JDK version + distribution: 'zulu' # Specify Zulu as the distribution + + # Step 3: Build the project 🔨 + - name: 🔨 Run Gradle build + run: ./gradlew build --no-daemon + + # Step 4: Create the shadow JAR 📦 + - name: 🛠️ Build Shadow JAR + run: ./gradlew shadowJar --no-daemon + + # Step 5: Get the name of the generated jar file + - name: 🧾 Get the shadowJar file name + id: get_jar_name + run: | + JAR_NAME=$(basename build/libs/*.jar) + echo "jar_name=$JAR_NAME" >> $GITHUB_ENV + + # Step 6: Upload the shadowJar artifact (optional) 🎁 + - name: 🎁 Upload shadowJar + uses: actions/upload-artifact@v4 + with: + name: ${{ env.jar_name }} + path: build/libs/${{ env.jar_name }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..5e03970 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,71 @@ +name: Create Release 🎉 + +on: + push: + tags: + - 'v*' # Trigger on version tag pushes (e.g., v1.0, v2.0) + +jobs: + build: + runs-on: ubuntu-latest + + steps: + # Step 1: Checkout the repository + - name: 🛎️ Checkout code + uses: actions/checkout@v4 + + # Step 2: Set up JDK (using Zulu) + - name: ☕ Set up Zulu JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' # Specify the JDK version + distribution: 'zulu' + + # Step 3: Build the project and create shadowJar + - name: 🚧 Build with Gradle + run: ./gradlew shadowJar --no-daemon + + # Step 4: Create a new release + - name: 📦 Create Release + id: create_release + uses: actions/github-script@v6 + with: + script: | + const { exec } = require('child_process'); + const { promises: fs } = require('fs'); + + // Get the latest tag + const tag = context.ref.replace('refs/tags/', ''); + + // Read the release notes if available + const releaseNotes = await fs.readFile('CHANGELOG.md', 'utf-8').catch(() => 'No release notes.'); + + // Create the release + const release = await github.rest.repos.createRelease({ + owner: context.repo.owner, + repo: context.repo.repo, + tag_name: tag, + name: tag, + body: releaseNotes, + draft: false, + prerelease: false, + }); + + return release.data; + + # Step 5: Upload the shadowJar artifact to the release + - name: 🎁 Upload shadowJar to Release + id: upload_jar + run: | + # Find the generated JAR file name + jar_file=$(ls build/libs/*.jar | grep -v '\-javadoc' | grep -v '\-sources' | head -n 1) + echo "Found JAR file: $jar_file" + echo "jar_file_name=$jar_file" >> $GITHUB_ENV + + - name: 🎁 Upload shadowJar to Release + uses: actions/upload-release-asset@v1 + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: ${{ env.jar_file_name }} + asset_name: ${{ env.jar_file_name }} # Use the dynamic name here + asset_content_type: application/java-archive diff --git a/.gitignore b/.gitignore index a0c9cda..6619c67 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,9 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* +.idea/ +.gradle/ +*.iml +build/ +toDelete +.DS_Store \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..9b4328d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,26 @@ +# Changelog + +## [Version 1.0] + +### Added +- Flag-based operations for **find** and **delete** functionalities, allowing users to specify operations more clearly using command-line flags. + +### Changed +- Organized the project structure using **Gradle**, making it easier to manage dependencies and build processes. + +### Updated +- Integrated JAR file usage for executing the application, simplifying the running process for users. + +### Removed +- Manual compilation steps are no longer required, enhancing user experience and reducing setup complexity. + +### Examples +- **Find duplicates**: + ```bash + java -jar search-and-delete-duplicates-1.0-SNAPSHOT.jar --find [...] + ``` + +- **Delete files**: + ```bash + java -jar search-and-delete-duplicates-1.0-SNAPSHOT.jar --delete + ``` \ No newline at end of file diff --git a/Deletion.java b/Deletion.java deleted file mode 100644 index 6b5696b..0000000 --- a/Deletion.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - - Copyright 2014 Krrishnaaaa - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.InputStream; -import java.security.MessageDigest; -import java.util.ArrayList; - -public class Deletion { - - public static void main(String[] args) { - if(args.length == 0) { - System.out.println("Provide file to delete a list"); - return; - } - BufferedReader br = null; - - try { - - String sCurrentLine; - - br = new BufferedReader(new FileReader(args[0])); - - while ((sCurrentLine = br.readLine()) != null) { - new File(sCurrentLine).delete(); - } - - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - if (br != null)br.close(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - -} - diff --git a/DuplicateDetails.java b/DuplicateDetails.java deleted file mode 100644 index 9a7a96d..0000000 --- a/DuplicateDetails.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - - Copyright 2014 Krrishnaaaa - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ -import java.util.HashSet; -import java.util.Set; - -public class DuplicateDetails { - - String md5; - Set filePath = new HashSet(); - -} diff --git a/Files.java b/Files.java deleted file mode 100644 index e033e72..0000000 --- a/Files.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - - Copyright 2014 Krrishnaaaa - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ -public class Files { - String md5, filePath; - - public String getMd5() { - return md5; - } - - public void setMd5(String md5) { - this.md5 = md5; - } - - public String getFilePath() { - return filePath; - } - - public void setFilePath(String filePath) { - this.filePath = filePath; - } - - @Override - public boolean equals(Object obj) { - if(obj instanceof Files) { - String checkMD5 = ((Files) obj).getMd5(); - return this.md5.equals(checkMD5); - } - return false; - } - -} diff --git a/ListFiles.java b/ListFiles.java deleted file mode 100644 index 50ffc4f..0000000 --- a/ListFiles.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - - Copyright 2014 Krrishnaaaa - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileWriter; -import java.io.InputStream; -import java.security.MessageDigest; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; - -public class ListFiles { - - public static void main(String[] args) { - if(args.length == 0) { - System.out.println("Usage: java ListFiles "); - return; - } - ArrayList mFiles = new ArrayList(); - - String rootPath = args[0]; - - File folder = new File(rootPath); - - System.out.println("\nSearching for duplicate files on path: " + rootPath); - - System.out.println("Processing started at " + new Date()); - - addFileToList(folder, mFiles); - - ArrayList dups = new ArrayList(); - - for (int i = 0; i < mFiles.size(); i++) { - Set completePath = new HashSet(); - DuplicateDetails details = new DuplicateDetails(); - for (int j = i + 1; j < mFiles.size(); j++) { - Files f1 = mFiles.get(i); - Files f2 = mFiles.get(j); - if (f1.equals(f2)) { - completePath.add(f1.getFilePath()); - completePath.add(f2.getFilePath()); - mFiles.remove(j); - j--; - } - if (completePath.size() > 0) { - details.filePath = completePath; - details.md5 = f1.getMd5(); - } - } - if (completePath.size() > 0) { - dups.add(details); - } - } - - System.out.println("\nDuplicate(s) of (" + dups.size() + ") file(s) found."); - String fileName = "./toDelete" - + args[0].replaceAll(File.separator, "_").replaceAll(" ", "_"); - System.out.println("\nList of duplicate files is stored in " + fileName); - File logFile = new File(fileName); - BufferedWriter writer = null; - try { - writer = new BufferedWriter(new FileWriter(logFile)); - - for (DuplicateDetails details : dups) { - writer.write(details.md5+"\n"); - for (String completePath : details.filePath) { - writer.write(completePath+"\n"); - } - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - if(writer != null) writer.close(); - } catch (Exception e) { - } - } - - System.out.println("\nProcessing ended at " + new Date()); - } - - private static int counter = 0; - - private static void addFileToList(File mFile, ArrayList mFiles) { - if (mFile.isFile()) { - counter++; - String path = mFile.getAbsolutePath(); - double kb = mFile.length()/1024.0; - String message = String.format("\r(%d) files scanned. Current file size : %10.2f KB", counter, kb); - System.out.print(message); - addFileToList(path, mFiles); - } else if (mFile.isDirectory()) { - for (File child : mFile.listFiles()) { - addFileToList(child, mFiles); - } - } - } - - static void addFileToList(String filePath, ArrayList mFiles) { - String md5 = fileToMD5(filePath); - Files files = new Files(); - files.setFilePath(filePath); - files.setMd5(md5); - mFiles.add(files); - } - - public static String fileToMD5(String filePath) { - InputStream inputStream = null; - try { - inputStream = new FileInputStream(filePath); - byte[] buffer = new byte[1024]; - MessageDigest digest = MessageDigest.getInstance("MD5"); - int numRead = 0; - while (numRead != -1) { - numRead = inputStream.read(buffer); - if (numRead > 0) - digest.update(buffer, 0, numRead); - } - byte[] md5Bytes = digest.digest(); - return convertHashToString(md5Bytes); - } catch (Exception e) { - return null; - } finally { - if (inputStream != null) { - try { - inputStream.close(); - } catch (Exception e) { - } - } - } - } - - private static String convertHashToString(byte[] md5Bytes) { - String returnVal = ""; - for (int i = 0; i < md5Bytes.length; i++) { - returnVal += Integer.toString((md5Bytes[i] & 0xff) + 0x100, 16).substring(1); - } - return returnVal.toUpperCase(); - } - -} - diff --git a/README.md b/README.md index 5083c5d..c4358c4 100644 --- a/README.md +++ b/README.md @@ -1,50 +1,81 @@ Search-and-Delete-duplicate-files ================================= - Prerequisites: - 1. JDK must be installed, and - 2. Path environments must be set. +This tool scans specified directories for duplicate files, automatically excluding common project and system directories. It helps users reclaim disk space by identifying and removing redundant files with ease. -How to use this? +## Prerequisites - Follow the steps to use it: - Step 1: Clone the repo - Step 2: Open `Terminal` or `Command Prompt` - Step 3: Navigate to the cloned repo - Step 4: Compile code `javac *.java` - Step 5: Run `java ListFiles ` - Step 6: After processing is completed a file will be generated with list of - duplicate files. Open the file and REMOVE THE ENTRIES WHICH YOU WANT TO KEEP. - Step 7: Run 'java Deletion ` - -Now it will delete all those files listed in `toDelete` file. +1. **JDK 17** must be installed. +2. Path environments must be set. - NOTE: - 1. File once deleted cannot be recovered. They will be deleted permanently. - So, be careful while using `Deletion`. - 2. Whenever you want to escape press +c [^c] to exit. +## How to use this +Follow the steps to use it: -Java source code to search a directory, recursively, for duplicate files. Well, this code is not commented, but feel free to query. +1. Download the JAR file: `search-and-delete-duplicates-1.0-SNAPSHOT.jar`. +2. Open `Terminal` or `Command Prompt`. +3. Run the command to find duplicates: + ```shell + java -jar search-and-delete-duplicates-1.0-SNAPSHOT.jar --find + ``` +4. After processing is completed, a file will be generated with a list of duplicate files. Open the file and REMOVE THE ENTRIES WHICH YOU WANT TO KEEP. +5. To delete the files listed in the `toDelete` file, run: + ```shell + java -jar search-and-delete-duplicates-1.0-SNAPSHOT.jar --delete + ``` -Feel free to reorganize code, and distribute your own version. I would be happy if you could state your name and application, in which this code is used. +## Usage +```shell +java -jar search-and-delete-duplicates-1.0-SNAPSHOT.jar --find [...] +java -jar search-and-delete-duplicates-1.0-SNAPSHOT.jar --delete +``` -Send email with following details: +## Examples +```shell +java -jar search-and-delete-duplicates-1.0-SNAPSHOT.jar --find ~/dir1 ~/dir2 +java -jar search-and-delete-duplicates-1.0-SNAPSHOT.jar --delete toDelete.txt +``` - To: krishna[at]pcsalt[dot]com - Subject: [Search-and-Delete-duplicate-files] - Message: [Name] [Application-Name] +## NOTE +1. File once deleted cannot be recovered. They will be deleted permanently. So, be careful while using `Deletion`. +2. Whenever you want to escape, press `+c` [^c] to exit. + +## Ignored Directories and Files + +When the program searches for duplicate files, it ignores specific directories and files to streamline the process and avoid unnecessary scanning of commonly used directories. + +### Ignored Directories +The following directories are excluded from the search: +- **.git**: This directory is used for version control by Git, and its contents are not relevant to duplicate file searching. +- **build**: This directory often contains compiled files generated during the build process, which are not considered duplicates. +- **node_modules**: This directory is used by Node.js projects to store dependencies and is typically large, so it is ignored. +- **.gradle**: This directory contains Gradle-specific files and caches, which do not need to be scanned. +- **.idea**: This directory is used by JetBrains IDEs (like IntelliJ IDEA) to store project-specific settings and configurations. + +### Ignored Files +The program also ignores the following file: +- **.DS_Store**: This is a file created by macOS to store custom attributes of a folder, and it is not useful for the duplicate file search. + +By excluding these directories and files, the program focuses on relevant files, enhancing performance and accuracy. + +Feel free to reorganize the code and distribute your own version. I would be happy if you could state your name and application in which this code is used. + +Send email with the following details: + +- **To:** krishna[at]pcsalt[dot]com +- **Subject:** [Search-and-Delete-duplicate-files] +- **Message:** [your-text] Thank you. - Copyright 2014 Krrishnaaaa - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +## License +Copyright 2014 Krrishnaaaa + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +[Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and limitations under the License. \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..2976bf4 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,53 @@ +plugins { + kotlin("jvm") version "1.9.10" + application + id("com.github.johnrengelman.shadow") version "8.1.1" +} + +group = "com.example" +version = "1.0-SNAPSHOT" + +repositories { + mavenCentral() +} + +sourceSets { + main { + kotlin.srcDirs("src/main/kotlin") + resources.srcDirs("src/main/resources") + } +} +dependencies { + implementation(kotlin("stdlib")) +} + +application { + mainClass.set("com.pcsalt.utility.MainKt") // Main class path +} + +tasks.jar { + manifest { + attributes["Main-Class"] = "com.pcsalt.utility.MainKt" + } + from(sourceSets.main.get().output) +} + +tasks { + shadowJar { + archiveBaseName.set("search-and-delete-duplicates") + archiveClassifier.set("") + archiveVersion.set("1.0-SNAPSHOT") + } +} + +tasks.named("startShadowScripts") { + dependsOn(tasks.named("jar")) +} + +tasks.named("startScripts") { + dependsOn(tasks.named("shadowJar")) +} + +tasks.named("distTar") { + dependsOn(tasks.named("shadowJar")) +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..7fc6f1f --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..9355b41 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..fa0eced --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "search-and-delete-duplicates" diff --git a/src/main/kotlin/com/pcsalt/utility/Deletion.kt b/src/main/kotlin/com/pcsalt/utility/Deletion.kt new file mode 100644 index 0000000..93b8021 --- /dev/null +++ b/src/main/kotlin/com/pcsalt/utility/Deletion.kt @@ -0,0 +1,61 @@ +/* + + Copyright 2014 Krrishnaaaa + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ +package com.pcsalt.utility + +import java.io.BufferedReader +import java.io.File +import java.io.FileReader + +class Deletion { + fun delete(args: List) { + if (args.isEmpty()) { + println("Provide a file to delete a list") + return + } + var br: BufferedReader? = null + + try { + var sCurrentLine: String? + br = BufferedReader(FileReader(args[0])) + while ((br.readLine().also { sCurrentLine = it }) != null) { + // Check if the line starts with '#' and ignore it + if (sCurrentLine!!.trim().startsWith("#")) { + continue // Skip the line + } + + // Attempt to delete the file + val fileToDelete = File(sCurrentLine) + if (fileToDelete.exists()) { + val size = fileToDelete.length() / 1024 + if (fileToDelete.delete()) { + println("Deleted: ${fileToDelete.absolutePath} | Size: $size kb") + } else { + println("Failed to delete: ${fileToDelete.absolutePath}") + } + } else { + println("File not found: ${fileToDelete.absolutePath}") + } + } + } catch (e: Exception) { + e.printStackTrace() + } finally { + try { + br?.close() + } catch (ex: Exception) { + ex.printStackTrace() + } + } + } +} diff --git a/src/main/kotlin/com/pcsalt/utility/ListFiles.kt b/src/main/kotlin/com/pcsalt/utility/ListFiles.kt new file mode 100644 index 0000000..6432b54 --- /dev/null +++ b/src/main/kotlin/com/pcsalt/utility/ListFiles.kt @@ -0,0 +1,152 @@ +/* + + Copyright 2014 Krrishnaaaa + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package com.pcsalt.utility + +import java.io.BufferedWriter +import java.io.File +import java.io.FileInputStream +import java.io.FileWriter +import java.security.MessageDigest +import java.util.Date +import java.util.Locale + +data class Files(val md5: String, val filePath: String) +data class DuplicateDetails(val md5: String, val filePath: Set) + +class ListFiles { + private var counter = 0 + private var totalFilesCount = 0 + private var lastMessageLength = 0 + + fun find(dirToSearch: List) { + + val mFiles = mutableListOf() + val duplicates = mutableMapOf>() // Map for grouping duplicates + val ignoreFolders = setOf(".git", "build", "node_modules", ".gradle", ".idea") // Specify folders to ignore + val ignoreFiles = setOf(".DS_Store") + + println("\nSearching for duplicate files in directories: ${dirToSearch.joinToString(", ")}") + println("Processing started at " + Date()) + for (rootPath in dirToSearch) { + countFiles(File(rootPath), ignoreFolders, ignoreFiles) + } + + println("Total files to scan: $totalFilesCount") + // Process each directory + for (rootPath in dirToSearch) { + addFilesToList(File(rootPath), mFiles, ignoreFolders, ignoreFiles) + } + + // Group files by MD5 hash + for (file in mFiles) { + duplicates.computeIfAbsent(file.md5) { mutableSetOf() }.add(file.filePath) + } + + // Filter out non-duplicates + val duplicateDetails = duplicates.filter { it.value.size > 1 } + .map { DuplicateDetails(it.key, it.value) } + + println("\nDuplicate(s) of (${duplicateDetails.size}) file(s) found.") + val logFileName = + "./toDelete" + dirToSearch.joinToString("_") { it.replace(File.separator.toRegex(), "_").replace(" ", "_") } + println("\nList of duplicate files is stored in $logFileName") + + // Write duplicates to log file + writeDuplicatesToFile(logFileName, duplicateDetails) + + println("\nProcessing ended at " + Date()) + } + + private fun countFiles(folder: File, ignoreFolders: Set, ignoreFiles: Set) { + if (folder.isDirectory) { + if (ignoreFolders.any { folder.resolve(it).exists() }) { + return + } + folder.listFiles()?.forEach { child -> countFiles(child, ignoreFolders, ignoreFiles) } + } else if (folder.isFile) { + if (!ignoreFiles.contains(folder.name)) { + totalFilesCount++ + } + } + } + + private fun addFilesToList( + folder: File, + mFiles: MutableList, + ignoreFolders: Set, + ignoreFiles: Set + ) { + if (folder.isFile) { + if (!ignoreFiles.contains(folder.name)) { + counter++ + val path = folder.absolutePath + val kb = folder.length() / 1024.0 + if (lastMessageLength > 0) print("\r"+" ".repeat(lastMessageLength)) + val message = String.format("\r(%d) files scanned. %s size : %10.2f KB", counter, folder.path, kb) + lastMessageLength = message.length + print(message) + addFileToList(path, mFiles) + } + } else if (folder.isDirectory) { + if (ignoreFolders.any { folder.resolve(it).exists() }) { + return + } + folder.listFiles()?.forEach { child -> addFilesToList(child, mFiles, ignoreFolders, ignoreFiles) } + } + } + + private fun addFileToList(filePath: String, mFiles: MutableList) { + val md5 = fileToMD5(filePath) + mFiles.add(Files(md5, filePath)) + } + + private fun fileToMD5(filePath: String): String { + FileInputStream(filePath).use { inputStream -> + val buffer = ByteArray(1024) + val digest = MessageDigest.getInstance("MD5") + var numRead: Int + while (inputStream.read(buffer).also { numRead = it } != -1) { + if (numRead > 0) digest.update(buffer, 0, numRead) + } + val md5Bytes = digest.digest() + return convertHashToString(md5Bytes) + } + } + + private fun convertHashToString(md5Bytes: ByteArray): String { + val returnVal = StringBuilder() + for (md5Byte in md5Bytes) { + returnVal.append(((md5Byte.toInt() and 0xff) + 0x100).toString(16).substring(1)) + } + return returnVal.toString().uppercase(Locale.getDefault()) + } + + private fun writeDuplicatesToFile(fileName: String, duplicateDetails: List) { + val logFile = File(fileName) + try { + BufferedWriter(FileWriter(logFile)).use { writer -> + for (details in duplicateDetails) { + writer.write("${details.md5}\n") + for (completePath in details.filePath) { + writer.write("$completePath\n") + } + } + } + } catch (e: Exception) { + e.printStackTrace() + } + } +} diff --git a/src/main/kotlin/com/pcsalt/utility/Main.kt b/src/main/kotlin/com/pcsalt/utility/Main.kt new file mode 100644 index 0000000..0a557de --- /dev/null +++ b/src/main/kotlin/com/pcsalt/utility/Main.kt @@ -0,0 +1,41 @@ +package com.pcsalt.utility + +fun main(args: Array) { + if (args.isEmpty()) { + printUsage() + return + } + + when { + args[0] == "--find" && args.size >= 3 -> { + val directories = args.drop(1) + println("Find command detected. Searching in directories: $directories") + ListFiles().find(directories) + } + + args[0] == "--delete" && args.size == 2 -> { + val fileToDelete = args.drop(1) + println("Delete command detected. Deleting files listed in: $fileToDelete") + Deletion().delete(fileToDelete) + } + + else -> { + println("Invalid arguments.") + printUsage() + } + } +} + +fun printUsage() { + println( + """ + Usage: + java -jar program.jar --find [...] + java -jar program.jar --delete + + Examples: + java -jar program.jar --find ~/dir1 ~/dir2 + java -jar program.jar --delete toDelete.txt + """.trimIndent() + ) +} \ No newline at end of file