Appending filename when name and path are occupied.

Hello Everyone,

I must admit I’ve only recently become interested with Applescript (roughly two months), and the majority of what I have has been pieced together bit by little bit (mostly taken from this site). That being said, my apologies if I don’t use the vernacular, but please correct me so I can learn. I’m sure this isn’t the first time you’ve read something similar.

My Problem:

I’m using Entropy as an archive utility, and I’ve pieced together an Applescript which uses the currently selected finder items as the contents for a new archive. The name and path of the archive is designated in the script. Everything runs smoothly when creating one archive, but when I try to create a second archive the program stalls because there is already a file with the same name and path.

How can I alter the script so when the second file (or third, or fourth) is created a number is added to the end of the name? So that the first file name is archive.zip, the second archive1.zip, the third archive2.zip, etc.

Also, if its not too much to ask please include the reasoning behind your answer so that I can learn.

regards,

DrLulz

tell application "Finder" to set theSel to selection as alias list
repeat with i from 1 to count of theSel
	set item i of theSel to POSIX path of item i of theSel
end repeat

tell application "Entropy"
	archive "/Users/HOME/Desktop/archive.zip" files theSel
end tell

I’ve added a subroutine (handler) which does exactly that:

tell application "Finder" to set theSel to selection as alias list
repeat with i from 1 to count of theSel
	set item i of theSel to POSIX path of item i of theSel
end repeat

-- this line calls the handler, below
set archiveName to getEmptyPath(path to desktop as text, "archive", "zip")

tell application "Entropy"
	archive "/Users/HOME/Desktop/" & archiveName & ".zip" files theSel-- modified to accept file name
end tell
---------------------------------------------------------------
-- See if a file with the passed name exists
-- If so, add an integer to the name, and check again
-- Keep checking until an unused name is found
-- Parameters:	path of file's container
--				file name, no extension
--				file extension
-- Returns:		updated file name
---------------------------------------------------------------
on getEmptyPath(containerPath, fileName, fileExtension)
	set filePath to containerPath & fileName
	tell application "Finder"
		if exists file (filePath & "." & fileExtension) then
			set x to 1 -- start counting
			repeat
				set cFilePath to filePath & " " & x & "." & fileExtension
				if exists file cFilePath then -- are we there?
					set x to x + 1 -- no, increment counter
				else
					exit repeat -- yes, leave
				end if
			end repeat
			return fileName & " " & x -- this name is safe to use
		else
			return fileName -- use original name
		end if
	end tell
end getEmptyPath

I believe the code is simple enough to follow. Don’t hesitate to ask, though.

Hi, there

Try it, it’s worked, but one issue present “ application Entropy don’t wait because archive is done, and exit from loop

-- Raster images files formats
property rasterTypeList : {"JPEG", "8BPS", "8BPB", "TIFF", "PNGf"}
property rasterExtensionList : {"jpg", "jpeg", "psd", "psb", "tif", "tiff", "png"}
property rasterTypeIDsList : {"public.png", "public.jpeg", "com.adobe.photoshop-image", "dyn.ah62d4rv4ge81a65c", "public.tiff"}

-- Vector images files formats
property vectorTypeList : {"EPSP", "PDF"}
property vectorExtensionList : {"ai", "eps", "pdf"}
property vectorTypeIDsList : {"com.adobe.illustrator.ai-image", "com.adobe.encapsulated-postscript", "com.adobe.pdf"}

global filesCounter -- счетчик обработанных файлов
global validFiles -- счетчик поддерживаемых файлов

property filesName : {}

property myTitle : "Create ZIP archives"
property buttonCancel : "Cancel" as text
property buttonOk : " Ok " as text
property buttonRepeat : "Repeat" as text
property buttonContinue : "Continue" as text

on run
	set infomsg to "This programm work only as drag'n'drop"
	my dspinfomsg(infomsg)
	return
end run

on open droppeditems
		
	my setFilesList(droppeditems)
	set filesCount to the count of the filesName
	
	if filesCount < 1 then
		my unsupportedFormat()
		return
	end if
	
	set workResult to my createArhcives()
	if workResult is false then
		tell application "Entropy" to quit
		return
	end if
	my workIsDone()
	tell application "Entropy" to quit
	return
end open

