0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Windows で Mac の絶対パス /Users/... を動かす: subst・ジャンクション・cwd の使い方

0
Posted at

背景

私は Mac と Windows の2台で同じリポジトリを回しています。
Mac で書いたスクリプトには /Users/hashito/git/... という絶対パスが何箇所も埋まっています。
Windows に持ってくると当然そのままでは動かなくて、毎回パスを書き換えるのも嫌でした。
そこで subst とジャンクションで「Windows 上に /Users/hashito を作る」ことにしました。

結論

先に実行結果を貼ります。
同じ node のワンライナーを、cwd(カレントディレクトリ)だけ変えて実行しました。

PS> Set-Location C:\Users\hasit
PS> node -e "console.log(require('path').resolve('/Users/x'))"
C:\Users\x

PS> Set-Location V:\
PS> node -e "console.log(require('path').resolve('/Users/x'))"
V:\Users\x

下記のとおり、C: にいると C:\Users\x になり、V: にいると V:\Users\x になります。
Windows の node は、先頭が / のパスを「今いるドライブの直下」として解決するだけです。
だから V: という仮想ドライブの下に Users\hashito を用意しておき、cwd を V: に置けば、Mac のパスがそのまま通ります。

仕組み

subst は、フォルダに別のドライブ文字を割り当てる Windows 標準のコマンドです。
今回は C:\Users\hasit.fleet-vroot という普通のフォルダを V: に割り当てています。

PS> subst V: C:\Users\hasit\.fleet-vroot
PS> subst
V:\: => C:\Users\hasit\.fleet-vroot

次にその中の Users\hashito\git の下へ、本物のリポジトリがある場所へのジャンクションを置きます。
ジャンクションは、あるフォルダを別の場所のフォルダとして見せるリンクです(管理者権限なしで作れるのが助かります)。
私の環境では次のようになっていました。

PS> Get-ChildItem V:\Users\hashito\git | Select Name,LinkType,Target

Name    LinkType Target
----    -------- ------
scripts Junction {C:\Users\hasit\git\scripts}
web     Junction {C:\Users\hasit\git\web}

作るときは New-Item -ItemType Junction -Path {リンクの場所} -Target {実体の場所} です。
{ } の中は自分の環境の値に置き換えてください。

cwd が V: でないと効かない理由

ここが一番ハマったところです。
cwd が V: の状態でスクリプトを起動すると、存在確認はこうなります。

PS> Set-Location V:\Users\hashito\git\scripts\web-fleet
PS> node -e "console.log(require('fs').existsSync('/Users/hashito/git/scripts/web-fleet/package.json'))"
true

PS> Set-Location C:\Users\hasit
PS> node -e "console.log(require('fs').existsSync('/Users/hashito/git/scripts/web-fleet/package.json'))"
false

入力が同じでも出力が変わる(true と false)理由はこうです。
C: にいると /Users/hashito/... C:\Users\hashito... として探されて、そんなフォルダは無いので false です。
つまり絶対パス側を直したのではなく、「どのドライブから見るか」を cwd で切り替えているだけです。
私の環境は PowerShell の cwd が呼び出しごとにリセットされるので、毎回 Set-Location V:... を先頭に置いています(地味に忘れます…)。

注意点

subst の割り当ては再起動で消えるので、起動時に subst を打ち直す仕組みが要ります。
また、同じファイルが V: 側と実体の C: 側の2通りの名前で見えます。
git のように「パスの文字列を比べる」ツールでは混乱のもとなので、どのツールをどちらの綴りで呼ぶかは決めておくほうが安全だと思います。

こうしたパス周りの運用をしながら、ブラウザで遊べる小さなツールも作っています。
気になった方はこちらです。
https://hashito.biz/tools/amidacuji/

Mac 用の絶対パスを書き換えたくないときは、subst とジャンクションで仮想ルートを作り、cwd をそのドライブに置けば動きます。


本記事はAI補助で執筆した、個人開発の紹介記事です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?