AppleScriptでMacの作業を自動化する

AppleScriptでMacの作業を自動化する

AppleScriptを使うと、いつも行う操作や処理などを自動化できるのでとても便利です。本記事ではAppleScriptを簡単に紹介します。

はじめに

AppleScriptとは、アップルが開発したmacOS用のオブジェクト指向のスクリプト言語で、システムや様々な対応アプリケーションを制御できます。

このAppleScriptを使うことで、いつも行う操作や処理などを自動化できます。

例えば。私はフリーランスで複数のプロジェクトに関わっています。当然、プロジェクトごとに環境は異なりますので、稼働日に応じて現在立ち上がってる環境を落として、新しい環境を立ち上げる、ということを繰り返してたのですが、これが毎回となると結構な手間です。

そこで、AppleScriptを使って、環境の切り替えを自動化しました。

上の動画では、AppleScriptで下記の作業を自動化してます。

  1. iTermを立ち上げて分割。一つはプロジェクトディレクトリに移動しdocker立ち上げ、一つはVS codeでプロジェクトディレクトリを開く
  2. chromeでローカルホストを開く(docker起動が終わる前なので最初はnot foundになる)
  3. Finderでプロジェクトディレクトリを開き、新規タブでプロジェクトの作業フォルダを開く
  4. Sourcetree立ち上げ

このようにAppleScriptを使うとMac上での作業を効率化できます。
この記事では初めてAppleScriptを使う方向けに、基本的な使い方とどのようなことができるのか紹介します。

エディタ

エディタには、Macにプリインストールされてるスクリプトエディタを使います。他のエディタでもAppleScriptは書けると思いますが、スクリプトエディタは直ぐにスクリプトを実行できたり、後述するアプリケーションの書き出し対応や、用語説明など一通りの機能が備わってるので、まずはこれを使うのが良いと思います。

また、Automatorを使うと、GUIで簡単にワークフローを作れますが、本記事では触れません。

基本コマンド

アプリケーションの選択

tell application "Google Chrome"
    <コマンド>
end tell

tell application "起動したいアプリケーション で、操作するアプリケーションを指定します。
telend tell の間に実行したいコマンドを書きます。

アプリケーションの起動

tell application "Google Chrome"
    activate
end tell

activate でアプリケーションを起動します。
同様に run でもアプリケーションを起動できます。

activaterun の違いは、 activate アプリケーションを起動してアクティブ(手前)にするのに対し、 run は起動するのみでアクティブにはしません。
参考:AppleScript でアプリケーションを起動・終了する \- ObjecTips

アプリケーションの終了

quit でアプリケーションを終了します

tell application "Google Chrome"
    quit
end tell

key入力

tell application "System Events" でSystem Eventsを選択して、keystrokekey code コマンドでkey入力を制御できます

スペースキーなど特殊なキーを入力したい場合は key code コマンドを使用します。

tell application "System Events"
    -- スペースキー入力
	key code 49
end tell

key code 一覧はこちらを参照ください。
Complete list of AppleScript key codes

コマンドやオプションなどの特殊キーと組み合わせる時は、 using <特殊キー> down と書きます。

-- コマンドキーを押しながらc(コピー)
keystroke "c" using command down
-- コントロールキー、シフトキーを押しながらスペース
key code 49 using {control down, shift down}

Finderを開き、新規タブを開く(「command + T」を入力する)スクリプトは下記のようになります。

tell application "Finder"
    activate
    tell application "System Events"
        keystroke "t" using command down
    end tell
end tell

主な構文

ダイアログ表示

display dialog でダイアログを表示します

display dialog "hello"

変数への代入

変数への代入は setを使用します。

set <変数名> to <値>
# sample
set greeting to "hello"
set thisYear to 2021
set isAnimal to true

if 文

if文は、 if 条件式 thenend if になります。
また、条件式の = は代入ではなく、等しいという意味の比較演算子になります。

if <条件式> then
    <命令>
else if <条件式> then
    <命令>
else 
    <命令>
end if

