Groovy delete specific file from the list - file

I try to delete files which i can find in folderPath. But I want delete only that, which have in name "Jenkins".
How to define in list to delete only that file.?
Example :
In C:\test\test have 3 files, want delete that which have Jenkins in name :
import groovy.io.FileType
String folderPath = "C:\\test" + "\\" + "test"
def list = []
def dir = new File("$folderPath")
dir.eachFileRecurse (FileType.FILES) { file ->
list << file
}
list.each {
println it.findAll() == "Jenkins" // Just files witch include in list "Jenkins" name
}
Thanks for tips !

Here you go:
Use either of the below two:
import groovy.io.FileType
String folderPath = "C:/test/test"
new File(folderPath).eachFile (FileType.FILES) { file ->
//Delete file if file name contains Jenkins
if (file.name.contains('Jenkins')) file.delete()
}
or
Below one uses FileNameFinder class
String folderPath = "C:/test/test"
def files = new FileNameFinder().getFileNames(folderPath, '**/*Jenkins*')
println files
files.each { new File(it).delete()}

Related

Groovy / jenkins : rename file

I would like to rename lastModified() json as filename+"processing" in jenkins with groovy. I am unsuccessfully doing :
JSON_BASE_PATH="/json_repo/"
def file = new File(JSON_BASE_PATH).listFiles()?.sort { it.lastModified() }?.find{it=~/.json$/}
file.renameTo( new File( file.getName() + ".processing") )
print "Filename is : " + file
How to rename it ?
You actually already have the answer in your code, you're just not storing it in a variable! new File( file.getName() + ".processing")
An instance of File isn't the actual entry on the file system, it's just a representation of one. So after you perform the rename, you need to work with the File instance that represents the renamed file system entry:
JSON_BASE_PATH="/json_repo/"
def file = new File(JSON_BASE_PATH).listFiles()?.sort { it.lastModified() }?.find{it=~/.json$/}
def modifiedFile = new File("${file.getName()}.processing")
/* Check their existence */
println "${file.getName()} exists? ${file.exists()}"
println "${modifiedFile.getName()} exists? ${modifiedFile.exists()}"
/* Rename the file system entry using the File objects */
file.renameTo(modifiedFile)
/* See what we have */
println "Original filename is: ${file}"
println "${file.getName()} exists? ${file.exists()}"
println "Modified Filename is: ${modifiedFile}"
println "${modifiedFile.getName()} exists? ${modifiedFile.exists()}"
Update : renameTo is working fine. However file var is not reflecting the rename name. How to get new rename name ?

Groovy rename a file

