20260617

【Finder】ファイル名でフォルダを作って、ファイルをフォルダの中に入れる

【Finder】ファイル名でフォルダを作って、ファイルをフォルダの中に入れる

NOTE記事一覧ですnote.com

【Safari・FireFox用Script Editorで開く】 |

Folder_IN.scpt.scpt
ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003(*
004ファイル名(拡張子を除く)のフォルダを作って
005ファイルをそのフォルダの中に入れる
006
007スクリプトエディタで開いて
008ファイル>>書き出す>>アプリケーションで保存してください
009
010v1 初回作成
011
012v2 ドロップレットアプリケーションに書き出すとフォルダでも動作するようにした
013v3 重複チェックを入れた
014v4 WEBLOC等でOpenしてしまうので
015v4.1 OPENを利用しないドロップレットに変更した
016v4.2 拡張子のないファイルに対応
017v4.3 デスクトップでの処理に限りファイルのあった場所にフォルダが来るようにした
018v4.4 RUNのダイアログの戻り値をOPENに渡さずに直接本処理に渡すように変更(WEBLOC対策)
019
020com.cocolog-nifty.quicktimer.icefloe *)
021----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
022use AppleScript version "2.8"
023use framework "Foundation"
024use framework "AppKit"
025use scripting additions
026
027property refMe : a reference to current application
028property listAliasFilePath : a reference to {} as list
029
030
031####################################
032#ダブルクリックかスクリプトエディタから実行
033#   on run {listAliasFilePath}
034
035(*
036   #テスト用
037   
038      *)
039on run
040   if (count of listAliasFilePath) = 0 then
041      
042      
043      set appFileManager to refMe's NSFileManager's defaultManager()
044      set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
045      set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
046      set aliasDesktopDirPath to ocidDesktopDirPathURL's absoluteURL() as alias
047      set strMes to ("ファイルを選んでください") as text
048      set strPrompt to ("ファイルを選んでください") as text
049      set listUTI to {"public.item"} as list
050      try
051         tell application "Finder"
052            tell application "SystemUIServer"
053               activate
054               set listAliasFilePath to (choose file strMes with prompt strPrompt default location (aliasDesktopDirPath) of type listUTI with multiple selections allowed without showing package contents and invisibles) as list
055            end tell
056         end tell
057      on error strErrMes number numErrNo
058         log (strErrMes & numErrNo) as text
059         return false
060      end try
061   end if
062   
063   #サブルーチンに渡す
064   set boolDone to doAction(listAliasFilePath)
065   
066   #サブルーチンの戻り値でエラーチェック
067   if boolDone is false then
068      tell application "System Events"
069         activate
070         display alert "エラーが発生しました" message "エラーが発生しましたログを確認ください3"
071      end tell
072      try
073         with timeout of 3 seconds
074            tell application "System Events" to quit
075         end timeout
076      on error strErrMes number numErrNo
077         log "Quit System Events" & strErrMes & numErrNo
078         return false
079      end try
080   end if
081   doQuitSelf()
082   return
083   
084end run
085
086
087####################################
088#ドロップレットでドロップした場合
089
090on open listAliasFilePath
091   
092   #サブルーチンに渡す
093   set boolDone to doAction(listAliasFilePath)
094   
095   return boolDone
096   
097end open
098
099####################################
100#
101on doAction(argListAliasFilePath)
102   ##ファイルマネージャ初期化
103   set appFileManager to refMe's NSFileManager's defaultManager()
104   ##繰り返しのはじまり
105   repeat with itemAliasFilePath in argListAliasFilePath
106      set aliasFilePath to itemAliasFilePath as alias
107      #対象がデスクトップにある場合のみポジションを保持する
108      tell application "Finder"
109         set aliasContainer to (container of aliasFilePath) as alias
110         if aliasContainer is ((path to desktop folder from user domain) as alias) then
111            set listPosition to (desktop position of item aliasFilePath) as list
112            set boolDesktop to true as boolean
113         else
114            set boolDesktop to false as boolean
115         end if
116      end tell
117      #パスをNSURLにして
118      set strFilePath to (POSIX path of aliasFilePath) as text
119      set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
120      set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
121      set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath))
122      #getResourceValue
123      set listResponse to (ocidFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLIsDirectoryKey) |error|:(reference))
124      set boolActionPathIsDir to (item 2 of listResponse)'s boolValue() as boolean
125      ##拡張子
126      set ocidExtensionName to ocidFilePathURL's pathExtension()
127      ##フォルダを作るディレクトリ
128      set ocidConteinerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
129      ##ファイル名(拡張子あり)
130      set ocidFileName to ocidFilePathURL's lastPathComponent()
131      ##拡張子をとって
132      set ocidBaseFileName to ocidFileName's stringByDeletingPathExtension()
133      #カンマを置換する→これがフォルダ名
134      #拡張子が2重に指定してあるケース対応でカンマをアンダースコアに置換する
135      set ocidDirName to (ocidBaseFileName's stringByReplacingOccurrencesOfString:(".") withString:("_"))
136      #作成するフォルダパス
137      set ocidMakeDirPathURL to (ocidConteinerDirPathURL's URLByAppendingPathComponent:(ocidDirName) isDirectory:(true))
138      ##フォルダパス+ファイル名で移動先
139      set ocidMoveFilePathURL to (ocidMakeDirPathURL's URLByAppendingPathComponent:(ocidFileName) isDirectory:(false))
140      ##作ろうとしているディレクトリがすでに無いか?確認
141      set ocidMakeDirPath to ocidMakeDirPathURL's |path|()
142      set boolDirExists to (appFileManager's fileExistsAtPath:(ocidMakeDirPath))
143      log boolDirExists
144      #ファイルかフォルダかがすでにあるなら
145      if boolDirExists is true then
146         #フォルダか?を確認して
147         set listResponse to (ocidMakeDirPathURL's getResourceValue:(reference) forKey:(refMe's NSURLIsDirectoryKey) |error|:(reference))
148         set boolIsDir to (item 2 of listResponse)'s boolValue() as boolean
149         log boolIsDir
150         if boolIsDir is true then
151            if boolActionPathIsDir is true then
152               set boolIsDir to false
153            end if
154         end if
155      else if boolDirExists is false then
156         set boolIsDir to false
157      end if
158      
159      if boolIsDir is true then
160         log "フォルダがすでにある"
161         #-->今あるフォルダをそのまま利用
162         ##重複チェック
163         set ocidDistFilePath to doChkExists(ocidMoveFilePathURL)
164         if ocidDistFilePath is false then
165            tell application "System Events"
166               activate
167               display alert "エラーが発生しました" message "重複チェックでエラーになりました"
168            end tell
169            log "重複チェックでエラーになりました"
170            return false
171         end if
172         set ocidDistFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidDistFilePath) isDirectory:false)
173         if ocidMoveFilePathURL = ocidMoveFilePathURL then
174            log "置換します"
175            #今あるファイルをゴミ箱に
176            set listResult to (appFileManager's trashItemAtURL:(ocidDistFilePathURL) resultingItemURL:(ocidDistFilePathURL) |error|:(reference))
177            #移動
178            set ListDone to (appFileManager's moveItemAtURL:(ocidFilePathURL) toURL:(ocidDistFilePathURL) |error|:(reference))
179         else
180            #移動
181            set ListDone to (appFileManager's moveItemAtURL:(ocidFilePathURL) toURL:(ocidDistFilePathURL) |error|:(reference))
182         end if
183         set boolDone to (item 1 of ListDone) as boolean
184         if boolDone is false then
185            tell application "System Events"
186               activate
187               display alert "移動に失敗しました1"
188            end tell
189            return false
190         end if
191         
192      else if boolIsDir is false then
193         log "フォルダを作る"
194         #UUIDでフォルダを作り
195         set ocidUUID to refMe's NSUUID's alloc()'s init()
196         set ocidUUIDString to ocidUUID's UUIDString()
197         set ocidTMPDirPathURL to (ocidConteinerDirPathURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:(true))
198         set ocidAttrDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
199         # 777-->511 755-->493 700-->448 766-->502 
200         (ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions))
201         set listBoolMakeDir to (appFileManager's createDirectoryAtURL:(ocidTMPDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference))
202         ##テンポラリーへ移動のパス
203         set ocidDistFilePathURL to (ocidTMPDirPathURL's URLByAppendingPathComponent:(ocidFileName) isDirectory:(false))
204         #移動
205         set ListDone to (appFileManager's moveItemAtURL:(ocidFilePathURL) toURL:(ocidDistFilePathURL) |error|:(reference))
206         
207         set boolDone to (item 1 of ListDone) as boolean
208         if boolDone is false then
209            tell application "System Events"
210               activate
211               display alert "移動に失敗しました2"
212            end tell
213            return false
214         end if
215         #リネーム
216         set ListDone to (appFileManager's moveItemAtURL:(ocidTMPDirPathURL) toURL:(ocidMakeDirPathURL) |error|:(reference))
217      end if
218      set aliasMakeDirPath to (ocidMakeDirPathURL's absoluteURL()) as alias
219      if boolDesktop is true then
220         tell application "Finder"
221            set desktop position of item aliasMakeDirPath to listPosition
222         end tell
223      end if
224   end repeat
225   return true
226end doAction
227
228
229
230
231####################################
232#上書きチェック
233# ocid file path = NSPathStore を返します
234####################################
235to doChkExists(argFilePath)
236   log (className() of argFilePath) as text
237   if (class of argFilePath) is text then
238      log "テキストファイルパス"
239      set ocidFilePathStr to refMe's NSString's stringWithString:(argFilePath)
240      set ocidArgFilePath to ocidFilePathStr's stringByStandardizingPath()
241   else if (class of argFilePath) is alias then
242      log "エリアスファイルパス"
243      set strArgFilePath to (POSIX path of argFilePath) as text
244      set ocidFilePathStr to refMe's NSString's stringWithString:(argFilePath)
245      set ocidArgFilePath to ocidFilePathStr's stringByStandardizingPath()
246   else if (class of argFilePath) is «class furl» then
247      log "エリアスfurlファイルパス"
248      set aliasFilePath to argFilePath as alias
249      set strArgFilePath to (POSIX path of argFilePath) as text
250      set ocidFilePathStr to refMe's NSString's stringWithString:(argFilePath)
251      set ocidArgFilePath to ocidFilePathStr's stringByStandardizingPath()
252   else if (className() of argFilePath as text) contains "NSCFString" then
253      log "NSStringファイルパス"
254      set ocidArgFilePath to argFilePath's stringByStandardizingPath()
255   else if (className() of argFilePath as text) contains "NSPathStore" then
256      log "NSPathStore2ファイルパス"
257      set ocidArgFilePath to argFilePath
258   else if (className() of argFilePath as text) contains "NSURL" then
259      log "NSURLファイルパス"
260      set ocidArgFilePath to argFilePath's |path|
261   end if
262   ####
263   set appFileManager to refMe's NSFileManager's defaultManager()
264   set boolExists to appFileManager's fileExistsAtPath:(ocidArgFilePath) isDirectory:(false)
265   #
266   if boolExists = true then
267      ##ダイアログを前面に
268      set strName to (name of current application) as text
269      if strName is "osascript" then
270         tell application "SystemUIServer" to activate
271      else
272         tell current application to activate
273      end if
274      set strMes to "同名のファイルがすでにあります" & return & "上書きします?" as text
275      try
276         tell application "System Events"
277            activate
278            set objResponse to (display alert strMes buttons {"上書きする", "処理を中止する", "ファイル名を変更"} default button "上書きする" cancel button "処理を中止する" as informational giving up after 20)
279         end tell
280      on error
281         log "処理を中止しました"
282         return false
283      end try
284      if true is equal to (gave up of objResponse) then
285         log "時間切れですやりなおしてください"
286         return false
287      end if
288      if "上書きする" is equal to (button returned of objResponse) then
289         log "上書き保存します"
290         set ocidReturnFilePath to ocidArgFilePath
291      else if "ファイル名を変更" is equal to (button returned of objResponse) then
292         log "ファイル名を変更"
293         set ocidContainerDirFilePath to ocidArgFilePath's stringByDeletingLastPathComponent()
294         set strFileName to ocidArgFilePath's lastPathComponent() as text
295         set aliasContainerDirPath to (POSIX file (ocidContainerDirFilePath as text)) as alias
296         ##
297         set strPromptText to "名前を決めてください" as text
298         set strMesText to "名前を決めてください" as text
299         ###ファイル名 ダイアログ
300         try
301            tell application "SystemUIServer"
302               activate
303               set aliasFilePath to (choose file name strMesText default location aliasContainerDirPath default name strFileName with prompt strPromptText) as «class furl»
304            end tell
305         on error strErrMes number numErrNo
306            set strErrMes to (strErrMes & numErrNo) as text
307            tell application "System Events"
308               activate
309               display alert "エラーが発生しました" message strErrMes as informational giving up after 5
310            end tell
311            return false
312         end try
313         set strFilePath to (POSIX path of aliasFilePath) as text
314         set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
315         set ocidReturnFilePath to ocidFilePathStr's stringByStandardizingPath()
316      else if "処理を中止する" is equal to (button returned of objResponse) then
317         return false
318      else
319         return false
320      end if
321   else if boolExists = false then
322      log "そのままファイル生成"
323      set ocidReturnFilePath to ocidArgFilePath
324   end if
325   return ocidReturnFilePath
326   
327end doChkExists
328
329
330
331
332####################################
333#
334to doQuitSelf()
335   try
336      tell application "System Events" to quit
337   end try
338   set strOutputString to (missing value)
339   set listAliasFilePath to (missing value)
340   set listBundleID to {"com.apple.automator.xpc.runner", "com.apple.automator.xpc.workflowServiceRunner"} as list
341   repeat with itemBundleID in listBundleID
342      set ocidAppArray to (refMe's NSRunningApplication's runningApplicationsWithBundleIdentifier:(itemBundleID))
343      repeat with itemApp in ocidAppArray
344         try
345            set boolDone to itemApp's terminate()
346         end try
347      end repeat
348   end repeat
349   return true
350end doQuitSelf
AppleScriptで生成しました