File size: 11,937 Bytes
da5a206 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 | # Copyright (c) 2022-2025, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""This script sets up the vs-code settings for this project.
This script merges the extraPaths from the "{ISAACSIM_DIR}/.vscode/settings.json" file into
the ".vscode/settings.json" file to enable code completion, go to definition, and other code navigation features
and a default python interpreter set to the isaac-sim python.sh script.
NOTE: This script is not specific to VSCode - it also supports Cursor.
"""
import os
import pathlib
import platform
import re
import sys
# Path to the the project directory
PROJECT_DIR = pathlib.Path(__file__).parents[2]
def get_isaacsim_dir() -> str:
"""Get the location of the Isaac Sim directory via the following methods:
1. Try to import isaacsim, and use __file__ to get the directory
2. If that fails, try to get the ISAAC_PATH environment variable
3. If that fails, return None
Returns:
The Isaac Sim directory if found, otherwise None.
"""
try:
import isaacsim
isaacsim_dir = pathlib.Path(isaacsim.__file__).parents[2]
print(f"Found Isaac Sim directory via importing isaacsim: {isaacsim_dir}")
except ModuleNotFoundError or ImportError:
isaacsim_dir = os.environ.get("ISAAC_PATH")
if isaacsim_dir is None:
print(
"ISAAC_PATH is not set. Please set the ISAAC_PATH environment variable to the root of your local Isaac"
" Sim installation / clone if you want to use python language server with Isaac Sim imports."
)
return None
if not os.path.exists(isaacsim_dir):
raise FileNotFoundError(
f"Could not find the isaac-sim directory: {isaacsim_dir} specified via ISAAC_PATH. Please provide the"
" correct path to the Isaac Sim installation."
)
print(f"Found Isaac Sim directory via ISAAC_PATH: {isaacsim_dir}")
return isaacsim_dir
def read_vscode_settings(vscode_filename: str) -> str:
"""Read VSCode settings from a file.
Args:
vscode_filename: Path to the VSCode settings file.
Returns:
The contents of the settings file as a string.
"""
with open(vscode_filename) as f:
return f.read()
def extract_extra_paths(vscode_settings: str) -> list[str]:
"""Extract extraPaths from VSCode settings.
Args:
vscode_settings: The VSCode settings content as a string.
Returns:
List of path names from the extraPaths setting.
"""
# search for the python.analysis.extraPaths section and extract the contents
settings_match = re.search(
r"\"python.analysis.extraPaths\": \[.*?\]", vscode_settings, flags=re.MULTILINE | re.DOTALL
)
if not settings_match:
# as a fallback,search for the cursorpyright.analysis.extraPaths section and extract the contents
settings_match = re.search(
r"\"cursorpyright.analysis.extraPaths\": \[.*?\]", vscode_settings, flags=re.MULTILINE | re.DOTALL
)
if not settings_match:
return []
settings = settings_match.group(0)
settings = settings.split('"python.analysis.extraPaths": [')[-1]
settings = settings.split("]")[0]
# read the path names from the settings file
path_names = settings.split(",")
path_names = [path_name.strip().strip('"') for path_name in path_names]
path_names = [path_name for path_name in path_names if len(path_name) > 0]
return path_names
def process_path_names(path_names: list[str], source_dir: str, target_dir: str = None) -> list[str]:
"""Process path names to be relative to the target directory.
Args:
path_names: List of path names to process.
source_dir: The source directory (relative to which paths are currently defined).
target_dir: The target directory (relative to which paths should be defined).
If None, uses PROJECT_DIR.
Returns:
List of processed path names.
"""
if target_dir is None:
target_dir = PROJECT_DIR
# change the path names to be relative to the target directory
rel_path = os.path.relpath(source_dir, target_dir)
processed_paths = []
for path_name in path_names:
# Remove any existing workspace folder reference
clean_path = path_name.replace("${workspaceFolder}/", "")
processed_path = f'"${{workspaceFolder}}/{rel_path}/{clean_path}"'
processed_paths.append(processed_path)
return processed_paths
def get_extra_paths_from_file(vscode_filename: str, source_dir: str, target_dir: str = None) -> list[str]:
"""Get extra paths from a VSCode settings file.
Args:
vscode_filename: Path to the VSCode settings file.
source_dir: The source directory (relative to which paths are currently defined).
target_dir: The target directory (relative to which paths should be defined).
Returns:
List of processed path names.
"""
if not os.path.exists(vscode_filename):
raise FileNotFoundError(f"Could not find the VS Code settings file: {vscode_filename}")
vscode_settings = read_vscode_settings(vscode_filename)
path_names = extract_extra_paths(vscode_settings)
return process_path_names(path_names, source_dir, target_dir)
def overwrite_python_analysis_extra_paths(isaacsim_dir: str | None, vscode_settings: str) -> str:
"""Overwrite the extraPaths in the VS Code settings file.
The extraPaths are replaced with the path names from the isaac-sim settings file that exists in the
"{ISAACSIM_DIR}/.vscode/settings.json" file.
If the isaac-sim VS Code settings file does not exist, the extraPaths are not overwritten.
Args:
isaacsim_dir: The path to the Isaac Sim directory.
vscode_settings: The settings string to use as template.
Returns:
The settings string with overwritten python analysis extra paths.
"""
# Get paths from Isaac Sim settings (if available)
if isaacsim_dir is not None:
isaacsim_vscode_filename = os.path.join(isaacsim_dir, ".vscode", "settings.json")
isaacsim_paths = get_extra_paths_from_file(isaacsim_vscode_filename, isaacsim_dir)
else:
isaacsim_paths = []
# Extract paths that were already in the template file
template_paths = extract_extra_paths(vscode_settings)
template_paths = process_path_names(template_paths, PROJECT_DIR)
# combine them into a single string
all_paths = isaacsim_paths + template_paths
path_names = ",\n\t\t".expandtabs(4).join(all_paths)
# deal with the path separator being different on Windows and Unix
path_names = path_names.replace("\\", "/")
for extra_path_type in ["python.analysis.extraPaths", "cursorpyright.analysis.extraPaths"]:
# replace the path names in the VS Code settings file with the path names parsed
vscode_settings = re.sub(
rf"\"{extra_path_type}\": \[.*?\]",
f'"{extra_path_type}": [\n\t\t'.expandtabs(4) + path_names + "\n\t]".expandtabs(4),
vscode_settings,
flags=re.DOTALL,
)
# return the VS Code settings string with modified extra paths
return vscode_settings
def overwrite_default_python_interpreter(vscode_settings: str) -> str:
"""Overwrite the default python interpreter in the VS Code settings file.
The default python interpreter is replaced with the path to the python interpreter used by the
isaac-sim project. This is necessary because the default python interpreter is the one shipped with
isaac-sim.
Args:
vscode_settings: The settings string to use as template.
Returns:
The settings string with overwritten default python interpreter.
"""
# read executable name
python_exe = os.path.normpath(sys.executable)
# replace with Isaac Sim's python.sh or python.bat scripts to make sure python with correct
# source paths is set as default
if f"kit{os.sep}python{os.sep}bin{os.sep}python" in python_exe:
# Check if the OS is Windows or Linux to use appropriate shell file
if platform.system() == "Windows":
python_exe = python_exe.replace(f"kit{os.sep}python{os.sep}bin{os.sep}python3", "python.bat")
else:
python_exe = python_exe.replace(f"kit{os.sep}python{os.sep}bin{os.sep}python3", "python.sh")
# replace the default python interpreter in the VS Code settings file with the path to the
# python interpreter in the Isaac Sim directory
vscode_settings = re.sub(
r"\"python.defaultInterpreterPath\": \".*?\"",
f'"python.defaultInterpreterPath": "{python_exe}"',
vscode_settings,
flags=re.DOTALL,
)
# return the VS Code settings file with modified default python interpreter
return vscode_settings
def create_header_message(template_filename: str) -> str:
"""Create a header message for generated files.
Args:
template_filename: The template filename to reference in the header.
Returns:
The header message string.
"""
return (
"// This file is a template and is automatically generated by the setup_vscode.py script.\n"
"// Do not edit this file directly.\n"
"// \n"
f"// Generated from: {template_filename}\n"
)
def write_settings_file(output_filename: str, content: str, template_filename: str):
"""Write settings content to a file with header.
Args:
output_filename: The output filename.
content: The content to write.
template_filename: The template filename for the header.
"""
header_message = create_header_message(template_filename)
full_content = header_message + content
with open(output_filename, "w") as f:
f.write(full_content)
def main():
"""Main function to setup the VS Code settings for the project."""
# get the Isaac Sim directory
isaacsim_dir = get_isaacsim_dir()
# VS Code template settings
pairlab_vscode_template_filename = os.path.join(PROJECT_DIR, ".vscode", "tools", "settings.template.json")
# make sure the VS Code template settings file exists
if not os.path.exists(pairlab_vscode_template_filename):
raise FileNotFoundError(
f"Could not find the PAIR Lab template settings file: {pairlab_vscode_template_filename}"
)
# read the Pair Lab VS Code template settings file
with open(pairlab_vscode_template_filename) as f:
pairlab_template_vscode_settings = f.read()
# overwrite the extraPaths in the Isaac Sim settings file with the path names
vscode_settings = overwrite_python_analysis_extra_paths(isaacsim_dir, pairlab_template_vscode_settings)
vscode_settings = overwrite_default_python_interpreter(vscode_settings)
# write the VS Code settings file
isaaclab_vscode_filename = os.path.join(PROJECT_DIR, ".vscode", "settings.json")
write_settings_file(isaaclab_vscode_filename, vscode_settings, pairlab_vscode_template_filename)
# copy the launch.json file if it doesn't exist
isaaclab_vscode_launch_filename = os.path.join(PROJECT_DIR, ".vscode", "launch.json")
isaaclab_vscode_template_launch_filename = os.path.join(PROJECT_DIR, ".vscode", "tools", "launch.template.json")
if not os.path.exists(isaaclab_vscode_launch_filename):
# read template launch settings
with open(isaaclab_vscode_template_launch_filename) as f:
isaaclab_template_launch_settings = f.read()
# write the VS Code launch settings file
write_settings_file(
isaaclab_vscode_launch_filename, isaaclab_template_launch_settings, isaaclab_vscode_template_launch_filename
)
if __name__ == "__main__":
main()
|