iTerm2下实现点击文件唤起IDE

· 1 min read

终端下光标移动到文件路径上,⌘+click可以触发执行某个命令,比如点击一个项目文件夹,触发WebStorm,但是有时我希望不同的文件类型,触发不同的动作,这样就需要自定义脚本进行拓展。

解决方案

实现方案如下,因为个人Shell渣渣,为了方便,实际打开IDElogic使用JS编写,只是在shell中执行nodejs

贴下部分代码,完整代码戳这里

iterm2-trigger.js

/**
 * 调试脚本 ./iterm2-trigger.sh '/git/chainmaker-go'
 * 设置各种文件的默认打开程序
 * key为条件,value为执行命令,缺省使用默认打开程序
 * 项目文件夹名称命中go词汇的,使用goland打开
 */
const commandMap = new Map();
commandMap.set((_filePath) => utils.isDirectory(_filePath) && utils.suffixMatch(10, _filePath, ['.go']), '/usr/local/bin/goland');
commandMap.set((_filePath) => utils.isDirectory(_filePath) && utils.suffixMatch(10, _filePath, ['.js', '.jsx', '.ts', '.tsx']), '/usr/local/bin/webstorm');
commandMap.set((_filePath) => true, 'open');

(function init() {
  let commandStr = '';
  for (const fn of commandMap.keys()) {
    if (fn(filePath)) {
      commandStr = commandMap.get(fn);
      if (utils.checkAppExist(commandStr)) {
        break;
      }
    }
  }
  execSync(`${commandStr} ${filePath}`);
})();

iterm2-trigger.sh

#!/usr/bin/env bash
DIR="$(dirname $0)"

/usr/local/bin/node "$DIR/iterm2-trigger.js" $1
exit 0;

iTerm2下进入Preferences=>Profiles=>local Profile=>Advanced=>Semantic History,配置如下

$HOME/bin/iterm2-trigger.sh \1

当然如果只想所有文件都走WebStorm或某程序打开,直接如下配置即可

/usr/local/bin/webstorm \1

写在最后

有了这个设定脚本,就可以灵活控制文件点击的动作了。