20260418

フォルダのファイルサイズ合計

フォルダ内のファイルサイズを種類別で合計を出力

ダウンロードはこちら
NOTE記事一覧ですnote.com

【スクリプトエディタで開く】 |

フォルダ内のファイルサイズ合計MD.scpt.scpt
ソース
001#!/usr/bin/env osascript
002#coding: utf-8
003----+----1----+----2----+-----3----+----4----+----5----+----6----+----7--
004(*
005
0061:ダイアログ
0072:コンテンツの収集
0083:サイズ取得
0094:Dict化
0105:タブ区切りテキストに(ファイルサイズ tab UTIの並び)
0116:大きい順にソート
0127:タブ区切りテキストに(UTI tab ファイルサイズの並び)
0138:ダイアログ
014
015
016順番で処理
017
018
019v1 初回作成
020v1.1 ダイアログをつけてMDで保存できるようにした
021v1.2 指定したパスをMDの出力結果に付与
022
023com.cocolog-nifty.quicktimer.icefloe *)
024----+----1----+----2----+-----3----+----4----+----5----+----6----+----7--
025use AppleScript version "2.8"
026use framework "Foundation"
027use framework "AppKit"
028use framework "UniformTypeIdentifiers"
029use scripting additions
030
031property refMe : a reference to current application
032
033####################################
034#1:ダイアログ
035set appFileManager to refMe's NSFileManager's defaultManager()
036set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDownloadsDirectory) inDomains:(refMe's NSUserDomainMask))
037set ocidDownloadsDirPathURL to ocidURLsArray's firstObject()
038set aliasDefaultLocation to (ocidDownloadsDirPathURL's absoluteURL()) as alias
039set strMsg to ("フォルダ選択") as text
040set strPrompt to ("ファイルを調べるフォルダを選んでください") as text
041try
042   tell application "SystemUIServer"
043      activate
044      set aliasDirPath to (choose folder strMsg with prompt strPrompt default location aliasDefaultLocation with invisibles and showing package contents without multiple selections allowed) as alias
045   end tell
046on error strErrMsg number numErrNo
047   log strErrMsg & numErrNo
048   return false
049end try
050
051
052set strDirPath to (POSIX path of aliasDirPath) as text
053set ocidDirPathStr to refMe's NSString's stringWithString:(strDirPath)
054set ocidDirPath to ocidDirPathStr's stringByStandardizingPath()
055set ocidDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidDirPath) isDirectory:true)
056
057
058####################################
059#2:コンテンツの収集
060set ocidKeyArray to refMe's NSMutableArray's alloc()'s init()
061ocidKeyArray's addObject:(refMe's NSURLPathKey)
062ocidKeyArray's addObject:(refMe's NSURLNameKey)
063ocidKeyArray's addObject:(refMe's NSURLTotalFileAllocatedSizeKey)
064ocidKeyArray's addObject:(refMe's NSURLTotalFileSizeKey)
065ocidKeyArray's addObject:(refMe's NSURLFileSizeKey)
066ocidKeyArray's addObject:(refMe's NSURLContentTypeKey)
067ocidKeyArray's addObject:(refMe's NSURLIsDirectoryKey)
068#オプション
069set ocidOption to (0) as integer
070#収集
071set boolHasPre to (ocidDirPathStr's hasPrefix:("/Users"))
072if boolHasPre is false then
073   set ocidEmuDict to appFileManager's enumeratorAtURL:(ocidDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) errorHandler:(missing value)
074else if boolHasPre is true then
075   set ocidEmuDict to appFileManager's enumeratorAtURL:(ocidDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) errorHandler:(reference)
076end if
077
078####################################
079#3:サイズ取得
080#次工程に回すDICT
081set ocidSizeDict to refMe's NSMutableDictionary's alloc()'s init()
082ocidSizeDict's setObject:(0) forKey:("合計")
083set ocidValue to (missing value)
084#収集したURLをひとつずつ確認
085repeat
086   set ocidEnuURL to ocidEmuDict's nextObject()
087   if ocidEnuURL = (missing value) then
088      exit repeat
089   else
090      #フォルダは対象外
091      set listResponse to (ocidEnuURL's getResourceValue:(reference) forKey:(refMe's NSURLIsDirectoryKey) |error|:(reference))
092      set boolIsDir to (2nd item of listResponse) as boolean
093      if boolIsDir is true then
094         #フォルダには何もしない
095      else if boolIsDir is false then
096         #ファイルなら AllocatedSize を取得
097         set listResponse to (ocidEnuURL's getResourceValue:(reference) forKey:(refMe's NSURLTotalFileAllocatedSizeKey) |error|:(reference))
098         set ocidResponseValue to (2nd item of listResponse)
099         if ocidResponseValue = (missing value) then
100            set numSizeValue to 0 as number
101         else
102            set numSizeValue to ocidResponseValue's longLongValue()
103         end if
104         set ocidFileName to ocidEnuURL's lastPathComponent()
105         #合計処理
106         set ocidTotalValue to ocidSizeDict's objectForKey:("合計")
107         set numTotalValue to ocidTotalValue's longLongValue()
108         set numSetTotalSize to (numTotalValue + numSizeValue)
109         ocidSizeDict's setObject:(numSetTotalSize) forKey:("合計")
110         #DS_Storeは別処理で収集
111         set boolIsEq to (ocidFileName's isEqualToString:(".DS_Store"))
112         if boolIsEq is true then
113            set ocidValue to ocidSizeDict's objectForKey:("DS_Store")
114            if ocidValue ≠ (missing value) then
115               set numValue to ocidValue's longLongValue()
116               set numSetSize to (numValue + numSizeValue)
117               ocidSizeDict's setObject:(numSetSize) forKey:("DS_Store")
118            else if ocidValue = (missing value) then
119               ocidSizeDict's setObject:(numSizeValue) forKey:("DS_Store")
120            end if
121         else
122            #DS_Store以外はUTIを取得
123            set listResponse to (ocidEnuURL's getResourceValue:(reference) forKey:(refMe's NSURLContentTypeKey) |error|:(reference))
124            set ocidUTType to (2nd item of listResponse)
125            #UTI取得
126            set ocidSetKey to ocidUTType's identifier()
127            #DYN=デフォルトのアプリケーションが指定されていないファイルの場合
128            set boolHasPre to (ocidSetKey's hasPrefix:("dyn")) as boolean
129            if boolHasPre is true then
130               #拡張子をキーにする
131               set ocidSetKey to ocidEnuURL's pathExtension()
132               #拡張子がない場合は
133               if ocidSetKey = (missing value) then
134                  #やっぱりUTIをキーにしておく
135                  set ocidSetKey to ocidUTType's identifier()
136               end if
137            else
138               ####################################
139               #4:Dict化 ファイルサイズは合計しながらDICT化していく
140               set ocidValue to ocidSizeDict's objectForKey:(ocidSetKey)
141               if ocidValue ≠ (missing value) then
142                  set numValue to ocidValue's longLongValue()
143                  set numSetSize to (numValue + numSizeValue)
144                  ocidSizeDict's setObject:(numSetSize) forKey:(ocidSetKey)
145               else if ocidValue = (missing value) then
146                  ocidSizeDict's setObject:(numSizeValue) forKey:(ocidSetKey)
147               end if
148            end if
149         end if
150      end if
151   end if
152end repeat
153
154
155####################################
156#5:タブ区切りテキストに(ファイルサイズ tab UTIの並び)
157set ocidAllKeys to ocidSizeDict's allKeys()
158set ocidOutputString to refMe's NSMutableString's alloc()'s init()
159
160repeat with itemKey in ocidAllKeys
161   set ocidValue to (ocidSizeDict's objectForKey:(itemKey))'s stringValue()
162   #VALUE=ファイルサイズを先に(ソート用に)してテキストにする
163   #なんでこんな事をしたか?というと ファイルサイズの合計値が同じになる場合があるので
164   #ファイルサイズの合計値をキーとして利用できないため
165   (ocidOutputString's appendString:(ocidValue))
166   (ocidOutputString's appendString:(tab))
167   (ocidOutputString's appendString:(itemKey))
168   (ocidOutputString's appendString:(linefeed))
169end repeat
170
171####################################
172#6:大きい順にソート
173#改行毎でArrayにして
174set ocidCharSet to refMe's NSCharacterSet's newlineCharacterSet()
175set ocidLineArray to ocidOutputString's componentsSeparatedByCharactersInSet:(ocidCharSet)
176#ソートする
177set appDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(false) selector:("localizedStandardCompare:")
178set ocidDescriptorArrayM to refMe's NSMutableArray's alloc()'s init()
179ocidDescriptorArrayM's addObject:(appDescriptor)
180set ocidSortedArray to ocidLineArray's sortedArrayUsingDescriptors:(ocidDescriptorArrayM)
181
182
183####################################
184#7:タブ区切りテキストに(UTI tab ファイルサイズの並び)
185
186set ocidOutputString to refMe's NSMutableString's alloc()'s init()
187
188repeat with itemLineString in ocidSortedArray
189   #タブでArrayにして
190   set ocidItemLineArray to (itemLineString's componentsSeparatedByString:(tab))
191   #値を取り出して
192   set ocidValue to ocidItemLineArray's firstObject()
193   set ocidKey to ocidItemLineArray's lastObject()
194   #数値をファイルサイズに変換
195   set appFormatter to refMe's NSByteCountFormatter's alloc()'s init()
196   (appFormatter's setAllowedUnits:(refMe's NSByteCountFormatterUseAll))
197   (appFormatter's setCountStyle:(refMe's NSByteCountFormatterCountStyleFile))
198   set ocidAllocSize to (appFormatter's stringFromByteCount:(ocidValue))
199   #今度はUTIを先にしてタブ区切りテキストにする
200   set boolIsEq to (ocidKey's isEqualToString:(""))
201   if boolIsEq is true then
202      (ocidOutputString's appendString:("未分類"))
203   else
204      (ocidOutputString's appendString:(ocidKey))
205   end if
206   (ocidOutputString's appendString:(tab))
207   (ocidOutputString's appendString:(ocidAllocSize))
208   (ocidOutputString's appendString:(linefeed))
209   
210end repeat
211
212
213
214########################
215#8:ダイアログ
216set strOutputString to ocidOutputString as text
217set strTitle to ("処理をえらんでください") as text
218set strMsg to ("TSVタブ区切りテキストになっています" & linefeed & "処理を選んでください") as text
219set strOK to ("クリップボードにコピー") as text
220set strCancel to ("保存せずに終了") as text
221set strSaveMD to ("MD形式で保存")
222set listButtons to {strSaveMD, strCancel, strOK}
223set aliasIconPath to (POSIX file "/System/Applications/TextEdit.app/Contents/Resources/AppIcon.icns")
224#
225try
226   tell application "SystemUIServer"
227      activate
228      set recordResult to (display dialog strMsg with title strTitle buttons listButtons default button strOK cancel button strCancel giving up after 60 with icon aliasIconPath default answer strOutputString) as record
229   end tell
230on error strErrMes number numErrNo
231   try
232      tell application "System Events" to quit
233   end try
234   log strErrMes & numErrNo
235   return false
236end try
237
238if (gave up of recordResult) is true then
239   return false
240else if (button returned of recordResult) is strCancel then
241   return false
242else if (button returned of recordResult) is strOK then
243   set strOutputString to (text returned of recordResult)
244   set boolDone to doSendPasteboard(strOutputString)
245else if (button returned of recordResult) is strSaveMD then
246   set boolDone to doMakeMdTable(strOutputString, ocidDirPath)
247end if
248
249
250return true
251
252
253
254########################
255#MDのテーブル生成と保存まで
256to doMakeMdTable(argOutputString, ocidDirPath)
257   
258   set strHeader to ("UTI" & tab & "合計サイズ" & linefeed & "") as text
259   set ocidTSVstring to refMe's NSMutableString's stringWithString:(strHeader)
260   (ocidTSVstring's appendString:(argOutputString))
261   
262   #改行をUNIXに強制(Force line breaks to UNIX)
263   set strLF to ("" & linefeed & "") as text
264   set strCR to ("" & return & "") as text
265   set strCRLF to ("" & return & linefeed & "") as text
266   set strSpace to ("" & space & "") as text
267   set strTab to ("" & tab & "") as text
268   
269   #行末の改行を削除(Delete the line break at the end of the line)
270   set boolHas to (ocidTSVstring's hasSuffix:(strLF)) as boolean
271   if boolHas is true then
272      set ocidLength to ((ocidTSVstring's |length|()) - 1) as integer
273      set ocidTSVstring to ocidTSVstring's substringToIndex:(ocidLength)
274   end if
275   #改行でArrayにする(Make it Array with a new line)
276   set ocidTSVArray to ocidTSVstring's componentsSeparatedByString:(strLF)
277   
278   #Arrayの空の項目(空行)削除
279   set ocidNULL to refMe's NSNull's |null|()
280   set appPredicate to refMe's NSPredicate's predicateWithFormat_("SELF != '' AND SELF != ' ' AND SELF != %@", ocidNULL)
281   set ocidTSVArray to ocidTSVArray's filteredArrayUsingPredicate:(appPredicate)
282   
283   ########################
284   #アライメント行作成(Create an alignment line)
285   #最大値格納用のリスト(List for maximum value storage)
286   set listCntMax to {} as list
287   #最大文字数判定用のリストを作る(Make a list for determining the maximum number of characters)
288   set ocidFirstLine to ocidTSVArray's firstObject()
289   set ocidLineArray to (ocidFirstLine's componentsSeparatedByString:(strTab))
290   set numCntLineArray to ocidLineArray's |count|()
291   repeat with itemNo from 1 to (numCntLineArray) by 1
292      set end of listCntMax to 0
293   end repeat
294   
295   #最大桁数取得(Obtain the maximum number of digits)
296   repeat with itemArray in ocidTSVArray
297      set ocidLineArray to (itemArray's componentsSeparatedByString:(strTab))
298      set numCntLineArray to ocidLineArray's |count|()
299      repeat with itemNo from 0 to (numCntLineArray - 1) by 1
300         set ocidItemString to (ocidLineArray's objectAtIndex:(itemNo))
301         set numCharLength to ocidItemString's |length|() as integer
302         set numMaxItem to (item (itemNo + 1) of listCntMax) as integer
303         if numMaxItem < numCharLength then
304            copy numCharLength to (item (itemNo + 1) of listCntMax)
305         end if
306      end repeat
307   end repeat
308   
309   #アライメント行を先に作っておく(Make the alignment line first)
310   set strAlignment to ("") as text
311   set numCntRaw to (count of listCntMax) as integer
312   
313   set strAlignment to ("" & strAlignment & "|") as text
314   repeat with itemNo from 1 to numCntRaw by 1
315      #左寄せ時 または 中央寄せ時(When pulling left or when pulling in the center)
316      #      set strAlignment to ("" & strAlignment & ":-") as text
317      #右寄せ時(When to the right)
318      set strAlignment to ("" & strAlignment & "-") as text
319      set numCntItemLine to (item itemNo of listCntMax)
320      repeat with itemIntNo from 1 to numCntItemLine by 1
321         set strAlignment to ("" & strAlignment & "-") as text
322         if itemIntNo > 8 then
323            exit repeat
324         end if
325      end repeat
326      #中央寄せ時 または 右寄せ時(When centered or right)
327      set strAlignment to ("" & strAlignment & "-:|") as text
328      #左寄せ時(When it's coming)
329      #   set strAlignment to ("" & strAlignment & "-|") as text
330   end repeat
331   
332   set strAlignment to ("" & "|---:" & strAlignment & "") as text
333   
334   #   set strAlignment to ("|---:|:-----------|---------:|") as text
335   
336   
337   ########################
338   #出力用テキスト(Text for output)
339   set ocidOutputString to refMe's NSMutableString's alloc()'s init()
340   ocidOutputString's appendString:(ocidDirPath)
341   ocidOutputString's appendString:(strLF & strLF)
342   #ヘッダー行作成(Create a header line)
343   set ocidFirstLine to ocidTSVArray's firstObject()
344   set ocidLineArray to (ocidFirstLine's componentsSeparatedByString:(strTab))
345   set numCntLineArray to ocidLineArray's |count|()
346   ocidOutputString's appendString:("|  |")
347   
348   
349   repeat with itemNo from 0 to (numCntLineArray - 1) by 1
350      set ocidItemText to (ocidLineArray's objectAtIndex:(itemNo))
351      (ocidOutputString's appendString:(" "))
352      (ocidOutputString's appendString:(ocidItemText))
353      (ocidOutputString's appendString:(" "))
354      (ocidOutputString's appendString:("|"))
355   end repeat
356   (ocidOutputString's appendString:(strLF))
357   
358   #アライメント行挿入(Alignment line insertion)
359   (ocidOutputString's appendString:(strAlignment))
360   (ocidOutputString's appendString:(strLF))
361   
362   #テーブルボディの処理(Table body processing)
363   set numCntTsvArray to ocidTSVArray's |count|()
364   set numCntLineNo to 0 as integer
365   #1行目は処理済みだから2行目から(The first line has been processed, so from the second line)
366   repeat with itemNo from 1 to (numCntTsvArray - 1) by 1
367      set ocidLineTsv to (ocidTSVArray's objectAtIndex:(itemNo))
368      set ocidLineArray to (ocidLineTsv's componentsSeparatedByString:(strTab))
369      set numCntLineNo to (numCntLineNo + 1) as integer
370      #ゼロサプレス2桁
371      set strCntLoneNo to ("000" & numCntLineNo & "") as text
372      set strCntLoneNo to (text -2 through -1 of strCntLoneNo) as text
373      set strLineNo to ("| " & strCntLoneNo & " | ") as text
374      (ocidOutputString's appendString:(strLineNo))
375      
376      #各TD要素項目の処理
377      repeat with itemString in ocidLineArray
378         (ocidOutputString's appendString:(" "))
379         (ocidOutputString's appendString:(itemString))
380         (ocidOutputString's appendString:(" "))
381         (ocidOutputString's appendString:("|"))
382      end repeat
383      (ocidOutputString's appendString:(strLF))
384   end repeat
385   
386   ##リンクの置換 正規表現初期化
387   set strPattern to ("(https?://[^\\s|]+)") as text
388   set ocidRefPattern to (refMe's NSString's stringWithString:(strPattern))
389   set listResponse to (refMe's NSRegularExpression's regularExpressionWithPattern:(ocidRefPattern) options:(0) |error|:(reference))
390   set appRegex to (first item of listResponse)
391   ##リンクの置換
392   set ocidLength to ocidOutputString's |length|()
393   set ocidRange to refMe's NSRange's NSMakeRange(0, ocidLength)
394   set ocidResultString to appRegex's stringByReplacingMatchesInString:(ocidOutputString) options:(0) range:(ocidRange) withTemplate:("[LINK]($1)")
395   
396   
397   set strSaveFileName to ("MarkdownTable.md") as text
398   set strTargetExtension to ("md") as text
399   set appFileManager to refMe's NSFileManager's defaultManager()
400   set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
401   set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
402   set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
403   #
404   set strMsg to ("保存先を指定してください") as text
405   set strPrompt to ("保存先・ファイル名を指定してください") as text
406   try
407      tell application "SystemUIServer"
408         activate
409         set aliasFilePath to (choose file name strMsg with prompt strPrompt default location aliasDesktopDirPath default name strSaveFileName) as «class furl»
410      end tell
411   on error strErrMes number numErrNo
412      log strErrMes & numErrNo
413      return false
414   end try
415   set strFilePath to (POSIX path of aliasFilePath) as text
416   set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
417   set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
418   set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
419   set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
420   ###拡張子
421   set strExtension to (ocidFilePathURL's pathExtension()) as text
422   ###最後のアイテムがファイル名
423   set strFileName to (ocidFilePathURL's lastPathComponent()) as text
424   ###拡張子のつけ忘れ対策
425   if strFileName does not contain strTargetExtension then
426      set strFileName to (strFileName & "." & strTargetExtension) as text
427      set ocidFilePathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:(strFileName)
428   end if
429   set listDone to ocidOutputString's writeToURL:(ocidFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
430   
431   
432   try
433      with timeout of 5 seconds
434         tell application "System Events" to quit
435      end timeout
436   end try
437   
438   return true
439end doMakeMdTable
440
441
442########################
443#クリップボードにコピー
444on doSendPasteboard(argText)
445   set appPasteboard to refMe's NSPasteboard's generalPasteboard()
446   set ocidText to (refMe's NSString's stringWithString:(argText))
447   appPasteboard's clearContents()
448   set boolDone to appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString)
449   if boolDone is false then
450      try
451         tell application "Finder"
452            set the clipboard to argText as text
453         end tell
454      on error
455         return false
456      end try
457   else if boolDone is true then
458      return true
459   end if
460end doSendPasteboard
AppleScriptで生成しました