Return an updated value for the `existing_path_var` PATH-like environment variable value by adding `new_path` to the front of that variable if `new_path` is not already part of this PATH-like variable.
(existing_path_var, new_path)
| 263 | |
| 264 | |
| 265 | def update_path_var(existing_path_var, new_path): |
| 266 | """ |
| 267 | Return an updated value for the `existing_path_var` PATH-like environment |
| 268 | variable value by adding `new_path` to the front of that variable if |
| 269 | `new_path` is not already part of this PATH-like variable. |
| 270 | """ |
| 271 | if not new_path: |
| 272 | return existing_path_var |
| 273 | |
| 274 | existing_path_var = existing_path_var or "" |
| 275 | |
| 276 | existing_path_var = os.fsdecode(existing_path_var) |
| 277 | new_path = os.fsdecode(new_path) |
| 278 | |
| 279 | path_elements = existing_path_var.split(os.pathsep) |
| 280 | |
| 281 | if not path_elements: |
| 282 | updated_path_var = new_path |
| 283 | |
| 284 | elif new_path not in path_elements: |
| 285 | # add new path to the front of the PATH env var |
| 286 | path_elements.insert(0, new_path) |
| 287 | updated_path_var = os.pathsep.join(path_elements) |
| 288 | |
| 289 | else: |
| 290 | # new path is already in PATH, change nothing |
| 291 | updated_path_var = existing_path_var |
| 292 | |
| 293 | if not isinstance(updated_path_var, str): |
| 294 | updated_path_var = os.fsdecode(updated_path_var) |
| 295 | |
| 296 | return updated_path_var |
| 297 | |
| 298 | |
| 299 | PATH_VARS = ( |