ZipFile [AHK v1.1 and AHK v2.0]

Post your working scripts, libraries and tools for AHK v1.1 and older
Coco
Posts: 771
Joined: 29 Sep 2013, 20:37
Contact:

ZipFile [AHK v1.1 and AHK v2.0]

06 Jul 2014, 11:28

A wrapper for Windows native zip feature
Usage: Source is commented so usage should be straightforward.

Code: Select all

Include <ZipFile>

;// Instantiates the class, creates 'MyZip.zip' if it doesn't exist
zip := new ZipFile("MyZip.zip")
;// Add all text documents in the current directory to the archive and delete them
zip.pack("*.txt", true)
;// Enumerate the items in the archive
for item in zip
	MsgBox % "Name: "            . item.name
	       . "`nSize: "          . item.size
	       . "`nType: "          . item.type
	       . "`nDate modified: " . item.date
	       . "`nRelative Path: " . item.path
;// Delete 'test.txt' from the archive
zip.delete("test.txt")
;// Extract the contents of the archive to folder 'Extracted'
zip.unpack(, "Extracted")
return
Source: On GitHub
carno
Posts: 265
Joined: 20 Jun 2014, 16:48

Re: ZipFile [AHK v1.1 and AHK v2.0]

06 Jul 2014, 20:14

;// Add all text documents in the current directory to the archive and delete them
How to add documents without "deleting" them?
Coco
Posts: 771
Joined: 29 Sep 2013, 20:37
Contact:

Re: ZipFile [AHK v1.1 and AHK v2.0]

07 Jul 2014, 03:04

carno wrote:How to add documents without "deleting" them?
Hi carno, you can set the 2nd parameter of .pack() to false or you can omit it (default is false anyways).
As per source code:

Code: Select all

/* Function: pack
 * Adds the specified file(s) to the archive
 * Syntax:
 *     zip.pack([ fspec, del ])
 * Parameter(s):
 *     fpsec   [in] - The file(s) to zip, accepts wildcards. If omitted,
 *                    all the file(s) in the current directory will be
 *                    included.
 *     del     [in] - If true, the file(s) will be deleted after zipping.
 */
toralf
Posts: 868
Joined: 27 Apr 2014, 21:08
Location: Germany

Re: ZipFile [AHK v1.1 and AHK v2.0]

07 Jul 2014, 05:38

Does it work with .7z files too?
If not, could it be extended?
I would like to get independent of 7za.exe
ciao
toralf
Coco
Posts: 771
Joined: 29 Sep 2013, 20:37
Contact:

Re: ZipFile [AHK v1.1 and AHK v2.0]

07 Jul 2014, 07:58

AFAIK, this won't work for .7z format. It could be extended but it would still require 7za.exe.
ozzii
Posts: 481
Joined: 30 Oct 2013, 06:04

Re: ZipFile [AHK v1.1 and AHK v2.0]

08 Jul 2014, 03:01

It also can use the dll instead of the exe of 7za but you still need to use an external file.
User avatar
joedf
Posts: 8940
Joined: 29 Sep 2013, 17:08
Location: Canada
Contact:

Re: ZipFile [AHK v1.1 and AHK v2.0]

08 Jul 2014, 03:49

Using the DLL is not worth the trouble when 7za.exe was especially created to simplify people's lives... :P
Trust me, it's just Not worth it. Also, a lot of popular applications use 7za.exe
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500, NVIDIA GTX 1060 6GB, 2x16GB Kingston FURY Beast - DDR4 3200 MHz | [About Me] | [About the AHK Foundation] | [Courses on AutoHotkey]
[ASPDM - StdLib Distribution] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library]
User avatar
joedf
Posts: 8940
Joined: 29 Sep 2013, 17:08
Location: Canada
Contact:

Re: ZipFile [AHK v1.1 and AHK v2.0]

09 Jul 2014, 01:17

Here's a 7za.exe wrapper i made a while ago...
Have fun ;)

Code: Select all

;7z warpper - joedf
7z_exe:="7za.exe"

7z_compress(dPack,files*) {
	global 7z_exe
	flist:=""
	for each, file in files
		flist:= flist """" file """" " "
	if FileExist(dPack)
		FileDelete, %dPack%
	RunWait, %7z_exe% a -t7z "%dPack%" %flist%,,Hide UseErrorLevel
	return !7z_error(ErrorLevel)
}

7z_extract(dPack,dFolder="",opts="") {
	global 7z_exe
	if StrLen(dFolder)
		out:="-o" . """" . dFolder . """"
	RunWait, %7z_exe% x "%dPack%" %out% -y %opts%,,Hide UseErrorLevel
	return !7z_error(ErrorLevel)
}

