zoxide + tmux 세션 생성하기

RunFridge·2024년 6월 15일

cli-productivity

목록 보기
4/5
post-thumbnail

개념

설명을 시작하기에 앞서, zoxidetmux에 대해 간단하게 정리해보았다.

zoxide

Zoxide는 리포지토리의 한줄 설명으로 요약하자면 다음과 같은 기능을 수행하는 커맨드라인 툴이다.

zoxide is a smarter cd command, inspired by z and autojump.

Zoxide는 z와 autojump의 영감을 받아 개발된 똑똑한 cd 커맨드입니다.

It remembers which directories you use most frequently, so you can "jump" to them in just a few keystrokes.

자주 방문하는 디렉토리를 기억하여, 이후 약간의 키 입력만으로 "점프"할 수 있도록 도와줍니다.

zoxide demo

tmux

Tmux는 터미널 멀티플렉서이다. Tmux의 man페이지의 설명이다:

tmux is a terminal multiplexer: it enables a number of terminals to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background, then later reattached.

tmux는 터미널 멀티플렉서로서 단일 화면에서 여러 개의 터미널을 생성, 액세스 및 제어할 수 있습니다. tmux를 화면에서 분리하여 백그라운드에서 계속 실행한 다음 나중에 다시 연결할 수 있습니다.

zi

zoxide를 설치하게되고, zoxide init을 통하여 쉘 설정을 등록하게되면 zi 라는 쉘 함수가 생성이된다.

이를 터미널에서 확인해보면 다음과 같은 커맨드다.

$ which zi
zi () {
	__zoxide_zi "$@"
}

$ which __zoxide_zi
__zoxide_zi () {
	\builtin local result
    result="$(\command zoxide query --interactive -- "$@")" && __zoxide_cd "${result}"
}

부분적으로 분석해보면 result라는 변수를 선언하고 이에 zoxide query --interactive의 결과값을 저장후, zoxide의 기본기능을 사용하여 지정된 디렉토리로 이동한다.

Rust를 잘알지는 못하지만, 해당 커맨드를 실행해보고 코드를 확인해보면 fzf 인터랙티브 창을 열어 저장된 디렉토리 목록을 fuzzy search한다는 것을 알 수 있다!

fn query_interactive(&self, stream: &mut Stream, now: Epoch) -> Result<()> {
        let mut fzf = Self::get_fzf()?;
        let selection = loop {
            match stream.next() {
                Some(dir) if Some(dir.path.as_ref()) == self.exclude.as_deref() => continue,
                Some(dir) => {
                    if let Some(selection) = fzf.write(dir, now)? {
                        break selection;
                    }
                }
                None => break fzf.wait()?,
            }
        };

        if self.score {
            print!("{selection}");
        } else {
            let path = selection.get(7..).context("could not read selection from fzf")?;
            print!("{path}");
        }
        Ok(())
    }

그렇다면 이제 zi 커맨드를 연계하여 tmux 세션을 만드는 함수를 선언해보자!

zt

항상 함수/변수 이름 짓는게 고민이지만 zoxide와 tmux를 합쳐서 사용하기 때문에, 그리고 따로 시스템에 zt와 겹치는 커맨드가 없어서 이렇게 지어봤다.

# Zoxide & Tmux
function zt() {
    # 현재 세션이 Tmux인지 확인
    if [ -z "$TMUX" ]; then
        echo -e "\033[0;31mError: Not in a tmux session\033[0m"
        return 1
    fi
    # 로컬 결과 변수 선언
    \builtin local result
    # argument가 주어졌는지 확인
    if [ -z "$1" ]; then
    	# argument가 없으면 인터랙티브 fzf 세션 실행
        result=$(zoxide query --interactive)
    else
    	# argument가 있으면 argument 사용
        result=$(zoxide query --interactive $1)
    fi
    # Zoxide query가 실패한 경우 (exit != 0) 처리
    if [ $? -ne 0 ]; then
        return 1
    fi
    # 윈도우명을 디렉토리의 베이스 이름으로 사용
    window_name=$(basename $result)
    # 새로운 tmux 윈도우 생성
    tmux new-window -n $window_name -c $result
}

이제 tmux 세션 내부에서 zt 커맨드를 통하여 새로운 디렉토리로 윈도우를 빠르게 생성할 수 있게되었다.

0개의 댓글