평소 백준 문제를 풀 때마다 VSCode로 hellocpp.cpp를 열고 이전에 풀었던 문제의 소스코드를 지우고 보일러플레이트 코드를 적는다. 항상 똑같은 보일러플레이트를 쓰는데, 매번 일일이 지웠다 쓰는 게 여간 귀찮은 일이 아니다.
VSCode에서 현재 열린 파일 내용을 boilerplate로 수동으로 수정하는 것이 번거롭다.
shell script와 tasks.json을 이용해 자동화한다.
cpp 소스 파일, exe 실행 파일, 그리고 .vscode
폴더에 tasks.json
이 있는 상태 (.vscode
폴더 내 tasks.json
이 없다면 만들어줄 것)
scripts
폴더 내에 boilerplate.sh
파일을 만들고 다음 내용을 붙여넣는다.
#!/bin/bash
# Check if the file path is provided as an argument
if [ $# -eq 0 ]; then
echo "Please provide the file path as an argument."
read -n 1
exit 1
fi
# Get the file path from the argument
file_path=$1
# Check if the file exists
if [ ! -f "$file_path" ]; then
echo "File does not exist."
exit 1
fi
# Reset the content of the file with the boilerplate
cat << EOF > "$file_path"
#define FASTIO ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr)
#include <iostream>
#include <vector>
using namespace std;
int main() {
FASTIO;
return 0;
}
EOF
tasks.json
에 붙여넣는다.{
"label": "Overwrite with Baekjoon C++ Boilerplate",
"type": "shell",
"command": "./scripts/boilerplate.sh ${file}",
"group": "test",
"presentation": {
"reveal": "always",
"panel": "new"
}
}
붙여넣은 후의 tasks.json
의 모습은 다음과 같을 것이다.
{
"version": "2.0.0",
"tasks": [
(... 기존 tasks ...)
{
"label": "Overwrite with Baekjoon C++ Boilerplate",
"type": "shell",
"command": "./scripts/boilerplate.sh ${file}",
"group": "test",
"presentation": {
"reveal": "always",
"panel": "new"
}
}
]
}
이전에 만든 boilerplate.sh
파일을 현재 열린 파일 경로를 매개변수로 넘겨주면서 실행한다.
이걸로 자동화 작업이 끝났다!
hellocpp.cpp
를 열고 Ctrl + Shift + P
를 눌러 Tasks: Run Task
커맨드를 선택한다.
방금 우리가 만든 task의 이름인 Overwrite with Baekjoon C++ Boilerplate
을 선택한다. (task 이름이 마음에 안 들면 tasks.json
으로 가서 label
값을 자유롭게 바꾸자)
.sh 파일을 실행하는 기본 프로그램을 선택하라는 창이 뜰 경우
Windows의 경우 task를 처음 실행할 때 .sh 파일을 실행할 기본 프로그램을 선택하는 창이 뜰 수 있다. 나는 이미 설치되어 있던 Git Bash를 선택해 주었다.
잘 된다!
문제를 해결하는 과정이 다음과 같은 것들을 학습하는 계기가 되었다.
task.json
이제 편하게 보일러플레이트로 리셋할 수 있다 :)