7z_list(dPack) {
	global 7z_exe
	tmp:=TempFile()
	RunWait,%comspec% /c %7z_exe% l "%dPack%" > "%tmp%",,Hide UseErrorLevel
	r:={}
	if (!(e:=7z_error(ErrorLevel))) {
		FileRead,o,%tmp%
		Loop, Parse, o, `n, `r
		{
			if (RegExMatch(A_LoopField,"(-+\s+){4}")) {
				if (!i)
					i:=A_Index
				else
					break
			}
			if (A_Index-i > 0) {
				p:=StrSplit(A_LoopField,A_Space)
				RegExMatch(SubStr(A_LoopField,StrLen(p.1 p.2 p.3)+3),"\d+",S)
				c:=InStr(A_LoopField,S)+StrLen(S)
				StringTrimLeft,n,A_LoopField,%c%
				
				k:={}
				k.Date := p.1
				k.Time := p.2
				k.Attr := p.3
				k.Size := S
				k.Name := RegExReplace(n,"\s+\d*\s+","","",1)
				
				r.Insert(k)
			}
		}
	}
	FileDelete,%tmp%
	return (e?0:r)
}

7z_error(e) {
	if (e==1)
		MsgBox Warning (Non fatal error(s)). For example, one or more files were locked by some other application, so they were not compressed. 
	else if (e==2)
		MsgBox Fatal error 
	else if (e==7)
		MsgBox Command line error 
	else if (e==8)
		MsgBox Not enough memory for operation 
	else if (e==255)
		MsgBox User stopped the process 
	return e
}

TempFile() {
	Loop
		tempName := A_Temp "\~temp" A_TickCount ".tmp"
	until !FileExist(tempName)
	return tempName
}
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500, NVIDIA GTX 1060 6GB, 2x16GB Kingston FURY Beast - DDR4 3200 MHz | [About Me] | [About the AHK Foundation] | [Courses on AutoHotkey]
[ASPDM - StdLib Distribution] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library]
Guest

Re: ZipFile [AHK v1.1 and AHK v2.0]

17 Mar 2015, 08:20

At irregular intervals I get this error while trying to zip a folder and its sub-folders
[Window Title]
Compressed (zipped) Folders Error

[Content]
Missing or empty Zip file.

[OK]
but when I try with the shortest possible code

Code: Select all

UnpackFolder:=A_ScriptDir
BackupZip:=UnpackFolder "\Backup-" A_Now ".zip"
backup := new ZipFile(BackupZip)
backup.pack(A_ScriptDir "\*.*")
I don't get this error and I can run it 10 times in a row without any issues.

If I try to run my actual script several times in a row it sometimes fails and sometimes works. I can see that is has started to create a zip as it has some files in it at times but it stops with the error... Do you have any ideas what might cause the error? It seems to be a Windows error not a AHK script error message.
Coco
Posts: 771
Joined: 29 Sep 2013, 20:37
Contact:

Re: ZipFile [AHK v1.1 and AHK v2.0]

17 Mar 2015, 09:00

Thank you for reporting. I would need to investigate this, it could be during the creation of the zip file OR during the copying of the file(s) from/to the archive. Plus, this script might need some updating. I'll get back with an updated version. :)
list
Posts: 221
Joined: 26 Mar 2014, 14:03
Contact:

Re: ZipFile [AHK v1.1 and AHK v2.0]

17 Mar 2015, 12:30

Thanks Coco - I've done some further testing. If I build a filelist first and add these one by one to the zip file like so

Code: Select all

BackupZip:=UnpackFolder "\Backup-" A_Now ".zip"
backup := new ZipFile(BackupZip)
Loop, parse, filelist, `n, `r
	{
	 tooltip % "zipping: " A_LoopField
	 backup.pack(A_LoopField)
	}
it (randomly it seems) asks:
There is already a file with the same name in this location.
Click the file you want to keep:
Copy & Replace: default.txt
c:\users\....appdata\local\temp\radc1762.tmp
Don't copy
...
and it always seems to stall at the same file after clicking "copy & replace" a few times.
I've increased the sleep 15 to sleep 50 just to see if that would help but it didn't.
Coco
Posts: 771
Joined: 29 Sep 2013, 20:37
Contact:

Re: ZipFile [AHK v1.1 and AHK v2.0]

18 Mar 2015, 02:41

Guest wrote:At irregular intervals I get this error while trying to zip a folder and its sub-folders
How do you specify the folder name when Pack-ing? Make sure that your working directory is correct when specifying relative paths.
list wrote:There is already a file with the same name in this location.
Obviously, this indicates that a file with same name already exists in the destination ZIP file. There is a flag to automatically preform a rename(if there is conflict) during the CopyHere/MoveHere routine, however, as mentioned here:
Note In some cases, such as compressed (.zip) files, some option flags may be ignored by design.
list wrote:and it always seems to stall at the same file after clicking "copy & replace" a few times.
I've increased the sleep 15 to sleep 50 just to see if that would help but it didn't.
I believe it isn't stalling, the while loop doesn't break because that particular item(file or folder) in the temporary folder(created if the ZIP file is not empty) is not moved. Hence, while (dest.Items().Count != 0) remains true. In my case though, if I choose Copy and Replace, the loop breaks, however, if I choose Don't Copy, I would get the same effect as yours.

