File

ファイル比較 (選んだファイルが同一の内容か?の判断)

202411220657051_569x550
こんな感じでHTMLで比較結果を表示します

AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004# 選んだファイルを比較して 内容が同じか?判断します
005# 生成するHTMLは再起動時に削除されますので放置でOK
006#
007----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
008use AppleScript version "2.8"
009use framework "Foundation"
010use framework "UniformTypeIdentifiers"
011use framework "AppKit"
012
013use scripting additions
014property refMe : a reference to current application
015set appFileManager to refMe's NSFileManager's defaultManager()
016###ダイアログ
017set strName to (name of current application) as text
018if strName is "osascript" then
019  tell application "Finder" to activate
020else
021  tell current application to activate
022end if
023set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
024set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
025set aliasDefaultLocation to (ocidDesktopDirPathURL's absoluteURL()) as alias
026set listUTI to {"public.item"}
027set strMes to ("ファイルを選んでください") as text
028set strPrompt to ("ファイルを選んでください") as text
029try
030  ### ファイル選択時
031  set listAliasFilePath to (choose file strMes with prompt strPrompt default location aliasDefaultLocation of type listUTI with invisibles, multiple selections allowed and showing package contents) as list
032on error
033  log "エラーしました"
034  return "エラーしました"
035end try
036if listAliasFilePath is {} then
037  return "選んでください"
038end if
039
040################## 
041#情報収集
042#出力用のDICT
043set ocidResultDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
044#選択した順番に出力したいので入力順をリストにしておく
045set listKey to {} as list
046#ファイルの数だけ繰り返し
047repeat with itemAliasFilePath in listAliasFilePath
048  #出力用のDICTにセットするファイルの内容を格納するDICT
049  set ocidItemDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
050  #パス
051  set aliasItemFilePath to itemAliasFilePath as alias
052  set strItemFilePath to (POSIX path of aliasItemFilePath) as text
053  set ocidItemFilePathStr to (refMe's NSString's stringWithString:(strItemFilePath))
054  set ocidItemFilePath to ocidItemFilePathStr's stringByStandardizingPath()
055  #ファイル名はキーに使う
056  set ocidFileName to (ocidItemFilePath's lastPathComponent())
057  #順番用のリストに格納
058  set end of listKey to (ocidFileName as text)
059  set ocidItemFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidItemFilePath) isDirectory:false)
060  #パスとURLを格納
061  (ocidItemDict's setObject:(ocidItemFilePath) forKey:("PATH"))
062  (ocidItemDict's setObject:(ocidItemFilePathURL) forKey:("URL"))
063  #サイズ
064  set listResponse to (ocidItemFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLFileSizeKey) |error| :(reference))
065  set ocidSetValue to (item 2 of listResponse)
066  (ocidItemDict's setObject:(ocidSetValue) forKey:("SIZE"))
067  #変更日
068  set listResponse to (ocidItemFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLContentModificationDateKey) |error| :(reference))
069  set ocidSetValue to (item 2 of listResponse)
070  (ocidItemDict's setObject:(ocidSetValue) forKey:("ModDate"))
071  #作成日
072  set listResponse to (ocidItemFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLCreationDateKey) |error| :(reference))
073  set ocidSetValue to (item 2 of listResponse)
074  (ocidItemDict's setObject:(ocidSetValue) forKey:("CreDate"))
075  #MD5
076  set argCommandText to ("/sbin/md5 \"" & strItemFilePath & "\"") as text
077  set strValue to doExecTask(argCommandText)
078  set ocidValueStr to (refMe's NSString's stringWithString:(strValue))
079  set ocidValueArray to (ocidValueStr's componentsSeparatedByString:("="))
080  set ocidItemValue to ocidValueArray's lastObject()
081  set ocidItemValue to (ocidItemValue's stringByReplacingOccurrencesOfString:(" ") withString:(""))
082  set ocidItemValue to (ocidItemValue's stringByReplacingOccurrencesOfString:("\n") withString:(""))
083  (ocidItemDict's setObject:(ocidItemValue) forKey:("MD5"))
084  #sha256sum
085  set argCommandText to ("/sbin/sha256sum \"" & strItemFilePath & "\"") as text
086  set strValue to doExecTask(argCommandText)
087  set ocidValueStr to (refMe's NSString's stringWithString:(strValue))
088  set ocidValueArray to (ocidValueStr's componentsSeparatedByString:(" "))
089  set ocidItemValue to ocidValueArray's firstObject()
090  set ocidItemValue to (ocidItemValue's stringByReplacingOccurrencesOfString:("\n") withString:(""))
091  (ocidItemDict's setObject:(ocidItemValue) forKey:("SHA256"))
092  #取得した情報を出力用のDICTに格納 キーはファイル名
093  (ocidResultDict's setObject:(ocidItemDict) forKey:(ocidFileName))
094end repeat
095
096################## 
097#HTML生成開始
098set ocidXMLDoc to refMe's NSXMLDocument's alloc()'s init()
099ocidXMLDoc's setDocumentContentKind:(refMe's NSXMLDocumentHTMLKind)
100set ocidDTD to refMe's NSXMLDTD's alloc()'s init()
101ocidDTD's setName:("html")
102ocidXMLDoc's setDTD:(ocidDTD)
103set ocidRootElement to refMe's NSXMLElement's elementWithName:("html")
104set ocidAddNode to refMe's NSXMLNode's attributeWithName:("lang") stringValue:("ja")
105ocidRootElement's addAttribute:(ocidAddNode)
106#head
107set ocidHeadElement to refMe's NSXMLElement's elementWithName:("head")
108set ocidAddElement to refMe's NSXMLElement's elementWithName:("title")
109ocidAddElement's setStringValue:("ファイル比較")
110ocidHeadElement's addChild:(ocidAddElement)
111set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
112set ocidAddNode to refMe's NSXMLNode's attributeWithName:("name") stringValue:("viewport")
113ocidAddElement's addAttribute:(ocidAddNode)
114set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("width=720")
115ocidAddElement's addAttribute:(ocidAddNode)
116ocidHeadElement's addChild:(ocidAddElement)
117set ocidAddElement to refMe's NSXMLElement's elementWithName:("style")
118ocidAddElement's setStringValue:("body { margin: 10px; background-color: #FFFFFF; } table { border-spacing: 0; caption-side: top; font-family: system-ui; } thead th { border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; &:first-of-type { border-start-start-radius: .5em } &:last-of-type { border-start-end-radius: .5em; border-inline-end-width: 1px } } tbody td { word-wrap: anywhere;word-break: break-all;max-width: 360px;border-spacing: 0; border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; &:last-of-type { border-inline-end-width: 1px } } tbody th { border-spacing: 0; border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; } tbody tr:nth-of-type(odd) { background: #F2F2F2; } .kind_string { font-size: 0.75em; } .date_string { font-size: 0.5em; } .tbody_th_title{text-align: left;} tfoot th { border: solid 1px #666666; padding: .5ch 1ch; &:first-of-type { border-end-start-radius: .5em } &:last-of-type { border-end-end-radius: .5em; border-inline-end-width: 1px } }")
119ocidHeadElement's addChild:(ocidAddElement)
120ocidRootElement's addChild:(ocidHeadElement)
121#body
122set ocidBodyElement to refMe's NSXMLElement's elementWithName:("body")
123################## 
124#ヘッダー
125set ocidHeaderElement to refMe's NSXMLElement's elementWithName:("header")
126set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("header")
127ocidHeaderElement's addAttribute:(ocidAddNode)
128set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_header")
129ocidHeaderElement's addAttribute:(ocidAddNode)
130set ocidSetHeaderElement to (refMe's NSXMLElement's elementWithName:("div"))
131set ocidH3Element to (refMe's NSXMLElement's elementWithName:("h3"))
132(ocidH3Element's setStringValue:("ファイル比較v1"))
133(ocidSetHeaderElement's addChild:(ocidH3Element))
134ocidHeaderElement's addChild:(ocidSetHeaderElement)
135ocidBodyElement's addChild:(ocidHeaderElement)
136
137
138################## 
139#アーティクル
140set ocidArticleElement to refMe's NSXMLElement's elementWithName:("article")
141set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("article")
142ocidArticleElement's addAttribute:(ocidAddNode)
143set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_article")
144ocidArticleElement's addAttribute:(ocidAddNode)
145################## 
146#テーブル開始
147#【table】
148set ocidTableElement to (refMe's NSXMLElement's elementWithName:("table"))
149#【caption】
150set ocidCaptionElement to (refMe's NSXMLElement's elementWithName:("caption"))
151(ocidCaptionElement's setStringValue:("内容が同じでも修正が入っているなら相違となります"))
152(ocidTableElement's addChild:(ocidCaptionElement))
153#【colgroup】
154set beginning of listKey to "項目名"
155set numCntCol to (count of listKey) as integer
156set ocidColgroupElement to (refMe's NSXMLElement's elementWithName:("colgroup"))
157repeat with itemNo from 1 to numCntCol by 1
158  set strItemName to (item itemNo of listKey) as text
159  #【col】col生成
160  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("col"))
161  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(strItemName))
162  (ocidAddElement's addAttribute:(ocidAddNode))
163  (ocidColgroupElement's addChild:(ocidAddElement))
164end repeat
165#テーブルエレメントに追加
166(ocidTableElement's addChild:(ocidColgroupElement))
167#【thead】
168set ocidTheadElement to (refMe's NSXMLElement's elementWithName:("thead"))
169set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
170repeat with itemNo from 1 to numCntCol by 1
171  set strItemName to (item itemNo of listKey) as text
172  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("th"))
173  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(strItemName))
174  (ocidAddElement's addAttribute:(ocidAddNode))
175  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("col"))
176  (ocidAddElement's addAttribute:(ocidAddNode))
177  (ocidAddElement's setStringValue:(strItemName))
178  (ocidTrElement's addChild:(ocidAddElement))
179end repeat
180(ocidTheadElement's addChild:(ocidTrElement))
181(ocidTableElement's addChild:(ocidTheadElement))
182#【tbody】
183set ocidTbodyElement to refMe's NSXMLElement's elementWithName:("tbody")
184set listKey to (items 2 thru -1 of listKey) as list
185set numCntCol to (count of listKey) as integer
186#TR 1
187set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
188set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("row"))
189(ocidTrElement's addAttribute:(ocidAddNode))
190set ocidTdElement to (refMe's NSXMLElement's elementWithName:("th"))
191set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("項目名"))
192(ocidTdElement's addAttribute:(ocidAddNode))
193(ocidTdElement's setStringValue:("ファイルパス"))
194(ocidTrElement's addChild:(ocidTdElement))
195repeat with itemNo from 1 to numCntCol by 1
196  set strItemName to (item itemNo of listKey) as text
197  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("td"))
198  set itemDict to (ocidResultDict's objectForKey:(strItemName))
199  set itemValue to (itemDict's valueForKey:("PATH"))
200  (ocidAddElement's setStringValue:(itemValue))
201  (ocidTrElement's addChild:(ocidAddElement))
202end repeat
203(ocidTbodyElement's addChild:(ocidTrElement))
204#TR 2
205set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
206set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("row"))
207(ocidTrElement's addAttribute:(ocidAddNode))
208set ocidTdElement to (refMe's NSXMLElement's elementWithName:("th"))
209set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("項目名"))
210(ocidTdElement's addAttribute:(ocidAddNode))
211(ocidTdElement's setStringValue:("リンク"))
212(ocidTrElement's addChild:(ocidTdElement))
213repeat with itemNo from 1 to numCntCol by 1
214  set strItemName to (item itemNo of listKey) as text
215  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("td"))
216  set itemDict to (ocidResultDict's objectForKey:(strItemName))
217  set itemValue to (itemDict's valueForKey:("URL"))
218  set strLinkPathURL to itemValue's absoluteString() as text
219  set ocidAElement to (refMe's NSXMLElement's elementWithName:("a"))
220  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("href") stringValue:(strLinkPathURL))
221  (ocidAElement's addAttribute:(ocidAddNode))
222  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("target") stringValue:("_blank"))
223  (ocidAElement's addAttribute:(ocidAddNode))
224  (ocidAElement's setStringValue:("LINK"))
225  (ocidAddElement's addChild:(ocidAElement))
226  (ocidTrElement's addChild:(ocidAddElement))
227end repeat
228(ocidTbodyElement's addChild:(ocidTrElement))
229#TR 3
230set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
231set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("row"))
232(ocidTrElement's addAttribute:(ocidAddNode))
233set ocidTdElement to (refMe's NSXMLElement's elementWithName:("th"))
234set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("項目名"))
235(ocidTdElement's addAttribute:(ocidAddNode))
236(ocidTdElement's setStringValue:("ファイルサイズ"))
237(ocidTrElement's addChild:(ocidTdElement))
238repeat with itemNo from 1 to numCntCol by 1
239  set strItemName to (item itemNo of listKey) as text
240  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("td"))
241  set itemDict to (ocidResultDict's objectForKey:(strItemName))
242  set itemValue to (itemDict's valueForKey:("SIZE"))
243  set strValue to itemValue as text
244  (ocidAddElement's setStringValue:(strValue))
245  (ocidTrElement's addChild:(ocidAddElement))
246end repeat
247(ocidTbodyElement's addChild:(ocidTrElement))
248#TR 4
249set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
250set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("row"))
251(ocidTrElement's addAttribute:(ocidAddNode))
252set ocidTdElement to (refMe's NSXMLElement's elementWithName:("th"))
253set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("項目名"))
254(ocidTdElement's addAttribute:(ocidAddNode))
255(ocidTdElement's setStringValue:("作成日"))
256(ocidTrElement's addChild:(ocidTdElement))
257repeat with itemNo from 1 to numCntCol by 1
258  set strItemName to (item itemNo of listKey) as text
259  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("td"))
260  set itemDict to (ocidResultDict's objectForKey:(strItemName))
261  set itemValue to (itemDict's valueForKey:("CreDate"))
262  set strValue to itemValue as date
263  (ocidAddElement's setStringValue:(strValue))
264  (ocidTrElement's addChild:(ocidAddElement))
265end repeat
266(ocidTbodyElement's addChild:(ocidTrElement))
267#TR 5
268set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
269set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("row"))
270(ocidTrElement's addAttribute:(ocidAddNode))
271set ocidTdElement to (refMe's NSXMLElement's elementWithName:("th"))
272set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("項目名"))
273(ocidTdElement's addAttribute:(ocidAddNode))
274(ocidTdElement's setStringValue:("修正日"))
275(ocidTrElement's addChild:(ocidTdElement))
276#
277set ocidCompareArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
278repeat with itemNo from 1 to numCntCol by 1
279  set strItemName to (item itemNo of listKey) as text
280  set itemDict to (ocidResultDict's objectForKey:(strItemName))
281  set itemValue to (itemDict's valueForKey:("ModDate"))
282  (ocidCompareArray's addObject:(itemValue))
283end repeat
284set ocidFirstItem to ocidCompareArray's firstObject()
285set boolCompare to missing value
286repeat with itemArray in ocidCompareArray
287  set boolEqual to (ocidFirstItem's isEqualToDate:(itemArray)) as boolean
288  if boolEqual is false then
289    set boolCompare to false as boolean
290    exit repeat
291  end if
292end repeat
293#
294set ocidNewerDate to ocidCompareArray's valueForKeyPath:("@max.self")
295#
296repeat with itemNo from 1 to numCntCol by 1
297  set strItemName to (item itemNo of listKey) as text
298  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("td"))
299  set itemDict to (ocidResultDict's objectForKey:(strItemName))
300  set itemValue to (itemDict's valueForKey:("ModDate"))
301  set boolSameDate to (ocidNewerDate's isEqualToDate:(itemValue)) as boolean
302  if boolCompare is false then
303    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("style") stringValue:("font-weight: bold;"))
304    (ocidAddElement's addAttribute:(ocidAddNode))
305    if boolSameDate is true then
306      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("style") stringValue:("color: blue;font-weight: bold;"))
307      (ocidAddElement's addAttribute:(ocidAddNode))
308    end if
309  end if
310  
311  set strValue to itemValue as date
312  (ocidAddElement's setStringValue:(strValue))
313  (ocidTrElement's addChild:(ocidAddElement))
314end repeat
315(ocidTbodyElement's addChild:(ocidTrElement))
316#TR 6
317set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
318set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("row"))
319(ocidTrElement's addAttribute:(ocidAddNode))
320set ocidTdElement to (refMe's NSXMLElement's elementWithName:("th"))
321set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("項目名"))
322(ocidTdElement's addAttribute:(ocidAddNode))
323(ocidTdElement's setStringValue:("HASH MD5"))
324(ocidTrElement's addChild:(ocidTdElement))
325#
326set ocidCompareArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
327repeat with itemNo from 1 to numCntCol by 1
328  set strItemName to (item itemNo of listKey) as text
329  set itemDict to (ocidResultDict's objectForKey:(strItemName))
330  set itemValue to (itemDict's valueForKey:("MD5"))
331  (ocidCompareArray's addObject:(itemValue))
332end repeat
333set ocidFirstItem to ocidCompareArray's firstObject()
334set boolCompare to missing value
335repeat with itemArray in ocidCompareArray
336  set boolEqual to (ocidFirstItem's isEqualToString:(itemArray)) as boolean
337  if boolEqual is false then
338    set boolCompare to false as boolean
339    exit repeat
340  end if
341end repeat
342
343repeat with itemNo from 1 to numCntCol by 1
344  set strItemName to (item itemNo of listKey) as text
345  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("td"))
346  if boolCompare is false then
347    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("style") stringValue:("color: red;"))
348    (ocidAddElement's addAttribute:(ocidAddNode))
349  end if
350  set itemDict to (ocidResultDict's objectForKey:(strItemName))
351  set itemValue to (itemDict's valueForKey:("SHA256"))
352  set strValue to itemValue as text
353  (ocidAddElement's setStringValue:(strValue))
354  (ocidTrElement's addChild:(ocidAddElement))
355end repeat
356(ocidTbodyElement's addChild:(ocidTrElement))
357
358#TR 7
359set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
360set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("row"))
361(ocidTrElement's addAttribute:(ocidAddNode))
362set ocidTdElement to (refMe's NSXMLElement's elementWithName:("th"))
363set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("項目名"))
364(ocidTdElement's addAttribute:(ocidAddNode))
365(ocidTdElement's setStringValue:("HASH SHA256"))
366(ocidTrElement's addChild:(ocidTdElement))
367#
368set ocidCompareArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
369repeat with itemNo from 1 to numCntCol by 1
370  set strItemName to (item itemNo of listKey) as text
371  set itemDict to (ocidResultDict's objectForKey:(strItemName))
372  set itemValue to (itemDict's valueForKey:("SHA256"))
373  (ocidCompareArray's addObject:(itemValue))
374end repeat
375set ocidFirstItem to ocidCompareArray's firstObject()
376set boolCompare to missing value
377repeat with itemArray in ocidCompareArray
378  set boolEqual to (ocidFirstItem's isEqualToString:(itemArray)) as boolean
379  if boolEqual is false then
380    set boolCompare to false as boolean
381    exit repeat
382  end if
383end repeat
384
385repeat with itemNo from 1 to numCntCol by 1
386  set strItemName to (item itemNo of listKey) as text
387  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("td"))
388  if boolCompare is false then
389    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("style") stringValue:("color: red;"))
390    (ocidAddElement's addAttribute:(ocidAddNode))
391  end if
392  set itemDict to (ocidResultDict's objectForKey:(strItemName))
393  set itemValue to (itemDict's valueForKey:("MD5"))
394  set strValue to itemValue as text
395  (ocidAddElement's setStringValue:(strValue))
396  (ocidTrElement's addChild:(ocidAddElement))
397end repeat
398(ocidTbodyElement's addChild:(ocidTrElement))
399
400
401
402(ocidTableElement's addChild:(ocidTbodyElement))
403#【tfoot】
404set ocidTfootElement to (refMe's NSXMLElement's elementWithName:("tfoot"))
405set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
406set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
407set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("テーブルの終わり"))
408(ocidThElement's addAttribute:(ocidAddNode))
409set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("colspan") stringValue:(numCntCol + 1))
410(ocidThElement's addAttribute:(ocidAddNode))
411set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("row"))
412(ocidThElement's addAttribute:(ocidAddNode))
413(ocidThElement's setStringValue:("ファイルの比較結果です"))
414(ocidTrElement's addChild:(ocidThElement))
415(ocidTfootElement's addChild:(ocidTrElement))
416(ocidTableElement's addChild:(ocidTfootElement))
417#
418ocidArticleElement's addChild:(ocidTableElement)
419ocidBodyElement's addChild:(ocidArticleElement)
420
421################## 
422#フッター
423set ocidFooterElement to refMe's NSXMLElement's elementWithName:("footer")
424set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("footer")
425ocidFooterElement's addAttribute:(ocidAddNode)
426set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_footer")
427ocidFooterElement's addAttribute:(ocidAddNode)
428set ocidSetFooterElement to (refMe's NSXMLElement's elementWithName:("div"))
429set ocidAElement to (refMe's NSXMLElement's elementWithName:("a"))
430set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("href") stringValue:("https://quicktimer.cocolog-nifty.com/"))
431(ocidAElement's addAttribute:(ocidAddNode))
432set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("target") stringValue:("_blank"))
433(ocidAElement's addAttribute:(ocidAddNode))
434set strContents to ("AppleScriptで生成しました") as text
435(ocidAElement's setStringValue:(strContents))
436(ocidSetFooterElement's addChild:(ocidAElement))
437ocidFooterElement's addChild:(ocidSetFooterElement)
438ocidBodyElement's addChild:(ocidFooterElement)
439
440
441################## 
442#保存先
443set appFileManager to refMe's NSFileManager's defaultManager()
444set ocidTempDirURL to appFileManager's temporaryDirectory()
445set ocidUUID to refMe's NSUUID's alloc()'s init()
446set ocidUUIDString to ocidUUID's UUIDString
447set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:true
448set appFileManager to refMe's NSFileManager's defaultManager()
449set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
450ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
451set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference)
452set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:("index.html") isDirectory:false
453
454################## 
455#保存
456#ボディをROOTエレメントにセット
457ocidRootElement's addChild:(ocidBodyElement)
458ocidXMLDoc's setRootElement:(ocidRootElement)
459#
460set ocidXMLdata to (ocidXMLDoc's XMLDataWithOptions:(refMe's NSXMLNodePrettyPrint))
461set listDone to (ocidXMLdata's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error| :(reference))
462set aliasSaveFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias
463
464####ブラウザで開く
465tell application "Finder"
466  open location aliasSaveFilePath
467end tell
468
469return "処理終了"
470
471
472
473
474
475################## 
476#コマンド実行
477to doExecTask(argCommandText)
478  #
479  set ocidComString to refMe's NSString's stringWithString:(argCommandText)
480  #
481  set appFileManager to refMe's NSFileManager's defaultManager()
482  set ocidTempDirURL to appFileManager's temporaryDirectory()
483  set ocidTermTask to refMe's NSTask's alloc()'s init()
484  ocidTermTask's setLaunchPath:("/bin/zsh")
485  set ocidArgumentsArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
486  ocidArgumentsArray's addObject:("-c")
487  ocidArgumentsArray's addObject:(ocidComString)
488  ocidTermTask's setArguments:(ocidArgumentsArray)
489  set ocidOutPut to refMe's NSPipe's pipe()
490  set ocidError to refMe's NSPipe's pipe()
491  ocidTermTask's setStandardOutput:(ocidOutPut)
492  ocidTermTask's setStandardError:(ocidError)
493  ocidTermTask's setCurrentDirectoryURL:(ocidTempDirURL)
494  set listDoneReturn to ocidTermTask's launchAndReturnError:(reference)
495  if (item 1 of listDoneReturn) is (false) then
496    log "エラーコード:" & (item 2 of listDoneReturn)'s code() as text
497    log "エラードメイン:" & (item 2 of listDoneReturn)'s domain() as text
498    log "Description:" & (item 2 of listDoneReturn)'s localizedDescription() as text
499    log "FailureReason:" & (item 2 of listDoneReturn)'s localizedFailureReason() as text
500  end if
501  ##################
502  #終了待ち
503  ocidTermTask's waitUntilExit()
504  
505  ##################
506  #標準出力をログに
507  set ocidOutPutData to ocidOutPut's fileHandleForReading()
508  set listResponse to ocidOutPutData's readDataToEndOfFileAndReturnError:(reference)
509  set ocidStdOut to (item 1 of listResponse)
510  set ocidStdOut to refMe's NSString's alloc()'s initWithData:(ocidStdOut) encoding:(refMe's NSUTF8StringEncoding)
511  ##これが戻り値
512  return ocidStdOut as text
513  
514end doExecTask
AppleScriptで生成しました

|

[Finder]選択中のファイル・フォルダの指定場所への移動(上書きせずにリネームして移動)


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# com.cocolog-nifty.quicktimer.icefloe
004#
005#  同名ファイルがあった場合
006#  ファイル名やフォルダ名を置換することで上書きしません
007#
008----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
009use AppleScript version "2.8"
010use scripting additions
011
012#フォルダ名
013set strBaseDistFolderName to "パーツフォルダ"
014#日付の取得
015set numDay to day of (current date) as number
016set numMon to month of (current date) as number
017set numYer to year of (current date) as number
018#日付入りフォルダ名
019set strFolderName to (strBaseDistFolderName & "@" & numYer & "-" & numMon & "-" & numDay) as text
020
021#ファイルなりフォルダなりを選択する
022tell application "Finder"
023  activate
024  set listAliasPath to selection
025end tell
026
027#宛先フォルダを確定させる
028set aliasDesktopDirPath to (path to desktop folder from user domain) as alias
029#フォルダの有無チェック
030tell application "Finder"
031  set boolFolderChk to (exists of (folder strFolderName of folder aliasDesktopDirPath)) as boolean
032  if boolFolderChk is false then
033    make new folder at aliasDesktopDirPath with properties {name:strFolderName}
034  end if
035  set aliasDistDirPath to (folder strFolderName of folder aliasDesktopDirPath) as alias
036end tell
037#
038tell application "Finder"
039  repeat with itemAliasPath in listAliasPath
040    #エイリアスで確定
041    set aliasPath to itemAliasPath as alias
042    #プロパティのレコードを取得して
043    set recordProperties to properties of aliasPath
044    #クラスを取得
045    set classPath to class of recordProperties
046    ##フォルダの場合
047    if classPath is folder then
048      #元のフォルダ名
049      set strBaseDirName to name of aliasPath as text
050      #移動時のフォルダ名
051      set strSetDirName to strBaseDirName as text
052      #同名フォルダがあった場合のカウンタ
053      set numCntNo to 1 as integer
054      #移動するフォルダの上位の親フォルダ
055      set aliasContainerDirPath to (container of aliasPath) as alias
056      #最大100まで同名フォルダ処理を行う
057      repeat 100 times
058        #同名フォルダの有無チェック
059        set booDistChk to (exists of (folder strSetDirName of folder aliasDistDirPath)) as boolean
060        #無ければそのまま移動する
061        if booDistChk is false then
062          exit repeat
063        else
064          #同名のフォルダがある場合は数字を付与していく
065          set strSetDirName to (strBaseDirName & " " & numCntNo) as text
066          #フォルダ名を変更して
067          tell folder aliasPath
068            set name to strSetDirName
069          end tell
070          #変更後のフォルダパス
071          set aliasPath to (folder strSetDirName of folder aliasContainerDirPath) as alias
072        end if
073        #カウントアップ
074        set numCntNo to numCntNo + 1 as integer
075      end repeat
076      #同名でなくなったら移動
077      move aliasPath to aliasDistDirPath
078    else
079      #フォルダでないならファイルだから
080      #元のファイル名
081      set strOrgFileName to name of aliasPath as text
082      #カンマでリストにして
083      set strDelim to AppleScript's text item delimiters
084      set AppleScript's text item delimiters to "."
085      set listFileName to every text item of strOrgFileName
086      set AppleScript's text item delimiters to strDelim
087      set numCntList to (count of listFileName) as integer
088      if numCntList = 1 then
089        set boolNoExtension to true as boolean
090        #拡張子無しファイル
091        set strExtension to ("") as text
092        set strBaseFileName to (listFileName) as list
093        #移動時のファイル名
094        set strSetFileName to (strBaseFileName & strExtension) as text
095      else
096        set boolNoExtension to false as boolean
097        #拡張子を取得して
098        set strExtension to (last item of listFileName) as text
099        #最後の項目を削除
100        set listBaseFileName to (items 1 thru -2 of listFileName) as list
101        #残りの項目をカンマで繋いでベースファイル名      
102        #ファイル名リストの数を数える
103        set numCntList to (count of listBaseFileName) as integer
104        #リストの結合
105        repeat with itemNo from 1 to (numCntList) by 1
106          set itemBaseFileName to (item itemNo of listBaseFileName) as text
107          if itemNo = 1 then
108            set strBaseFileName to (itemBaseFileName) as text
109          else
110            set strBaseFileName to (strBaseFileName & "." & itemBaseFileName) as text
111          end if
112        end repeat
113        #移動時のファイル名
114        set strSetFileName to (strBaseFileName & "." & strExtension) as text
115      end if
116      
117      
118      #同名ファイルがあった場合のカウンタ
119      set numCntNo to 1 as integer
120      #移動するフォルダの上位の親フォルダ
121      set aliasContainerDirPath to (container of aliasPath) as alias
122      #最大100まで同名フォルダ処理を行う
123      repeat 100 times
124        #同名フォルダの有無チェック
125        set booFileChk to (exists of (file strSetFileName of folder aliasDistDirPath)) as boolean
126        #無ければそのまま移動する
127        if booFileChk is false then
128          exit repeat
129        else
130          if boolNoExtension is true then
131            #同名のフォルダがある場合は数字を付与していく
132            set strSetFileName to (strBaseFileName & " " & numCntNo) as text
133          else
134            #同名のフォルダがある場合は数字を付与していく
135            set strSetFileName to (strBaseFileName & " " & numCntNo & "." & strExtension) as text
136          end if
137          #フォルダ名を変更して
138          tell file aliasPath
139            set name to strSetFileName
140          end tell
141          #変更後のフォルダパス
142          set aliasPath to (file strSetFileName of folder aliasContainerDirPath) as alias
143        end if
144        #カウントアップ
145        set numCntNo to numCntNo + 1 as integer
146      end repeat
147      #同名でなくなったら移動
148      move aliasPath to aliasDistDirPath
149    end if
150  end repeat
151end tell
152
AppleScriptで生成しました

|

フォルダ判定

シンボリックリンク判定が不要なら FinderでOK
シンボリックリンクの判定が必要ならgetResourceValue

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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application


on run
  set aliasDefaultLocation to (path to desktop from user domain) as alias
  set strPromptText to "フォルダをえらんでください"
  set strMesText to "フォルダをえらんでください"
  try
    set listFolderPath to (choose folder strMesText with prompt strPromptText default location aliasDefaultLocation with multiple selections allowed, invisibles and showing package contents) as list
  on error
    log "エラーしました"
return "エラーしました"
  end try
open listFolderPath
end run


on open listFolderPath
  ####フォルダの数だけ繰り返し
  repeat with itemFolderPath in listFolderPath
    ######パス フォルダのエイリアス
    set aliasDirPath to itemFolderPath as alias
    ###UNIXパスにして
    set strDirPath to POSIX path of aliasDirPath as text
    ##############################
    ###フォルダ判定 A Finderを使う
    ##############################
    ###シンボリックリンクは判定出来ない(エイリアスのリンク先を参照する)
    ###エイリアス判定もするのでわりと堅実
    tell application "Finder"
      set strKind to (kind of aliasDirPath)
    end tell
    log strKind
    if strKind is not "フォルダ" then
return "処理対象はフォルダのみですA"
    end if
    ##############################
    ###フォルダ判定 B appFileManagerを使う
    ##############################
    ## エイリアス判定はしない(エイリアスのリンク先を参照する)
    ###ファイルマネジャー初期化
    set appFileManager to refMe's NSFileManager's defaultManager()
    set ocidFilePathStr to (refMe's NSString's stringWithString:(strDirPath))
    set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
    set boolDir to (appFileManager's fileExistsAtPath:(ocidFilePath) isDirectory:true)
    if boolDir is false then
return "処理対象はフォルダのみですB"
    end if
    ##############################
    ###フォルダ判定 C getResourceValueを使う
    ##############################
    ## エイリアス判定はしない(エイリアスのリンク先を参照する)
    set ocidFilePathStr to (refMe's NSString's stringWithString:(strDirPath))
    set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
    set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath)
    set listResult to (ocidFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLIsDirectoryKey) |error|:(reference))
    set boolIsDir to (item 2 of listResult) as boolean
    log boolIsDir
    if boolDir is false then
return "処理対象はフォルダのみですC"
    end if
    ##############################
    ###フォルダ判定 D getResourceValueを使う
    ##############################
    set ocidFilePathStr to (refMe's NSString's stringWithString:(strDirPath))
    set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
    set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath)
    set listResult to (ocidFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLIsAliasFileKey) |error|:(reference))
    set boolIsDir to (item 2 of listResult) as boolean
    log boolIsDir
    if boolIsDir is true then
return "処理対象はフォルダのみです(エイリアス判定)D"
    end if
    
    ##############################
    ###フォルダ判定 E getResourceValueを使う
    ##############################
    set ocidFilePathStr to (refMe's NSString's stringWithString:(strDirPath))
    set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
    set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:ocidFilePath)
    set listResult to (ocidFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLIsSymbolicLinkKey) |error|:(reference))
    set boolIsDir to (item 2 of listResult) as boolean
    log boolIsDir
    if boolIsDir is true then
return "処理対象はフォルダのみです(シンボリックリンク判定)E"
    end if
    
  end repeat
  
  
  
end open


|

[Basic]ファイルサイズの取得

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
#                       com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7

use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSURL : a reference to refMe's NSURL
set objFileManager to refMe's NSFileManager's defaultManager()



set ocidUserDesktopPath to (objFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set aliasDefaultLocation to ocidUserDesktopPath as alias

tell application "Finder"
    ##    set aliasDefaultLocation to container of (path to me) as alias
end tell

set listChooseFileUTI to {"public.mp3", "com.apple.m4a-audio"}

set strPromptText to "音楽ファイルを選んでください" as text

set aliasFilePath to (choose file with prompt strPromptText default location (aliasDefaultLocation) of type listChooseFileUTI with invisibles and showing package contents without multiple selections allowed) as alias
-->alias

###パス
set strFilePath to POSIX path of aliasFilePath
set ocidFilePathStr to refNSString's stringWithString:strFilePath
set ocidFilePath to ocidFilePathStr's stringByExpandingTildeInPath()
set ocidFilePathURL to refNSURL's alloc()'s initFileURLWithPath:ocidFilePath isDirectory:false

log doGetFileSize(ocidFilePathURL) as text


log doGetFileSizeFM(ocidFilePathURL) as text



###########################################
### ファイルサイズを読み取るサブ NSURL
###########################################

to doGetFileSize(argURL)
    
    try
        set strClassName to className() of argURL as text
    on error
        set strClassName to class of argURL
    end try
    
    if strClassName is "__NSCFString" then
        set ocidArgFilePath to argURL's stringByExpandingTildeInPath()
        set ocidArgFilePathURL to refNSURL's alloc()'s initFileURLWithPath:ocidArgFilePath
        
    else if strClassName is "NSPathStore2" then
        set ocidArgFilePathURL to refNSURL's alloc()'s initFileURLWithPath:argURL
        
    else if strClassName is "NSURL" then
        set ocidArgFilePathURL to argURL
        
    else if strClassName is alias then
        set strArgFilePath to POSIX path of argURL
        set ocidArgFilePathStr to refNSString's stringWithString:strArgFilePath
        set ocidArgFilePath to ocidArgFilePathStr's stringByExpandingTildeInPath()
        set ocidArgFilePathURL to refNSURL's alloc()'s initFileURLWithPath:ocidArgFilePath
        
    else if strClassName is text then
        set ocidArgFilePathStr to refNSString's stringWithString:argURL
        set ocidArgFilePath to ocidArgFilePathStr's stringByExpandingTildeInPath()
        set ocidArgFilePathURL to refNSURL's alloc()'s initFileURLWithPath:ocidArgFilePath
        
    end if
    ###
    set listResults to ocidArgFilePathURL's getResourceValue:(reference) forKey:(refMe's NSURLFileSizeKey) |error|:(reference)
    set strFileSize to (item 2 of listResults) as text
    
    return (strFileSize)
end doGetFileSize


###########################################
### ファイルサイズを読み取るサブ NSFileManager
###########################################

to doGetFileSizeFM(argURL)
    
    try
        set strClassName to className() of argURL as text
    on error
        set strClassName to class of argURL
    end try
    
    if strClassName is "__NSCFString" then
        set ocidArgFilePath to argURL's stringByExpandingTildeInPath()
        
    else if strClassName is "NSPathStore2" then
        set ocidArgFilePath to argURL
        
    else if strClassName is "NSURL" then
        set ocidArgFilePath to argURL's |path|()
        
    else if strClassName is alias then
        set strArgFilePath to POSIX path of argURL
        set ocidArgFilePathStr to refNSString's stringWithString:strArgFilePath
        set ocidArgFilePath to ocidArgFilePathStr's stringByExpandingTildeInPath()
        
    else if strClassName is text then
        set ocidArgFilePathStr to refNSString's stringWithString:argURL
        set ocidArgFilePath to ocidArgFilePathStr's stringByExpandingTildeInPath()
        
        
    end if
    set objFileManager to refMe's NSFileManager's alloc()'s init()
    
    set listAttribute to (objFileManager's attributesOfItemAtPath:ocidArgFilePath |error|:(reference))
    set ocidAttribute to (item 1 of listAttribute)
    
    set ocidFileSize to ocidAttribute's NSFileSize
    
    set strFileSize to ocidFileSize as text
    
    return (strFileSize)
end doGetFileSizeFM

|

[writeToURL]空のテキストファイルを作成する

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application
property refNSArray : a reference to refMe's NSArray
property refNSString : a reference to refMe's NSString
property refNSURL : a reference to refMe's NSURL
property refNSMutableString : a reference to refMe's NSMutableString


###デスクトップフォルダを求める
set ocidDeskTopDirArray to refMe's NSSearchPathForDirectoriesInDomains(refMe's NSDesktopDirectory, refMe's NSUserDomainMask, true)
log className() of ocidDeskTopDirArray as text
-->(*__NSSingleObjectArrayI*)
set strUserDesktopPath to (ocidDeskTopDirArray's objectAtIndex:0) as text
####ダイアログ用にエイリアス
set aliasUserDesktopPath to POSIX file strUserDesktopPath as alias
###ダイアログ用のテキスト
set strDefaultName to "名称未設定.txt" as text
set strPromptText to "名前を決めてください"
####ファイル名選択ダイアログ(ポイントは:as «class furl»
set aliasPath to (choose file name default location aliasUserDesktopPath default name strDefaultName with prompt strPromptText) as «class furl»
set strPath to POSIX path of aliasPath as text

#####ファイルマネージャー
set objFileManager to refMe's NSFileManager's defaultManager()
####パスを
set ocidNSString to refNSString's stringWithString:strPath
####NSURL
set ocidURLPath to refNSURL's fileURLWithPath:ocidNSString
#####書き込む空のテキスト
set ocidMutableString to refNSMutableString's alloc()'s initWithCapacity:0
####ファイルを書き込む
set boolFileWrite to (ocidMutableString's writeToURL:ocidURLPath atomically:false encoding:(refMe's NSUTF8StringEncoding) |error|:(reference))


|

[stringWithContentsOfURL]テキストファイル読込(テキスト内容がコマンド)

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions


property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSMutableArray : a reference to refMe's NSMutableArray
property refNSURL : a reference to refMe's NSURL
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807



####ダイアログで使うデフォルトロケーション
tell application "Finder"
set aliasDefaultLocation to (path to desktop folder from user domain) as alias
end tell
####UTIリスト
set listUTI to {"public.text"}
####ダイアログを出す
set aliasReadFilePath to (choose file with prompt "ファイルを選んでください" default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias

set strReadFilePath to POSIX path of aliasReadFilePath
####ドキュメントのパスをNSString
set ocidReadFilePath to refNSString's stringWithString:strReadFilePath
####ドキュメントのパスをNSURL
set ocidReadFilePathURL to refNSURL's fileURLWithPath:ocidReadFilePath
################
###ファイルの読み込み(結果はリスト形式で戻る)
set listReadDataString to refNSString's stringWithContentsOfURL:ocidReadFilePathURL usedEncoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
###読み込みデータは『ocidReadTextContents』に入る
set ocidReadTextContents to item 1 of listReadDataString
###エラー内容を見る場合
set ocidNSErrorData to item 2 of listReadDataString
if ocidNSErrorData is not (missing value) then
doGetErrorData(ocidNSErrorData)
end if

#######可変Arrayを初期化して準備
set ocidReadData to refNSMutableArray's alloc()'s initWithCapacity:0
#######改行を区切り文字に指定
set ocidNewlineCharacterSett to refMe's NSCharacterSet's newlineCharacterSet()
#######改行で区切りでArrayに格納
set ocidReadData to ocidReadTextContents's componentsSeparatedByCharactersInSet:ocidNewlineCharacterSett

################
####Arrayの回数だけ繰り返し
repeat with ocidDataItem in ocidReadData
log ocidDataItem as text
###各行にあるテキストをコマンドとして
set strLineText to ocidDataItem as text
####コマンド実行
if strLineText is not "" then
try
do shell script strLineText with administrator privileges
end try
end if

end repeat








to doGetErrorData(ocidNSErrorData)
#####個別のエラー情報
log "エラーコード:" & ocidNSErrorData's code() as text
log "エラードメイン:" & ocidNSErrorData's domain() as text
log "Description:" & ocidNSErrorData's localizedDescription() as text
log "FailureReason:" & ocidNSErrorData's localizedFailureReason() as text
log ocidNSErrorData's localizedRecoverySuggestion() as text
log ocidNSErrorData's localizedRecoveryOptions() as text
log ocidNSErrorData's recoveryAttempter() as text
log ocidNSErrorData's helpAnchor() as text
set ocidNSErrorUserInfo to ocidNSErrorData's userInfo()
set ocidAllValues to ocidNSErrorUserInfo's allValues() as list
set ocidAllKeys to ocidNSErrorUserInfo's allKeys() as list
repeat with ocidKeys in ocidAllKeys
if (ocidKeys as text) is "NSUnderlyingError" then
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedDescription() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedFailureReason() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedRecoverySuggestion() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedRecoveryOptions() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s recoveryAttempter() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s helpAnchor() as text
else
####それ以外の値はそのままテキストで読める
log (ocidKeys as text) & ": " & (ocidNSErrorUserInfo's valueForKey:ocidKeys) as text
end if
end repeat

end doGetErrorData

|

[stringWithContentsOfURL]テキストファイル読込

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSURL : a reference to refMe's NSURL
property refNSMutableArray : a reference to refMe's NSMutableArray

###################################
#######入力ファイル関連
####ダイアログで使うデフォルトロケーション
tell application "Finder"
set aliasDefaultLocation to (path to desktop folder from user domain) as alias
end tell
####UTIリスト
set listUTI to {"public.text"}
####ダイアログを出す
set aliasReadFilePath to (choose file with prompt "ファイルを選んでください" default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias

set strReadFilePath to POSIX path of aliasReadFilePath
####ドキュメントのパスをNSString
set ocidReadFilePath to refNSString's stringWithString:strReadFilePath
####ドキュメントのパスをNSURL
set ocidReadFilePathURL to refNSURL's fileURLWithPath:ocidReadFilePath
####ファイル名
set ocidFileName to ocidReadFilePathURL's lastPathComponent()
####拡張子名
set ocidFileExtensionName to ocidReadFilePathURL's pathExtension()
####コンテナ(ファイルのあるディレクトリ)
set ocidContainerDirURL to ocidReadFilePathURL's URLByDeletingLastPathComponent()


###################################
#######ファイルの読み込み(結果はリスト形式で戻る)
set listReadDataString to refNSString's stringWithContentsOfURL:ocidReadFilePathURL usedEncoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
###読み込みデータは『ocidReadTextContents』に入る
set ocidReadTextContents to item 1 of listReadDataString
###エラー内容を見る場合
set ocidNSError to item 2 of listReadDataString
if ocidNSError is not (missing value) then
doGetErrorData(ocidNSError)
end if

###################################
#######読み込んだテキストを改行区切りでリストにする
#######可変Arrayを初期化して準備
set ocidReadData to refNSMutableArray's alloc()'s initWithCapacity:0
#######改行を区切り文字に指定
set ocidNewlineCharacterSett to refMe's NSCharacterSet's newlineCharacterSet()
#######改行で区切りでArrayに格納
set ocidReadData to ocidReadTextContents's componentsSeparatedByCharactersInSet:ocidNewlineCharacterSett


###################################
#######Arrayの回数だけ繰り返し
repeat with ocidReadItem in ocidReadData
###各行にあるテキスト
log ocidReadItem as text



end repeat








to doGetErrorData(ocidNSErrorData)
#####個別のエラー情報
log "エラーコード:" & ocidNSErrorData's code() as text
log "エラードメイン:" & ocidNSErrorData's domain() as text
log "Description:" & ocidNSErrorData's localizedDescription() as text
log "FailureReason:" & ocidNSErrorData's localizedFailureReason() as text
log ocidNSErrorData's localizedRecoverySuggestion() as text
log ocidNSErrorData's localizedRecoveryOptions() as text
log ocidNSErrorData's recoveryAttempter() as text
log ocidNSErrorData's helpAnchor() as text
set ocidNSErrorUserInfo to ocidNSErrorData's userInfo()
set ocidAllValues to ocidNSErrorUserInfo's allValues() as list
set ocidAllKeys to ocidNSErrorUserInfo's allKeys() as list
repeat with ocidKeys in ocidAllKeys
if (ocidKeys as text) is "NSUnderlyingError" then
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedDescription() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedFailureReason() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedRecoverySuggestion() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedRecoveryOptions() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s recoveryAttempter() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s helpAnchor() as text
else
####それ以外の値はそのままテキストで読める
log (ocidKeys as text) & ": " & (ocidNSErrorUserInfo's valueForKey:ocidKeys) as text
end if
end repeat

end doGetErrorData

|

[NSDATA]ファイルダウンロード

テキストファイルにあるURLを順番にダウンロード

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions


property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSMutableArray : a reference to refMe's NSMutableArray
property refNSURL : a reference to refMe's NSURL
property refNSData : a reference to refMe's NSData

property refNSDate : a reference to refMe's NSDate
property refNSDateFormatter : a reference to NSDateFormatter
property refNSURLComponents : a reference to refMe's NSURLComponents
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807

set strBaseURL to ""

####ダイアログで使うデフォルトロケーション
tell application "Finder"
set aliasDefaultLocation to (path to desktop folder from user domain) as alias
end tell
####UTIリスト
set listUTI to {"public.text"}
####ダイアログを出す
set aliasReadFilePath to (choose file with prompt "ファイルを選んでください" default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias

set strReadFilePath to POSIX path of aliasReadFilePath
####ドキュメントのパスをNSString
set ocidReadFilePath to refNSString's stringWithString:strReadFilePath
####ドキュメントのパスをNSURL
set ocidReadFilePathURL to refNSURL's fileURLWithPath:ocidReadFilePath
################
######保存先
###日付時間をフォルダ名
set strDateAndTime to doGetDateNo("yyyyMMdd_hhmmss") as text
###フォルダ作成パス
set strSaveDirPath to ("~/Downloads/" & strDateAndTime & "") as text
###NSString
set ocidSaveDirPath to (refNSString's stringWithString:strSaveDirPath)
###フルパス
set ocidSaveDirFullPath to ocidSaveDirPath's stringByStandardizingPath
###NSURL
set ocidSaveDirFullPathURL to (refNSURL's alloc()'s initFileURLWithPath:ocidSaveDirFullPath)
###作るフォルダの属性
(*
###主要なモード NSFilePosixPermissions
777-->511
775-->509
770-->504
755-->493
750-->488
700-->448
555-->365
333-->219
#####NSFileGroupOwnerAccountID
ゲストのGID
201-->_guest
99-->_unknown
-2-->nobody
*)
###ファイルマネージャー初期化
set objFileManager to refMe's NSFileManager's defaultManager()
###保存先フォルダ作成
set boolMakeNewFolder to (objFileManager's createDirectoryAtURL:ocidSaveDirFullPathURL withIntermediateDirectories:true attributes:({NSFilePosixPermissions:511}) |error|:(reference))

################
###ファイルの読み込み(結果はリスト形式で戻る)
set listReadDataString to refNSString's stringWithContentsOfURL:ocidReadFilePathURL usedEncoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
###読み込みデータは『ocidReadTextContents』に入る
set ocidReadTextContents to item 1 of listReadDataString
#######可変Arrayを初期化して準備
set ocidReadData to refNSMutableArray's alloc()'s initWithCapacity:0
#######改行を区切り文字に指定
set ocidNewlineCharacterSett to refMe's NSCharacterSet's newlineCharacterSet()
#######改行で区切りでArrayに格納
set ocidReadData to ocidReadTextContents's componentsSeparatedByCharactersInSet:ocidNewlineCharacterSett

################
####Arrayの回数だけ繰り返し
repeat with ocidDataItem in ocidReadData
log ocidDataItem as text
###各行にあるテキストをURLとして
set ocidDownLoadURL to (refNSURL's URLWithString:ocidDataItem)
###ファイル名取得
set ocidFileName to ocidDownLoadURL's lastPathComponent() as text
###保存ファイルのURL
set ocidSaveFilePathURL to (ocidSaveDirFullPathURL's URLByAppendingPathComponent:ocidFileName)
log ocidSaveFilePathURL as text
###ファイルをダウンロード
set listDownLoadData to (refNSData's dataWithContentsOfURL:ocidDownLoadURL options:0 |error|:(reference))
set ocidDownLoadData to (item 1 of listDownLoadData)
try
log className() of (item 1 of listDownLoadData) as text
log item 2 of listDownLoadData
end try
###ファイル保存
set boolSaveFileDone to (ocidDownLoadData's writeToURL:ocidSaveFilePathURL atomically:true)
####リリースするとクラッシュする事があるので通常初期化
set ocidDownLoadURL to ""
set ocidDownLoadData to ""
end repeat


to doGetDateNo(strDateFormat)
####日付情報の取得
set ocidDate to current application's NSDate's |date|()
###日付のフォーマットを定義
set ocidNSDateFormatter to current application's NSDateFormatter's alloc()'s init()
ocidNSDateFormatter's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
ocidNSDateFormatter's setDateFormat:strDateFormat
set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:ocidDate
set strDateAndTime to ocidDateAndTime as text
return strDateAndTime
end doGetDateNo

|

[テキストデータ]テキスト・データの保存

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSURL : a reference to refMe's NSURL


set strTextData to "美しい日本語" as text
set ocidTextData to refNSString's stringWithString:strTextData

################
###ファイルパス
set strFilePath to "~/Desktop/read.txt"

set ocidRelativePath to refNSString's stringWithString:strFilePath
set ocidFullPath to ocidRelativePath's stringByStandardizingPath
set ocidSaveFilePathURL to refNSURL's alloc()'s initFileURLWithPath:ocidFullPath



##############
###ファイル書き込み
set listSaveFileDone to ocidTextData's writeToURL:ocidSaveFilePathURL atomically:true encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)

###読み込みデータは『ocidReadTextContents』に入る
set boolSaveFileDone to item 1 of listSaveFileDone

###エラー内容を見る場合
if boolSaveFileDone is false then
set ocidNSError to item 2 of listSaveFileDone
doGetDateNo(ocidNSError)
end if
to doGetDateNo(ocidNSErrorData)
#####個別のエラー情報
log "エラーコード:" & ocidNSErrorData's code() as text
log "エラードメイン:" & ocidNSErrorData's domain() as text
log "Description:" & ocidNSErrorData's localizedDescription() as text
log "FailureReason:" & ocidNSErrorData's localizedFailureReason() as text
log ocidNSErrorData's localizedRecoverySuggestion() as text
log ocidNSErrorData's localizedRecoveryOptions() as text
log ocidNSErrorData's recoveryAttempter() as text
log ocidNSErrorData's helpAnchor() as text
set ocidNSErrorUserInfo to ocidNSErrorData's userInfo()
set ocidAllValues to ocidNSErrorUserInfo's allValues() as list
set ocidAllKeys to ocidNSErrorUserInfo's allKeys() as list
repeat with ocidKeys in ocidAllKeys
if (ocidKeys as text) is "NSUnderlyingError" then
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedDescription() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedFailureReason() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedRecoverySuggestion() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedRecoveryOptions() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s recoveryAttempter() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s helpAnchor() as text
else
####それ以外の値はそのままテキストで読める
log (ocidKeys as text) & ": " & (ocidNSErrorUserInfo's valueForKey:ocidKeys) as text
end if
end repeat

end doGetDateNo

|

[テキストデータ]テキスト・ファイルの読み込み

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSURL : a reference to refMe's NSURL

################
###ファイルパス
set strFilePath to "~/Desktop/read.txt"

set ocidRelativePath to refNSString's stringWithString:strFilePath
set ocidFullPath to ocidRelativePath's stringByStandardizingPath
set ocidFilePathURL to refNSURL's alloc()'s initFileURLWithPath:ocidFullPath

set ocidFileName to ocidFilePathURL's lastPathComponent()
set ocidFileExtensionName to ocidFilePathURL's pathExtension()
set ocidContainerDirURL to ocidFilePathURL's URLByDeletingLastPathComponent()


################
###ファイルの読み込み(結果はリスト形式で戻る)
set listReadDataString to refNSString's stringWithContentsOfURL:ocidFilePathURL usedEncoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
###読み込みデータは『ocidReadTextContents』に入る
set ocidReadTextContents to item 1 of listReadDataString
###エラー内容を見る場合
set ocidNSError to item 2 of listReadDataString
if ocidNSError is not (missing value) then
doGetErrorData(ocidNSError)
end if



################
####Arrayの回数だけ繰り返し
repeat with ocidReadTextItem in ocidReadTextContents
log ocidReadTextItem as text
###各行にあるテキストをURLとして
set ocidDownLoadURL to (refNSURL's URLWithString:ocidReadTextItem)


end repeat








to doGetErrorData(ocidNSErrorData)
#####個別のエラー情報
log "エラーコード:" & ocidNSErrorData's code() as text
log "エラードメイン:" & ocidNSErrorData's domain() as text
log "Description:" & ocidNSErrorData's localizedDescription() as text
log "FailureReason:" & ocidNSErrorData's localizedFailureReason() as text
log ocidNSErrorData's localizedRecoverySuggestion() as text
log ocidNSErrorData's localizedRecoveryOptions() as text
log ocidNSErrorData's recoveryAttempter() as text
log ocidNSErrorData's helpAnchor() as text
set ocidNSErrorUserInfo to ocidNSErrorData's userInfo()
set ocidAllValues to ocidNSErrorUserInfo's allValues() as list
set ocidAllKeys to ocidNSErrorUserInfo's allKeys() as list
repeat with ocidKeys in ocidAllKeys
if (ocidKeys as text) is "NSUnderlyingError" then
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedDescription() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedFailureReason() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedRecoverySuggestion() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedRecoveryOptions() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s recoveryAttempter() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s helpAnchor() as text
else
####それ以外の値はそのままテキストで読める
log (ocidKeys as text) & ": " & (ocidNSErrorUserInfo's valueForKey:ocidKeys) as text
end if
end repeat

end doGetErrorData

|

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat AddOn Acrobat Annotation Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat JS Acrobat Manifest Acrobat Menu Acrobat Open Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat python Acrobat Reader Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin Support Admin System Information Admin Tools Admin Users Admin Volumes Adobe Adobe FDKO Adobe RemoteUpdateManager AppKit Apple AppleScript AppleScript do shell script AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript System Events AppleScript System Events Plist AppleScript Video Applications AppStore Archive Attributes Automator BackUp Barcode Barcode QR Barcode QR Decode Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome CIImage CityCode CloudStorage Color com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time delimiters Desktop Device Diff Disk Dock DropBox Droplet eMail Encode % Encode Decode Encode UTF8 Error EXIFData ffmpeg File Finder Firefox Folder FolderAction Fonts GIF github Guide HTML HTML Entity Icon Illustrator Image Events Image2PDF ImageOptim iPhone iWork Javascript Jedit Json Label Leading Zero List locationd LRC lsappinfo LSSharedFileList m3u8 Mail MakePDF Map Math Media Media AVAsset Media AVconvert Media AVFoundation Media AVURLAsset Media Movie Media Music Memo Messages Microsoft Microsoft Edge Microsoft Excel Mouse Music NetWork Notes NSArray NSArray Sort NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSColor NSColorList NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSPrintOperation NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth OneDrive PDF PDFAnnotation PDFAnnotationWidget PDFContext PDFDisplayBox PDFDocumentPermissions PDFImageRep PDFKit PDFnUP PDFOutline perl Photoshop PlistBuddy pluginkit postalcode PostScript prefPane Preview Python QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver SF Symbols character id SF Symbols Entity sips Skype Slack Sound Spotlight sqlite SRT StandardAdditions Swift System Settings TCC TemporaryItems Terminal Text Text CSV Text MD Text TSV TextEdit Tools Translate Trash Twitter Typography UI Unit Conversion UTType valueForKeyPath Video VisionKit Visual Studio Code Wacom webarchive webp Wifi Windows XML XML EPUB XML OPML XML Plist XML RSS XML savedSearch XML SVG XML TTML XML webloc XML XMP YouTube zoom