I'm trying to rename files in a directory using Groovy but I can't seem to understand how it works.
Here is my script:
import groovy.io.FileType
def dir = new File("C:/Users/דודו/Downloads/Busta_Rhymes-Genesis-(Retail)-2001-HHI")
def replace = {
if (it == '_') {
' '
}
}
String empty = ""
dir.eachFile (FileType.FILES) { file ->
String newName = file.name
newName = newName.replaceAll(~/Busta_Rhymes/, "$empty")
newName = newName.replaceAll(~/feat/, "ft")
newName = newName.replaceAll(~/-HHI/, "$empty")
newName = newName.replaceAll(~/--/, "-")
newName = newName.collectReplacements(replace)
file.renameTo newName
println file.name
}
When I run this, the names of the files aren't changed as expected. I'm wondering how could I get this to work.
There are a number of things wrong here:
Your dir variable is not the directory; it is the file inside the directory that you actually want to change. Change this line:
dir.eachFile (FileType.FILES) { file ->
to this:
dir.parentFile.eachFile (FileType.FILES) { file ->
The renameTo method does not rename the local name (I know, very counterintuitive), it renames the path. So change the following:
String newName = file.name
to this:
String newName = file.path
Now, for some reason beyond my comprehension, println file.name still prints out the old name. However, if you look at the actual directory afterwords, you will see that the file is correctly renamed in the directory.

How to get all files from folder and subfolder in magento 2

I made a module for uploading images in frontend. Magento 2 saves files in a special way. For example:
uploading file - file.png,
path to file - pub/media/[module_folder]/f/i/file.png.
How to get all files from [module_folder]?
Try the below, use the directorylist class to get the path, and the file class to read the directory :D
public function __construct(
\Magento\Framework\Filesystem\DirectoryList $directoryList,
\Magento\Framework\Filesystem\Driver\File $driverFile,
LoggerInterface $logger)
{
$this->directoryList =$directoryList;
$this->driverFile = $driverFile;
$this->logger = $logger;
}
public function getAllFiles($path = '/import/') {
$paths = [];
try {
//get the base folder path you want to scan (replace var with pub / media or any other core folder)
$path = $this->directoryList->getPath('var') . $path;
//read just that single directory
$paths = $this->driverFile->readDirectory($path);
//read all folders
$paths = $this->driverFile->readDirectoryRecursively($path);
} catch (FileSystemException $e) {
$this->logger->error($e->getMessage());
}
return $paths;
}

How to create a new file name instead of overwriting a file in Groovy

I move a file to a folder. Is there any way to not overwrite a file with that name?
For example, folder contains a file named: file1.pdf. How can I move another file named: file1.pdf into that folder so that the name get changed to e.g. file1-1.pdf, file1-2.pdf to prevent the original file from getting overwritten.
I'm using substring to do that but it's quite long and awful code.
You could use something like this:
def save = { File dir, String name ->
int version = 1
def splitName = name.split(/\./, 0).with { it -> it.length == 1 ? [it[0], ''] : [it[0..-2].join('.'), ".${it[-1]}"] }
def rename = { String prefix, String ext -> "$prefix-$version$ext" }
while (new File(dir, name).exists()) {
name = rename(*splitName)
version++
}
println "Save the file as $name"
}
save(new File('/tmp'), 'file.txt')
Which assuming you have a file /tmp/file.txt and a file /tmp/file-1.txt already, prints out: Save the file as file-2.txt

Delete EMPTY Directory or folders / subfolders

I have the following folders/files.
A/B/C/D/giga.txt
A/BB/
A/CC/DD/fifa.jpg
A/ZZZ/1/a.txt
A/ZZZ/2/b.png
A/ZZZ/3/
How can I code in Gradle/Groovy to delete ONLY the empty directories/subfolders.
i.e. Delete "A/BB", "A/ZZZ/3" in the above sample example. Real case has lot of such folders.
I tried
tasks.withType(Delete) { includeEmptyDirs = true }
didn't work
tasks.withType(Delete) { includeEmptyDirs = false }
didn't work
I don't want to use Gradle > calling > Ant way as that'd be my last resort. Also, don't want to delete each empty folder by writing explicit delete statement per empty folder.
Case 2:
If I run the following:
delete fileTree (dir: "A", include: "**/*.txt")
this above cmd will remove any .txt file under folder A and any subfolder under it. Now, this will make "A/ZZZ/1" a valid candidate for "empty folder" which I would want to delete as well.
Using the Javadoc for FileTree, consider the following to delete empty dirs under "A". Uses Gradle 1.11:
task deleteEmptyDirs() {
def emptyDirs = []
fileTree (dir: "A").visit { def fileVisitDetails ->
def file = fileVisitDetails.file
if (file.isDirectory() && (file.list().length == 0)) {
emptyDirs << file
}
}
emptyDirs.each { dir -> dir.delete() }
}
If you want to delete all the folders that themselves only contain empty folders, this code might help.
def emptyDirs = []
project.fileTree(dir: destdir).visit {
def File f = it.file
if (f.isDirectory() ) {
def children = project.fileTree(f).filter { it.isFile() }.files
if (children.size() == 0) {
emptyDirs << f
}
}
}
// reverse so that we do the deepest folders first
emptyDirs.reverseEach { it.delete() }

Resources