set animal to "dog"
if animal = "dog" then
	display dialog "犬"
else if animal = "cat" then
	display dialog "猫"
else
	display dialog "その他"
end if

コメント

行頭に -- を入れるとその行はコメントになり実行されません。

-- コメントです

アプリケーションとして書き出し

アプリケーションとして書き出すと、ダブルクリックでスクリプトを実行できます。

書き出し方法は、メニューの「ファイル」→「書き出す」を選択し、表示されるウインドウで「ファイルフォーマット」を「アプリケーション」に選択します。

System Eventsエラー

アプリケーションでSystem Eventsを利用する時は、最初に下記のようなエラーが表示されると思います。

System Eventsでエラーが起きました: スクリプトエディタにはキー操作の送信は許可されません

アラートで許可するを選択すれば、それ移行はエラーが表示されずに実行されます。
それでもエラーが表示されるようであれば、「システム環境設定」で「セキュリティとプライバシー」を選択し、「アクセシビリティ」でアプリを追加すると解決します。

各アプリケーションごとのコマンド

アプリケーションによっては、AppleScriptで特定のコマンドを実行できるものがあります。主に自分が利用したアプリケーションのコマンドを紹介します。

他のコマンドやアプリケーションを調べたい時はネットで検索いただくか、「ファイル」→「用語説明を開く」でアプリケーションを選択して確認もできます。

Finder

フォルダを開く

open folder <path> でフォルダを開きます。

-- デスクトップを開く
tell application "Finder"
	open folder "Macintosh HD:Users:taro:Desktop"
end tell

ファイルのパスは下記の書き方もできます。

open folder POSIX file "/Users/hiro/Desktop"

下記の記事も参考になります。

iTerm

iTermを操作する基本構文

iTermのアクティブなセッションで ls を実行する場合。

tell application "iTerm"
    activate
    set _current_session to current session of current tab of current window
    tell _current_session
        -- ここに操作したいことを書く
		write text "ls"
    end tell
end tell

別のセッションを選択

first, second, … last などでセッションを指定できます。

tell second session of current tab of current window
	write text "ls"
end tell

下記の記事も参考になります。

Chrome

選択

tell application "Google Chrome"
	...
end tell

新規ウインドウを開く

make new window

タブでURLオープン

tell window 1 to make new tab with properties {URL:"<https://design-spice.com>"}

URLオープン

ウインドウが0ならウインドウを開いてアクセス、ウインドウがあるなら新規タブで指定したURLを開きます。

open location '<http://xxx>'

リロード

reload active tab of window 1

作成したもの

ここまでの技術をもとに、実際に私が使ってるものを最後に共有します。オリジナルのAppleScript作成するときに参考にしてください。
※ 一部、私の環境に依存してるところもあるので、その辺は書き換えてます。

set theUrl to "http://localhost:3000"
-- 開発ディレクトリ
set theFolder1 to "Macintosh HD:Users:hiro:develop:hoge"
-- 関連ファイルなどを管理するディレクトリ
set theFolder2 to "Macintosh HD:Users:hiro:project:hoge"
tell application "Finder"
	activate
	close every window
	open folder theFolder1
	tell application "System Events"
		keystroke "t" using command down
		delay 1
		tell application "Finder" to set target of Finder window 1 to theFolder2
	end tell
end tell

tell application "iTerm"
	activate
	close current window
	if current window = missing value then
		create window with default profile
	end if
	set _path to "cd /Users/hiro/develop/hoge"
	set _current_session to current session of current window
	tell _current_session
		-- ここに操作したいことを書く
		split horizontally with default profile
		-- docker立ち上げ
		write text _path
		write text "docker-compose up"
	end tell
	tell last session of current tab of current window
		write text _path
		-- vscode立ち上げ
		write text "code ./ -r"
	end tell
end tell

tell application "Google Chrome"
	activate
	open location theUrl
end tell

tell application "Sourcetree" to run
B!

Comment

コメント(0)

コメントはまだありません。

コメントする

Trackback(0)