Using a shell command as VSCode task variable value
Asked Answered
T

2

13

I am trying to define a VSCode task in tasks.json that would adapt to the specific architecture where VSCode runs. To do this, I want to get the architecture as uname --m (e.g. "aarch64" or "amd64"). My goal is to interpolate the output of uname into an environment variable like so

"version": "2.0.0",
"tasks": [
    {
        "label": "build",
        "type": "shell",
        "command": "cmake",
        "args": [
            "-DMYLIB_INCLUDE_DIR=$MYLIB/include",
            "-DMYLIB_LIBRARY=$MYLIB/lib"
        ],
        "options": {
            "env": {
                "MYLIB": "${workspaceFolder}/mylib/${command:get_arch}"
            }
        },
    }
]

In my case, I will have architecture-specific versions of mylib under mylib/aarch64, mylib/amd64, etc.

My attempt so far as been to define a second get_arch task used in the environment definition of MYLIB, that simply runs uname.

{
    "label": "get_arch",
    "type": "shell",
    "command": "uname --m"
}

Of course, this task is not a proper command and so it isn't detected by VSCode and my build task fails. I checked out the documentation on variable substition, but they don't mention if it's possible to substitute a shell command. I guess this would be possible from within an extension, but I want to keep things as simple as possible.

Transitory answered 7/11, 2019 at 11:20 Comment(0)
S
16

This extension provides a way to launch arbitrary shell commands as a VS Code command:

"tasks": [
    {
        "label": "test_arch",
        "type": "shell",
        "command": "echo",
        "args": [
            "${MYARCH}"
        ],
        "options": {
            "env": {
                "MYARCH": "${input:get_arch}"
            }
        },
        "problemMatcher": []
    },
],
"inputs": [
    {
        "id": "get_arch",
        "type": "command",
        "command": "shellCommand.execute",
        "args": {
            "command": "uname -m"
        }
    }
]

One disadvantage I discovered is that you have to press Enter once more when the result of the command is prompted in picker. Aside of this, this is the straightest way to implement what you want, and yet it can be utilized in many similar situations.

Alternatively, you can add pickString input with arch picker or create an extension that adds only single command GetArch.

Sphacelus answered 19/11, 2019 at 9:34 Comment(0)
D
4

If you don't want to press enter every time, you can add the option useFirstResult: true in the args section.

Devil answered 16/3, 2020 at 11:33 Comment(1)
fyi - This might serve better as a comment on Dmitriy Vornychev's answer as an iteration of that solution, rather than an independent answerAntilogy

© 2022 - 2024 — McMap. All rights reserved.