(* ==== Выбор и проверка файлов для конвертации в JPEG  ==== *)
on setFilesList(droppeditems)
	set filesName to {}
	repeat with aFile in droppeditems
		-- проверяем тип выбранных файлов
		set theFile to aFile
		set itemInfo to info for aFile
		try
			set thisExtension to the name extension of itemInfo
		on error
			set thisExtension to ""
		end try
		try
			set thisFiletype to the file type of itemInfo
		on error
			set thisExtension to ""
		end try
		try
			set thisTypeID to the type identifier of itemInfo
		on error
			set thisTypeID to ""
		end try
		copy theFile to end of filesName
		-- end if
	end repeat
	return
end setFilesList

on createArhcives()
	-- tell application "StuffIt Destinations"
	tell application "Entropy"
		activate
	end tell
	
	repeat with aFile in filesName
		tell application "Finder"
			set the itemInfo to info for aFile
		end tell
		
		if folder of the itemInfo is true then
			tell (POSIX path of aFile) to set {theSource, theDestination} to {it, it's text 1 thru -2 & "_folder" & ".zip"}
			try
				tell application "Entropy"
					try
						with timeout of 600 seconds
							-- zip theSource to theDestination without adjust extension
							archive theDestination files theSource
						end timeout
					on error the error_message number the error_number
						tell me
							activate
							display alert ¬
								"Sorry, an error has occured “" message ¬
								"Entropy can't ZIP folders: " & the error_number & ". " & the error_message ¬
								buttons {buttonCancel} default button 1
						end tell -- tell me
						return false
					end try
				end tell -- tell application "Entropy"
			on error the error_message number the error_number
				tell me
					activate
					display alert ¬
						"Sorry, an error has occured in module saveRasterAsJPEG() “" message ¬
						"Finder can't ZIP: " & the error_number & ". " & the error_message ¬
						buttons {buttonCancel} default button 1
				end tell -- tell me
				return false
			end try
		else
			try #1
				tell (POSIX path of aFile) to set {theSource, theDestination} to {it, it's text 1 thru -1 & ".zip"}
				tell application "Entropy"
					try
						with timeout of 600 seconds
							-- zip theFile to theFile --compress aFile to aFile
							archive theDestination files theSource
						end timeout
					on error the error_message number the error_number
						tell me
							activate
							display better alert ¬
								"Sorry, an error has occured “" message ¬
								"Entropy can't ZIP files: " & the error_number & ". " & the error_message ¬
								buttons {buttonCancel} default button 1
						end tell -- tell me
						return false
					end try
				end tell -- tell application "StuffIt Destinations"
			on error the error_message number the error_number
				tell me
					activate
					display better alert ¬
						"Sorry, an error has occured #1 “" message ¬
						"Finder can't create name for working file: " & the error_number & ". " & the error_message ¬
						buttons {buttonCancel} default button 1
				end tell -- tell me
				return false
			end try
		end if
	end repeat
	return true
end createArhcives

on dspinfomsg(infomsg)
	tell me
		activate
		display dialog infomsg buttons {buttonCancel} default button 1 with icon stop with title myTitle
	end tell
end dspinfomsg

on unsupportedFormat()
	tell me
		activate
		display dialog ¬
			"Unsupported format," & return & "or no one file was selected" buttons {buttonCancel} default button 1 with title myTitle with icon stop
	end tell
	return
end unsupportedFormat

on workIsDone()
	tell me
		activate
		display dialog "Make ZIP-archives done " buttons {buttonOk} default button 1 with title myTitle with icon 1
	end tell
	return missing value
end workIsDone

@alastor933

Thank you sir, it works flawlessly, and I appreciate its brevity.

Most of the script I followed easily, but I don’t understand how you called the handler, or the first line of the handler itself. Is that some kind of a list or record? (I’m trying to define the method so that I can look it up, or find examples)

Here is what I don’t understand, specifically what is happening inside the ()?

set archiveName to getEmptyPath(path to desktop as text, "archive", "zip")

Same thing here, what going on inside the ()?

on getEmptyPath(containerPath, fileName, fileExtension)

regards

The handler needs some data to do its thing. The data items are called parameters, and they are passed to the handler in a list-like structure, that’s the bits within the parentheses. I listed them in the ‘preambule’ of the handler:

  • path to file’s container
  • name of file
  • extension of file

In the call to the handler I used literal strings (path to desktop as text, “archive”, “zip”), but in the opening statement of the handler they must be variables, that are then used by the handler’s code. Important: order of parameters must be same in both statements.

Some benefits of handlers:

  1. Avoid repeating same block of code over & over, instead put it in a handler.
  2. Portable code. You can use the handler with any script that needs to save same-name files in one location.
  3. Readability of main script is improved, which comes in handy when you want to modify it after a year or so.

I hope this helps. You might want to look at MacScripter’s tutorial section Unscripted.