├── .gitignore ├── Assets.xcassets ├── Contents.json └── AppIcon.appiconset │ ├── unpkg.icns │ └── Contents.json ├── README.md ├── Package.swift ├── Info.plist ├── End-user Read Me.rtf ├── Makefile ├── COPYING └── unpkg.swift /.gitignore: -------------------------------------------------------------------------------- 1 | unpkg.app 2 | .DS_Store 3 | VERSION 4 | *.zip -------------------------------------------------------------------------------- /Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "author" : "xcode", 4 | "version" : 1 5 | } 6 | } -------------------------------------------------------------------------------- /Assets.xcassets/AppIcon.appiconset/unpkg.icns: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timdoug/unpkg/HEAD/Assets.xcassets/AppIcon.appiconset/unpkg.icns -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Build instructions 2 | ================== 3 | 4 | `make` 5 | 6 | Should work on macOS 11 Big Sur and above; only tested on 26 Tahoe. 7 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.7 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "unpkg", 8 | platforms: [ 9 | .macOS(.v11) 10 | ], 11 | products: [ 12 | .executable(name: "unpkg", targets: ["unpkg"]) 13 | ], 14 | dependencies: [], 15 | targets: [ 16 | .executableTarget( 17 | name: "unpkg", 18 | dependencies: [], 19 | path: ".", 20 | exclude: [ 21 | "Info.plist", 22 | "Makefile", 23 | "README.md", 24 | "COPYING", 25 | "End-user Read Me.rtf", 26 | "unpkg.app", 27 | "unpkg-notarize.zip" 28 | ], 29 | sources: [ 30 | "unpkg.swift" 31 | ], 32 | resources: [ 33 | .process("Assets.xcassets") 34 | ] 35 | ) 36 | ] 37 | ) -------------------------------------------------------------------------------- /Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "filename" : "unpkg.icns", 5 | "idiom" : "mac", 6 | "scale" : "1x", 7 | "size" : "16x16" 8 | }, 9 | { 10 | "filename" : "unpkg.icns", 11 | "idiom" : "mac", 12 | "scale" : "2x", 13 | "size" : "16x16" 14 | }, 15 | { 16 | "filename" : "unpkg.icns", 17 | "idiom" : "mac", 18 | "scale" : "1x", 19 | "size" : "32x32" 20 | }, 21 | { 22 | "filename" : "unpkg.icns", 23 | "idiom" : "mac", 24 | "scale" : "2x", 25 | "size" : "32x32" 26 | }, 27 | { 28 | "filename" : "unpkg.icns", 29 | "idiom" : "mac", 30 | "scale" : "1x", 31 | "size" : "128x128" 32 | }, 33 | { 34 | "filename" : "unpkg.icns", 35 | "idiom" : "mac", 36 | "scale" : "2x", 37 | "size" : "128x128" 38 | }, 39 | { 40 | "filename" : "unpkg.icns", 41 | "idiom" : "mac", 42 | "scale" : "1x", 43 | "size" : "256x256" 44 | }, 45 | { 46 | "filename" : "unpkg.icns", 47 | "idiom" : "mac", 48 | "scale" : "2x", 49 | "size" : "256x256" 50 | }, 51 | { 52 | "filename" : "unpkg.icns", 53 | "idiom" : "mac", 54 | "scale" : "1x", 55 | "size" : "512x512" 56 | }, 57 | { 58 | "filename" : "unpkg.icns", 59 | "idiom" : "mac", 60 | "scale" : "2x", 61 | "size" : "512x512" 62 | } 63 | ], 64 | "info" : { 65 | "author" : "xcode", 66 | "version" : 1 67 | } 68 | } -------------------------------------------------------------------------------- /Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | unpkg 9 | CFBundleIconFile 10 | unpkg 11 | CFBundleIdentifier 12 | org.timdoug.unpkg 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | unpkg 17 | CFBundleDisplayName 18 | unpkg 19 | CFBundlePackageType 20 | APPL 21 | CFBundleShortVersionString 22 | 5.0 23 | CFBundleVersion 24 | 1 25 | LSMinimumSystemVersion 26 | 11.0 27 | NSHumanReadableCopyright 28 | Copyright © 2025 timdoug. All rights reserved. 29 | https://www.timdoug.com/unpkg/ 30 | NSPrincipalClass 31 | NSApplication 32 | NSSupportsAutomaticTermination 33 | 34 | NSSupportsSuddenTermination 35 | 36 | LSSupportsOpeningDocumentsInPlace 37 | 38 | CFBundleDocumentTypes 39 | 40 | 41 | CFBundleTypeName 42 | macOS Installer Package 43 | CFBundleTypeRole 44 | Viewer 45 | LSHandlerRank 46 | Alternate 47 | LSItemContentTypes 48 | 49 | com.apple.installer-package-archive 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /End-user Read Me.rtf: -------------------------------------------------------------------------------- 1 | {\rtf1\ansi\ansicpg1252\cocoartf2867 2 | \cocoascreenfonts1\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica-Bold;\f1\fswiss\fcharset0 Helvetica;} 3 | {\colortbl;\red255\green255\blue255;} 4 | {\*\expandedcolortbl;;} 5 | \margl1440\margr1440\vieww16900\viewh20000\viewkind0 6 | \pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural\qc\partightenfactor0 7 | 8 | \f0\b\fs40 \cf0 unpkg 9 | \fs24 \ 10 | me@timdoug.com\ 11 | http://www.timdoug.com/\ 12 | 13 | \f1\b0 \ 14 | 15 | \f0\b\fs30 a quick and simple .(m)pkg extractor\ 16 | 17 | \f1\b0\fs24 \ 18 | released under the GNU GPL (see COPYING)\ 19 | \pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural\partightenfactor0 20 | \cf0 NEW IN 5.0:\ 21 | - Rewritten in Swift; new icon, thanks Andy Zeng Houming!\ 22 | \ 23 | NEW IN 4.8:\ 24 | - Port to Python3 for macOS 12.3+, see https://developer.apple.com/documentation/macos-release-notes/macos-12_3-release-notes#Python\ 25 | \ 26 | NEW IN 4.7:\ 27 | - Native Apple Silicon support: rebuild w/ arm64 and x86_64 binaries\ 28 | \ 29 | NEW IN 4.6:\ 30 | - rebuilt as a 64 bit app to run on 10.15+.\ 31 | \ 32 | NEW IN 4.5:\ 33 | - finally: metapackage extraction!\ 34 | - new progress bar interface\ 35 | - lots of behind-the-scenes changes and fixes\ 36 | \ 37 | NEW IN 4.0 (so new and different we skipped 3.0):\ 38 | - entirely re-written in Python\ 39 | - now works with multiple packages at once\ 40 | - also now extracts 10.5-style packages (nested ones, too, and in 10.4 as well!)\ 41 | - ripped out CocoaDialog, simplifying the interface\ 42 | - new (and prettier!) icon\ 43 | \ 44 | This program is pretty self explanatory -- there are some files in a package you want, but you don't want to let the package write all over your hard drive, or you don't have Administrator privileges or passwords, etc.\ 45 | \ 46 | Just drag the package onto unpkg's icon and it will extract the contents into the same directory, with the same name. For example, if I'm unpacking gcc3.3.pkg in my home folder, a folder named gcc3.3 will appear in that same folder with all of the package's contents.\ 47 | \ 48 | If the package is in a non-writable folder (e.g., a locked disk image, or a CD), unpkg will try unpacking onto the Desktop. In either case, if there already exists a folder with the chosen name (following our previous example, gcc3.3), a digit (or digits) will be appended to the extracted folder.\ 49 | \ 50 | The source is available on GitHub at https://github.com/timdoug/unpkg.\ 51 | \ 52 | Cheers,\ 53 | -Tim\ 54 | } 55 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: all clean build release app sign notarize dmg run 2 | 3 | # Configuration for code signing and notarization 4 | # Override these on the command line or set as environment variables 5 | DEVELOPER_ID ?= Developer ID Application: Your Name (TEAMID) 6 | APPLE_ID ?= your@email.com 7 | TEAM_ID ?= YOURTEAMID 8 | # Create an app-specific password at appleid.apple.com and store in keychain: 9 | # xcrun notarytool store-credentials "notarytool-profile" --apple-id "your@email.com" --team-id "TEAMID" 10 | NOTARYTOOL_PROFILE ?= notarytool-profile 11 | 12 | # Default target 13 | all: app 14 | 15 | # Clean build artifacts 16 | clean: 17 | rm -rf .build 18 | rm -rf unpkg.app 19 | rm -f unpkg.dmg 20 | rm -rf unpkg-dmg-temp 21 | 22 | # Build debug version 23 | build: 24 | swift build 25 | 26 | # Build release version (universal binary for Intel and Apple Silicon) 27 | release: 28 | @echo "Building for x86_64..." 29 | swift build -c release --arch x86_64 30 | @echo "Building for arm64..." 31 | swift build -c release --arch arm64 32 | @echo "Creating universal binary..." 33 | mkdir -p .build/release 34 | lipo -create \ 35 | .build/x86_64-apple-macosx/release/unpkg \ 36 | .build/arm64-apple-macosx/release/unpkg \ 37 | -output .build/release/unpkg 38 | @echo "Universal binary created" 39 | 40 | # Create macOS app bundle 41 | app: release 42 | @echo "Creating app bundle..." 43 | mkdir -p unpkg.app/Contents/MacOS 44 | mkdir -p unpkg.app/Contents/Resources 45 | cp .build/release/unpkg unpkg.app/Contents/MacOS/ 46 | cp Info.plist unpkg.app/Contents/ 47 | cp Assets.xcassets/AppIcon.appiconset/unpkg.icns unpkg.app/Contents/Resources/ 48 | @echo "App bundle created: unpkg.app" 49 | 50 | # Code sign the app with Developer ID (required for notarization) 51 | sign: app 52 | @echo "Code signing unpkg.app..." 53 | codesign --force --options runtime --sign "$(DEVELOPER_ID)" unpkg.app 54 | @echo "Verifying signature..." 55 | codesign --verify --verbose unpkg.app 56 | @echo "Code signing complete" 57 | 58 | # Notarize the app with Apple 59 | notarize: sign 60 | @echo "Creating zip for notarization..." 61 | ditto -c -k --keepParent unpkg.app unpkg-notarize.zip 62 | @echo "Submitting to Apple for notarization (this may take a few minutes)..." 63 | xcrun notarytool submit unpkg-notarize.zip --keychain-profile "$(NOTARYTOOL_PROFILE)" --wait 64 | @echo "Stapling notarization ticket to app..." 65 | xcrun stapler staple unpkg.app 66 | @rm -f unpkg-notarize.zip 67 | @echo "Notarization complete" 68 | 69 | # Create DMG for distribution (unsigned) 70 | dmg: app 71 | @echo "Creating DMG..." 72 | @rm -rf unpkg-dmg-temp 73 | @mkdir -p unpkg-dmg-temp 74 | @cp -r unpkg.app unpkg-dmg-temp/ 75 | @cp "End-user Read Me.rtf" unpkg-dmg-temp/ 76 | hdiutil create -volname "unpkg" -srcfolder unpkg-dmg-temp -ov -format UDZO unpkg.dmg 77 | @rm -rf unpkg-dmg-temp 78 | @echo "DMG created: unpkg.dmg" 79 | 80 | # Create signed and notarized DMG for distribution 81 | dmg-release: notarize 82 | @echo "Creating release DMG..." 83 | @rm -rf unpkg-dmg-temp 84 | @mkdir -p unpkg-dmg-temp 85 | @cp -r unpkg.app unpkg-dmg-temp/ 86 | @cp "End-user Read Me.rtf" unpkg-dmg-temp/ 87 | hdiutil create -volname "unpkg" -srcfolder unpkg-dmg-temp -ov -format UDZO unpkg.dmg 88 | @rm -rf unpkg-dmg-temp 89 | codesign --force --sign "$(DEVELOPER_ID)" unpkg.dmg 90 | @echo "Release DMG created: unpkg.dmg" 91 | 92 | # Run the app 93 | run: build 94 | .build/debug/unpkg 95 | 96 | # Show help 97 | help: 98 | @echo "Available targets:" 99 | @echo " make build - Build debug version" 100 | @echo " make release - Build release version (universal binary)" 101 | @echo " make app - Create macOS app bundle" 102 | @echo " make sign - Code sign the app with Developer ID" 103 | @echo " make notarize - Notarize the app with Apple" 104 | @echo " make dmg - Create distribution DMG (unsigned)" 105 | @echo " make dmg-release - Create signed and notarized DMG" 106 | @echo " make run - Build and run debug version" 107 | @echo " make clean - Remove build artifacts" 108 | @echo " make help - Show this help" 109 | @echo "" 110 | @echo "Before signing/notarizing, set up credentials:" 111 | @echo " 1. Get your Developer ID: security find-identity -v -p codesigning" 112 | @echo " 2. Store notarytool credentials:" 113 | @echo " xcrun notarytool store-credentials \"notarytool-profile\" \\" 114 | @echo " --apple-id \"your@email.com\" --team-id \"TEAMID\"" 115 | @echo "" 116 | @echo "Then run: make dmg-release DEVELOPER_ID=\"Developer ID Application: Name (TEAMID)\"" 117 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /unpkg.swift: -------------------------------------------------------------------------------- 1 | // 2 | // unpkg.swift 3 | // unpkg - Native macOS app for extracting installer packages 4 | // 5 | 6 | import SwiftUI 7 | import Cocoa 8 | import UniformTypeIdentifiers 9 | import Foundation 10 | import AppKit 11 | 12 | // MARK: - App Entry Point 13 | 14 | // Minimal app delegate to ensure app quits when last window is closed 15 | class AppDelegate: NSObject, NSApplicationDelegate { 16 | func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { 17 | return true 18 | } 19 | 20 | // Handle files opened by dropping onto app icon or double-clicking 21 | func application(_ application: NSApplication, open urls: [URL]) { 22 | for url in urls { 23 | let ext = url.pathExtension.lowercased() 24 | guard ext == "pkg" || ext == "mpkg" else { continue } 25 | 26 | // Post notification to ContentView to add file to queue 27 | NotificationCenter.default.post( 28 | name: NSNotification.Name("OpenPackageFile"), 29 | object: nil, 30 | userInfo: ["url": url] 31 | ) 32 | } 33 | } 34 | } 35 | 36 | @main 37 | struct unpkgApp: App { 38 | @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate 39 | 40 | var body: some Scene { 41 | WindowGroup("unpkg") { 42 | ContentView() 43 | .frame(minWidth: 600, minHeight: 500) 44 | .handlesExternalEvents(preferring: Set(["*"]), allowing: Set(["*"])) 45 | } 46 | .handlesExternalEvents(matching: Set(["*"])) 47 | .commands { 48 | CommandGroup(replacing: .newItem) { 49 | Button("Open...") { 50 | NotificationCenter.default.post(name: NSNotification.Name("OpenFileMenu"), object: nil) 51 | } 52 | .keyboardShortcut("O", modifiers: .command) 53 | } 54 | } 55 | } 56 | } 57 | 58 | // MARK: - UI Views 59 | 60 | struct ContentView: View { 61 | @StateObject private var extractor = PackageExtractor.shared 62 | @State private var isDragTargeted = false 63 | 64 | var body: some View { 65 | VStack(spacing: 20) { 66 | Spacer() 67 | 68 | // Logo and drop area 69 | VStack(spacing: 20) { 70 | if let nsImage = NSImage(named: "AppIcon") ?? NSImage(named: "unpkg") { 71 | Image(nsImage: nsImage) 72 | .resizable() 73 | .aspectRatio(contentMode: .fit) 74 | .frame(width: 100, height: 100) 75 | } else { 76 | Image(systemName: "shippingbox.fill") 77 | .font(.system(size: 80)) 78 | .foregroundColor(.accentColor) 79 | } 80 | 81 | Text("Drop packages here") 82 | .font(.headline) 83 | .foregroundColor(isDragTargeted ? .accentColor : .secondary) 84 | 85 | Button("Browse Files...") { 86 | selectFiles() 87 | } 88 | .buttonStyle(.bordered) 89 | } 90 | 91 | // Progress section 92 | if extractor.isExtracting { 93 | VStack(spacing: 10) { 94 | ProgressView(value: extractor.progress) 95 | .progressViewStyle(.linear) 96 | 97 | Text(extractor.currentOperation) 98 | .font(.caption) 99 | .foregroundColor(.secondary) 100 | } 101 | .padding() 102 | } 103 | 104 | // Queue status 105 | if !extractor.fileQueue.isEmpty { 106 | Text("Files in queue: \(extractor.fileQueue.count)") 107 | .font(.caption) 108 | .foregroundColor(.secondary) 109 | } 110 | 111 | // Results section 112 | if !extractor.extractionResults.isEmpty { 113 | ScrollView { 114 | VStack(alignment: .leading, spacing: 8) { 115 | Text("Extraction Results:") 116 | .font(.headline) 117 | .padding(.horizontal) 118 | 119 | ForEach(extractor.extractionResults, id: \.self) { result in 120 | ResultRow(result: result) 121 | } 122 | } 123 | } 124 | .frame(maxHeight: 200) 125 | } 126 | 127 | Spacer() 128 | 129 | // Clear button 130 | if !extractor.extractionResults.isEmpty { 131 | Button("Clear Results") { 132 | extractor.clearResults() 133 | } 134 | .buttonStyle(.plain) 135 | .font(.caption) 136 | .padding(.bottom, 10) 137 | } 138 | } 139 | .padding() 140 | .frame(maxWidth: .infinity, maxHeight: .infinity) 141 | .background(isDragTargeted ? Color.accentColor.opacity(0.05) : Color.clear) 142 | .onDrop(of: [.fileURL], isTargeted: $isDragTargeted, perform: handleDrop) 143 | .onReceive(NotificationCenter.default.publisher(for: NSNotification.Name("OpenFileMenu"))) { _ in 144 | selectFiles() 145 | } 146 | .onReceive(NotificationCenter.default.publisher(for: NSNotification.Name("OpenPackageFile"))) { notification in 147 | if let url = notification.userInfo?["url"] as? URL { 148 | extractor.addFilesToQueue([url]) 149 | } 150 | } 151 | } 152 | 153 | private func handleDrop(_ providers: [NSItemProvider]) -> Bool { 154 | var droppedURLs: [URL] = [] 155 | let group = DispatchGroup() 156 | let lock = NSLock() 157 | 158 | for provider in providers { 159 | group.enter() 160 | provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier, options: nil) { item, error in 161 | defer { group.leave() } 162 | 163 | guard let data = item as? Data, 164 | let url = URL(dataRepresentation: data, relativeTo: nil), 165 | (url.pathExtension.lowercased() == "pkg" || url.pathExtension.lowercased() == "mpkg") else { return } 166 | 167 | lock.lock() 168 | droppedURLs.append(url) 169 | lock.unlock() 170 | } 171 | } 172 | 173 | group.notify(queue: .main) { 174 | extractor.addFilesToQueue(droppedURLs) 175 | } 176 | 177 | return true 178 | } 179 | 180 | private func selectFiles() { 181 | let panel = NSOpenPanel() 182 | panel.allowsMultipleSelection = true 183 | panel.canChooseDirectories = false 184 | panel.allowedContentTypes = [ 185 | UTType(filenameExtension: "pkg") ?? .package, 186 | UTType(filenameExtension: "mpkg") ?? .package 187 | ] 188 | panel.message = "Select package files to extract" 189 | 190 | if panel.runModal() == .OK { 191 | extractor.addFilesToQueue(panel.urls) 192 | } 193 | } 194 | } 195 | 196 | struct ResultRow: View { 197 | let result: ExtractionResult 198 | 199 | var body: some View { 200 | HStack(spacing: 8) { 201 | Image(systemName: result.success ? "checkmark.circle.fill" : "xmark.circle.fill") 202 | .foregroundColor(result.success ? .green : .red) 203 | .font(.system(size: 14)) 204 | 205 | VStack(alignment: .leading, spacing: 2) { 206 | Text(result.packageName) 207 | .font(.system(size: 12, weight: .medium)) 208 | .lineLimit(1) 209 | 210 | Text(result.success 211 | ? "Extracted to: \(result.extractionPath ?? "")" 212 | : result.error ?? "Unknown error") 213 | .font(.system(size: 11)) 214 | .foregroundColor(result.success ? .secondary : .red) 215 | .lineLimit(result.success ? 1 : 2) 216 | } 217 | 218 | Spacer() 219 | 220 | if result.success, let path = result.extractionPath { 221 | Button { 222 | NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: path) 223 | } label: { 224 | Image(systemName: "arrow.right.circle") 225 | .font(.system(size: 14)) 226 | } 227 | .buttonStyle(.plain) 228 | .help("Show in Finder") 229 | } 230 | } 231 | .padding(.horizontal) 232 | .padding(.vertical, 4) 233 | } 234 | } 235 | 236 | // MARK: - Package Extraction Logic 237 | 238 | struct ExtractionResult: Hashable { 239 | let packageName: String 240 | let success: Bool 241 | let extractionPath: String? 242 | let error: String? 243 | } 244 | 245 | @MainActor 246 | class PackageExtractor: ObservableObject { 247 | static let shared = PackageExtractor() 248 | 249 | @Published var isExtracting = false 250 | @Published var progress: Double = 0.0 251 | @Published var currentOperation = "" 252 | @Published var extractionResults: [ExtractionResult] = [] 253 | @Published var showError = false 254 | @Published var errorMessage = "" 255 | @Published var fileQueue: [URL] = [] 256 | 257 | private var isProcessingQueue = false 258 | private let fileManager = FileManager.default 259 | 260 | private init() {} 261 | 262 | // MARK: - Public Methods 263 | 264 | func extractPackage(at url: URL) async { 265 | isExtracting = true 266 | progress = 0.0 267 | currentOperation = "Preparing to extract \(url.lastPathComponent)..." 268 | 269 | do { 270 | let result = try await performExtraction(url: url) 271 | extractionResults.append(result) 272 | } catch { 273 | let result = ExtractionResult( 274 | packageName: url.lastPathComponent, 275 | success: false, 276 | extractionPath: nil, 277 | error: error.localizedDescription 278 | ) 279 | extractionResults.append(result) 280 | errorMessage = error.localizedDescription 281 | showError = true 282 | } 283 | 284 | isExtracting = false 285 | progress = 1.0 286 | currentOperation = "" 287 | } 288 | 289 | func clearResults() { 290 | extractionResults.removeAll() 291 | errorMessage = "" 292 | showError = false 293 | } 294 | 295 | func addFilesToQueue(_ urls: [URL]) { 296 | for url in urls where !fileQueue.contains(url) { 297 | fileQueue.append(url) 298 | } 299 | 300 | if !isProcessingQueue { 301 | processQueue() 302 | } 303 | } 304 | 305 | private func processQueue() { 306 | guard !isProcessingQueue && !fileQueue.isEmpty else { return } 307 | 308 | isProcessingQueue = true 309 | 310 | Task { 311 | while !fileQueue.isEmpty { 312 | let url = fileQueue.removeFirst() 313 | await extractPackage(at: url) 314 | } 315 | isProcessingQueue = false 316 | } 317 | } 318 | 319 | // MARK: - Private Methods 320 | 321 | private func performExtraction(url: URL) async throws -> ExtractionResult { 322 | // Check if file is readable 323 | guard fileManager.isReadableFile(atPath: url.path) else { 324 | throw ExtractionError.fileNotReadable(url.lastPathComponent) 325 | } 326 | 327 | // Determine extraction directory 328 | let extractDir = try getExtractionDirectory(for: url) 329 | currentOperation = "Extracting to \(extractDir.lastPathComponent)..." 330 | 331 | // Check if it's a metapackage 332 | if url.pathExtension.lowercased() == "mpkg" { 333 | try await extractMetapackage(url: url, to: extractDir) 334 | } else { 335 | // Determine package type and extract 336 | let isNewStyle = try isNewStylePackage(url: url) 337 | if isNewStyle { 338 | try await extractNewStylePackage(url: url, to: extractDir) 339 | } else { 340 | try await extractOldStylePackage(url: url, to: extractDir) 341 | } 342 | } 343 | 344 | return ExtractionResult( 345 | packageName: url.lastPathComponent, 346 | success: true, 347 | extractionPath: extractDir.path, 348 | error: nil 349 | ) 350 | } 351 | 352 | private func getExtractionDirectory(for packageURL: URL) throws -> URL { 353 | let packageName = packageURL.deletingPathExtension().lastPathComponent 354 | var baseDir = packageURL.deletingLastPathComponent() 355 | 356 | // Check if source directory is writable, if not use Desktop 357 | if !fileManager.isWritableFile(atPath: baseDir.path) { 358 | baseDir = fileManager.urls(for: .desktopDirectory, in: .userDomainMask).first! 359 | } 360 | 361 | var extractDir = baseDir.appendingPathComponent(packageName) 362 | var suffix = 1 363 | 364 | // Handle naming collisions 365 | while fileManager.fileExists(atPath: extractDir.path) && suffix < 1000 { 366 | extractDir = baseDir.appendingPathComponent("\(packageName)-\(suffix)") 367 | suffix += 1 368 | } 369 | 370 | if suffix >= 1000 { 371 | throw ExtractionError.tooManyCollisions(packageName) 372 | } 373 | 374 | try fileManager.createDirectory(at: extractDir, withIntermediateDirectories: true, attributes: nil) 375 | return extractDir 376 | } 377 | 378 | private func isNewStylePackage(url: URL) throws -> Bool { 379 | // Check for xar archive format by reading first 4 bytes 380 | let fileHandle = try FileHandle(forReadingFrom: url) 381 | defer { fileHandle.closeFile() } 382 | 383 | let data = fileHandle.readData(ofLength: 4) 384 | guard data.count == 4 else { return false } 385 | 386 | // Check for "xar!" magic bytes 387 | let magic = String(data: data, encoding: .utf8) 388 | return magic == "xar!" 389 | } 390 | 391 | private func extractNewStylePackage(url: URL, to extractDir: URL) async throws { 392 | progress = 0.2 393 | currentOperation = "Extracting package metadata..." 394 | 395 | // Create temp directory for xar extraction 396 | let tempDir = try createTempDirectory() 397 | defer { try? fileManager.removeItem(at: tempDir) } 398 | 399 | // Extract with xar 400 | try await runCommand( 401 | "/usr/bin/xar", 402 | arguments: ["-xf", url.path], 403 | workingDirectory: tempDir 404 | ) 405 | 406 | progress = 0.4 407 | currentOperation = "Processing package contents..." 408 | 409 | // Find and extract all Payload files 410 | let payloadFiles = try findPayloadFiles(in: tempDir) 411 | let totalPayloads = Double(payloadFiles.count) 412 | 413 | for (index, payloadFile) in payloadFiles.enumerated() { 414 | progress = 0.4 + (0.5 * Double(index) / totalPayloads) 415 | currentOperation = "Extracting \(payloadFile.lastPathComponent)..." 416 | 417 | let isGzipped = payloadFile.lastPathComponent.hasSuffix(".gz") || 418 | payloadFile.lastPathComponent.hasSuffix(".gzip") 419 | 420 | if isGzipped { 421 | // Use gzcat | cpio pipeline 422 | try await runPipedCommand( 423 | command1: "/usr/bin/gzcat", 424 | args1: [payloadFile.path], 425 | command2: "/usr/bin/cpio", 426 | args2: ["-idm"], 427 | workingDirectory: extractDir 428 | ) 429 | } else { 430 | // Direct cpio extraction 431 | try await runCommand( 432 | "/usr/bin/cpio", 433 | arguments: ["-idm"], 434 | workingDirectory: extractDir, 435 | inputFile: payloadFile 436 | ) 437 | } 438 | } 439 | 440 | progress = 0.9 441 | } 442 | 443 | private func extractOldStylePackage(url: URL, to extractDir: URL) async throws { 444 | progress = 0.3 445 | currentOperation = "Extracting old-style package..." 446 | 447 | // Find pax files 448 | let paxFiles = try findPaxFiles(in: url) 449 | 450 | let totalPax = Double(paxFiles.count) 451 | for (index, paxFile) in paxFiles.enumerated() { 452 | progress = 0.3 + (0.6 * Double(index) / totalPax) 453 | currentOperation = "Extracting \(paxFile.lastPathComponent)..." 454 | 455 | let isGzipped = paxFile.pathExtension == "gz" 456 | 457 | if isGzipped { 458 | // Use gzcat | pax pipeline 459 | try await runPipedCommand( 460 | command1: "/usr/bin/gzcat", 461 | args1: [paxFile.path], 462 | command2: "/bin/pax", 463 | args2: ["-r"], 464 | workingDirectory: extractDir 465 | ) 466 | } else { 467 | // Direct pax extraction 468 | try await runCommand( 469 | "/bin/pax", 470 | arguments: ["-r", "-f", paxFile.path], 471 | workingDirectory: extractDir 472 | ) 473 | } 474 | } 475 | 476 | progress = 0.9 477 | } 478 | 479 | private func extractMetapackage(url: URL, to extractDir: URL) async throws { 480 | progress = 0.1 481 | currentOperation = "Processing metapackage..." 482 | 483 | // Find all .pkg files in the metapackage 484 | let packages = try findPackagesInMetapackage(url: url) 485 | let totalPackages = Double(packages.count) 486 | 487 | for (index, package) in packages.enumerated() { 488 | progress = Double(index) / totalPackages 489 | currentOperation = "Extracting \(package.lastPathComponent)..." 490 | 491 | let packageDir = extractDir.appendingPathComponent(package.deletingPathExtension().lastPathComponent) 492 | try fileManager.createDirectory(at: packageDir, withIntermediateDirectories: true, attributes: nil) 493 | 494 | let isNewStyle = try isNewStylePackage(url: package) 495 | if isNewStyle { 496 | try await extractNewStylePackage(url: package, to: packageDir) 497 | } else { 498 | try await extractOldStylePackage(url: package, to: packageDir) 499 | } 500 | } 501 | 502 | progress = 0.9 503 | } 504 | 505 | // MARK: - Helper Methods 506 | 507 | private func createTempDirectory() throws -> URL { 508 | let tempDir = fileManager.temporaryDirectory.appendingPathComponent(UUID().uuidString) 509 | try fileManager.createDirectory(at: tempDir, withIntermediateDirectories: true, attributes: nil) 510 | return tempDir 511 | } 512 | 513 | private func findPayloadFiles(in directory: URL) throws -> [URL] { 514 | var payloadFiles: [URL] = [] 515 | let enumerator = fileManager.enumerator(at: directory, includingPropertiesForKeys: nil) 516 | 517 | while let fileURL = enumerator?.nextObject() as? URL { 518 | let fileName = fileURL.lastPathComponent 519 | if fileName.hasPrefix("Payload") || fileName == "Payload.cpio" || 520 | fileName == "Payload.cpio.gz" || fileName == "Payload.cpio.gzip" { 521 | payloadFiles.append(fileURL) 522 | } 523 | } 524 | 525 | return payloadFiles.sorted { $0.path < $1.path } 526 | } 527 | 528 | private func findPaxFiles(in packageURL: URL) throws -> [URL] { 529 | var paxFiles: [URL] = [] 530 | 531 | // Check Contents directory 532 | let contentsURL = packageURL.appendingPathComponent("Contents") 533 | guard fileManager.fileExists(atPath: contentsURL.path) else { 534 | throw ExtractionError.invalidPackageFormat("No Contents directory found") 535 | } 536 | 537 | let enumerator = fileManager.enumerator(at: contentsURL, includingPropertiesForKeys: nil) 538 | 539 | while let fileURL = enumerator?.nextObject() as? URL { 540 | let fileName = fileURL.lastPathComponent 541 | if fileName.hasSuffix(".pax") || fileName.hasSuffix(".pax.gz") { 542 | paxFiles.append(fileURL) 543 | } 544 | } 545 | 546 | if paxFiles.isEmpty { 547 | throw ExtractionError.invalidPackageFormat("No pax files found in package") 548 | } 549 | 550 | return paxFiles.sorted { $0.path < $1.path } 551 | } 552 | 553 | private func findPackagesInMetapackage(url: URL) throws -> [URL] { 554 | var packages: [URL] = [] 555 | let contentsURL = url.appendingPathComponent("Contents/Packages") 556 | 557 | guard fileManager.fileExists(atPath: contentsURL.path) else { 558 | throw ExtractionError.invalidPackageFormat("No Packages directory in metapackage") 559 | } 560 | 561 | let contents = try fileManager.contentsOfDirectory(at: contentsURL, includingPropertiesForKeys: nil) 562 | for item in contents { 563 | if item.pathExtension == "pkg" { 564 | packages.append(item) 565 | } 566 | } 567 | 568 | if packages.isEmpty { 569 | throw ExtractionError.invalidPackageFormat("No packages found in metapackage") 570 | } 571 | 572 | return packages.sorted { $0.lastPathComponent < $1.lastPathComponent } 573 | } 574 | 575 | private func runCommand(_ command: String, arguments: [String], workingDirectory: URL? = nil, inputFile: URL? = nil) async throws { 576 | let process = Process() 577 | process.executableURL = URL(fileURLWithPath: command) 578 | process.arguments = arguments 579 | 580 | if let workingDirectory = workingDirectory { 581 | process.currentDirectoryURL = workingDirectory 582 | } 583 | 584 | if let inputFile = inputFile { 585 | process.standardInput = try FileHandle(forReadingFrom: inputFile) 586 | } 587 | 588 | let outputPipe = Pipe() 589 | let errorPipe = Pipe() 590 | process.standardOutput = outputPipe 591 | process.standardError = errorPipe 592 | 593 | try process.run() 594 | process.waitUntilExit() 595 | 596 | if process.terminationStatus != 0 { 597 | let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile() 598 | let errorString = String(data: errorData, encoding: .utf8) ?? "Unknown error" 599 | throw ExtractionError.commandFailed(command, errorString) 600 | } 601 | } 602 | 603 | private func runPipedCommand(command1: String, args1: [String], command2: String, args2: [String], workingDirectory: URL) async throws { 604 | // Create processes 605 | let process1 = Process() 606 | process1.executableURL = URL(fileURLWithPath: command1) 607 | process1.arguments = args1 608 | 609 | let process2 = Process() 610 | process2.executableURL = URL(fileURLWithPath: command2) 611 | process2.arguments = args2 612 | process2.currentDirectoryURL = workingDirectory 613 | 614 | // Create pipe to connect them 615 | let pipe = Pipe() 616 | process1.standardOutput = pipe 617 | process2.standardInput = pipe 618 | 619 | // Error pipes 620 | let errorPipe1 = Pipe() 621 | let errorPipe2 = Pipe() 622 | process1.standardError = errorPipe1 623 | process2.standardError = errorPipe2 624 | 625 | // Start both processes 626 | try process1.run() 627 | try process2.run() 628 | 629 | // Wait for completion 630 | process1.waitUntilExit() 631 | process2.waitUntilExit() 632 | 633 | // Check for errors 634 | if process1.terminationStatus != 0 { 635 | let errorData = errorPipe1.fileHandleForReading.readDataToEndOfFile() 636 | let errorString = String(data: errorData, encoding: .utf8) ?? "Unknown error" 637 | throw ExtractionError.commandFailed(command1, errorString) 638 | } 639 | 640 | if process2.terminationStatus != 0 { 641 | let errorData = errorPipe2.fileHandleForReading.readDataToEndOfFile() 642 | let errorString = String(data: errorData, encoding: .utf8) ?? "Unknown error" 643 | throw ExtractionError.commandFailed(command2, errorString) 644 | } 645 | } 646 | } 647 | 648 | // MARK: - Error Types 649 | 650 | enum ExtractionError: LocalizedError { 651 | case fileNotReadable(String) 652 | case invalidPackageFormat(String) 653 | case tooManyCollisions(String) 654 | case commandFailed(String, String) 655 | 656 | var errorDescription: String? { 657 | switch self { 658 | case .fileNotReadable(let file): 659 | return "Cannot read file: \(file)" 660 | case .invalidPackageFormat(let message): 661 | return "Invalid package format: \(message)" 662 | case .tooManyCollisions(let name): 663 | return "Too many naming collisions for: \(name)" 664 | case .commandFailed(let command, let error): 665 | return "Command failed: \(command)\nError: \(error)" 666 | } 667 | } 668 | } --------------------------------------------------------------------------------