The thing with Shell.Application zipping, esp. for the CopyHere/MoveHere methods, there is no way to determine if the operation has completed. One would have to resort to checking/comparing the items count, OR if the ZIP file is not empty, temporarily copy/move the files to a temporary folder, then move them to the ZIP file (while checking until the temp folder is empty).

Your issues would only occur if there are file/folder name conflicts so it's best to avoid them for now.
list
Posts: 221
Joined: 26 Mar 2014, 14:03
Contact:

Re: ZipFile [AHK v1.1 and AHK v2.0]

18 Mar 2015, 12:51

Thanks for the reply, it did inspire me to do some further digging and I made another test script just to see if I could create something that wouldn't work consistently so I could report back. This time I got an error message saying "A zip file cannot include itself" which got me thinking.

I have the following structure:

MyProgramFolder
+----sub
+----sub
+----sub
+----backup folder

I was zipping "MyProgramFolder" into "MyProgramFolder\backup folder"
which worked the first couple of times (and still does but not always)

I changed it so now I am zipping "MyProgramFolder" into A_Temp first and
when ready I move it to "MyProgramFolder\backup folder" and I have
run the script a dozen times in row without any errors. :D

So I suspect the stalling had/has something to do a "A zip file cannot
include itself" type of error. I think it works consistently now.

A new question: is there a way to exclude files from the zip file e.g. skip zip files or skip a certain folder?
Coco
Posts: 771
Joined: 29 Sep 2013, 20:37
Contact:

Re: ZipFile [AHK v1.1 and AHK v2.0]

18 Mar 2015, 13:58

list wrote:A new question: is there a way to exclude files from the zip file e.g. skip zip files or skip a certain folder?
Yes, I realized that as well. That happens when one attempts to pack files(say using a wildcard) and the ZIP file happens to be included in the filter. I was able to get around this. I'll push the changes with the fix once I'm done refactoring the code. As for specifying other exclusion(s), I'll leave it to the caller to handle it. Excluding only the ZIP file itself should be enough.
Coco
Posts: 771
Joined: 29 Sep 2013, 20:37
Contact:

Re: ZipFile [AHK v1.1 and AHK v2.0]

19 Mar 2015, 14:00

Ok, I've pushed a new dev branch to the repo. I will be merging it with the master branch once I've done some extensive testing. See commit for details on the changes.
list
Posts: 221
Joined: 26 Mar 2014, 14:03
Contact:

Re: ZipFile [AHK v1.1 and AHK v2.0]

20 Mar 2015, 12:54

Thanks - I've done some tests using Win7 (32bit, unicode) and Win8 (64bit) and have no problems to report so far...
Coco
Posts: 771
Joined: 29 Sep 2013, 20:37
Contact:

Re: ZipFile [AHK v1.1 and AHK v2.0]

29 Mar 2015, 03:37

I've merged dev into master. Deleted dev as it is no longer needed.
User avatar
FanaticGuru
Posts: 1906
Joined: 30 Sep 2013, 22:25

Re: ZipFile [AHK v1.1 and AHK v2.0]

15 Dec 2016, 13:17

I am having trouble getting ZipFile working with a path to the files to put in the zip.

This is what does not work:

Code: Select all

; Does Not Work - Creates MyZip.zip but it is empty
Zip := new ZipFile("c:\Temp2\MyZip.zip")
Zip.Pack("C:\Temp\*.txt")
If I don't put a path it works but gets the folder my script is in:

Code: Select all

; Works
Zip := new ZipFile("c:\Temp2\MyZip.zip")
Zip.Pack("*.txt")
If I don't put a path and get around it with SetWorkingDir, it works:

Code: Select all

; Works
Zip := new ZipFile("c:\Temp2\MyZip.zip")
SetWorkingDir, C:\Temp
Zip.Pack("*.txt")
Am I missing something simple in my syntax or does it really not accept a path?

I am using Windows 10 and AHK version 1.1.24.00.

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks
User avatar
FanaticGuru
Posts: 1906
Joined: 30 Sep 2013, 22:25

Re: ZipFile [AHK v1.1 and AHK v2.0]

12 Jan 2017, 17:31

Guest wrote:( Edit: this 7z discussion should be split from this thread as it has nothing to do with ZipFile by coco. )
Maybe all the bumping will have coco or someone else to help with my problem of using a path that I am having with coco's script.

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks
User avatar
joedf
Posts: 8940
Joined: 29 Sep 2013, 17:08
Location: Canada
Contact:

Re: ZipFile [AHK v1.1 and AHK v2.0]

13 Jan 2017, 10:57

True, however Guest has a point.
@Peter2 Please start a new topic, you can send me a pm later.
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500, NVIDIA GTX 1060 6GB, 2x16GB Kingston FURY Beast - DDR4 3200 MHz | [About Me] | [About the AHK Foundation] | [Courses on AutoHotkey]
[ASPDM - StdLib Distribution] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library]

Return to “Scripts and Functions (v1)”

Who is online

Users browsing this forum: charlie89, gwarble and 128 guests