microsoft / vscode

Visual Studio Code
https://code.visualstudio.com
MIT License
162.66k stars 28.68k forks source link

Support environment variables for paths in .code-workspace files #44755

Open akbyrd opened 6 years ago

akbyrd commented 6 years ago

Issue Type

Feature Request

Description

I'm attempting to use { "path": "${env:APPDATA}/Code/User" } in my workspace to be able to easily open settings.json and keybindings.json as raw files (the custom panels take up too much space and I rarely need them) and it appears variables are not substituted when loading the workspace file.

VS Code Info

VS Code version: Code 1.20.1 (f88bbf9137d24d36d968ea6b2911786bfe103002, 2018-02-13T15:34:36.336Z) OS version: Windows_NT x64 10.0.16299

akbyrd commented 6 years ago

Related: It's also very hard or impossible to ignore files in a specific folder from the workspace settings. Consider the following scenario:

I have a directory structure

root/
  engine/
  game/
    log/
      <various log files>

I configure a multi-root workspace that encompasses both the engine and the game. When I'm working solely on the game I want to see the log files. When I'm working on the engine I want to see the game, but I don't want to see the log files.

I've tried various patterns in settings.files.exclude in the workspace file and I can't find a way to get it to apply only to the game folder.

"game/log": true,
"../game/log": true,
"${workspaceFolder:game}/log": true,
Gubith commented 5 years ago

I thought I was doing it wrong.

I've also been frustrated with the settings panels, which might be useful, although extensions are not sorted, and the resizer between the panels is too thin and hard to find, and panels wont resize enough, and search right panel should be separate, but aside from that, $appdata and $username are sometimes helpful with multiple users.

Workarounds... 1) Junctions, C:\cod => %appdata%\Code\ 2) Move everything to one path, C:\cod

Maybe this example will help escalate:

Files: C:\Users\FOO\TheAnswer\42.txt C:\Users\BAR\TheAnswer\muhuhuh.txt C:\Users\BAR\Desktop\nothingtoseehere.code-workspace.lnk

Workspace: C:\nothingtoseehere.code-workspace

Workspace contains: { "folders": [ ` { "path": "C:\Users\BAR\TheAnswer" }, { "path": "C:\Users\${UserName}\TheAnswer" } ] }`

Problem You are Bar. Foo wanted to share. Foo's last words were his password. doh.

Warning: Recreation may involve Vogons.

nghtstr commented 5 years ago

@bpasero, here is a more realistic situation. You are part of a team, and you would like to share the workspace as a part of the GIT repository. Here is an example situation:

{
    "folders": [
        {
            "name": "React Application",
            "path": "."
        },
        {
            "name": "GO Server",
            "path": "../goserver"
        },
        {
            "name": "Database Models",
            "path": "../models-go"
        },
        {
            "name": "GoLang Utilities",
            "path": "../utils-go"
        },
        {
            "path": "${env:HOME}/.go/src/example.com/example/models-go",
            "name": "Models (testing)"
        }
    ],
    "settings": {
        "git.ignoreLimitWarning": true
    }
}

Right now, the ${env:HOME} does not work, and I would love to see this actually work.

cawoodm commented 5 years ago

Another use case: I am developing an app which writes to files in the user's home directory ~/myapp/cache/.... Thus I want to watch this cache folder via the workspace path.

{
   "name": "cache",
   "path": "${env:USERPROFILE}\\.powowshell\\cache"
}

Neither does:

{
   "name": "cache",
   "path": "~/.powowshell/cache"
}
schperplata commented 4 years ago

@bpasero Any milestones for this feature request? I am also having trouble creating a template workspace for our company dev team, and I currently don't have any workarounds. For example, in our case given envioronment variable points to a disk where we have our common (company guidelines) folder structure and folders I would like to add to template workspace.

markm77 commented 4 years ago

People on this thread might also be interested in upvoting https://github.com/microsoft/vscode/issues/87889 where I am proposing support for repo (folder) environment variables for use in launch configs, tasks, the integrated terminal and anything else related to that repo/folder ....

vscodebot[bot] commented 4 years ago
This feature request is now a candidate for our backlog. The community has 60 days to upvote the issue. If it receives 20 upvotes we will move it to our backlog. If not, we will close it. To learn more about how we handle feature requests, please see our [documentation](https://aka.ms/vscode-issue-lifecycle). Happy Coding!
vscodebot[bot] commented 4 years ago
:slightly_smiling_face: This feature request received a sufficient number of community upvotes and we moved it to our backlog. To learn more about how we handle feature requests, please see our [documentation](https://aka.ms/vscode-issue-lifecycle). Happy Coding!
schperplata commented 4 years ago

@bpasero As this is one of the most "blocking" basic features... I am thinking of investing my time into a fix for this issue. It seems that at least expanding process environment variables would cover a lot of use cases. Has this issue completely fall off the radar? Any plans, recommendations?

bpasero commented 4 years ago

I can currently not provide the time to be a mentor of this feature through a PR, sorry. I would search for issues labeled "help wanted" to make sure you get team members that are willing to review the change.

Since this issue is on the "Backlog" it may be considered in the future, but our "Backlog" is also very large.

FStefanni commented 3 years ago

Hi,

I also like and find useful this feature.

I also suggest to allow to specify different paths according with the OS. For example:

{
   "name": "cache",
   "Win32": {
       "path": "${env:USERPROFILE}\\work\\myproject"
    },
    "Linux": {
       "path": "${env:HOME}/open-source/myproject"
     }
}

This would cover basically any portability issue between OS and environments. The split of config according with current OS has been proposed in #117661.

Finally also #87889 would be of great help.

Regards.

Jaakkonen commented 3 years ago

I'd be really cool to be able to set linting configurations using these substitutions. Be it ${env:XXX} or ${workspaceFolder:XXX}. I would want to do something like:

{
  "folders": [
    {"path": "common"},
    {"path": "app1"},
    {"path": "app2"}
  ],
  "settings": {
    "python.linting.pylintArgs": ["--rcfile=${workspaceFolder:common}/pylint.cfg"]
  }
}
2BitSalute commented 3 years ago

I also want this feature. I have two clones of the same (large, multi-project) repo, and I want to use the same workspace file to filter out folders I don't care about. My repo has a setup script that sets the repo root environment variable, so if this feature worked, I'd substitute the variable for the hardcoded path.

alanlivio commented 3 years ago

It is a very interesting feature. $HOME or ${env.UserProfile} will help a lot.

myronwalkersonos commented 2 years ago

Maybe just allow for variables out of env.SOMETHING. I dont checkout my repositories under HOME or under a specific user profile. I put them on a separate drive altogether that is an SSD for speed with respect to checkout and builds.

env.REPOSITORIES is what I would probably end up using

My biggest issue here I run into is the python linter not being able to find the paths and not being able to checkin paths that are relative that all the users in a repot can use with out editing the workspace

myronwalkersonos commented 2 years ago

I have resorted to not checking in the workspaces but checking in templates and having the user run a script that creates rehomed versions of the workspaces from the templates.

#!/usr/bin/env python

import os
import shutil

# Standardized Python Version
PYTHON_VERSION = "python3.8"

THIS_DIR = os.path.abspath(os.path.dirname(__file__))

REPOSITORY_FOLDER = os.path.abspath(os.path.join(THIS_DIR, ".."))
AUTOMATION_FOLDER = os.path.abspath(os.path.join(REPOSITORY_FOLDER, "automation"))

VENV_FOLDER = os.path.join(AUTOMATION_FOLDER, ".venv")
VENV_BIN_FOLDER = os.path.join(VENV_FOLDER, "bin")
VENV_SITEPACKAGES_FOLDER = os.path.join(VENV_FOLDER, "lib", PYTHON_VERSION, "site-packages")

WORKSPACES_FOLDER = os.path.join(REPOSITORY_FOLDER, "workspaces")

def replace_macros(template_line):
    """
        Perform a simple replacement any macros found in the template line passed to us.
    """

    home = os.path.expanduser("~")

    filled_line = template_line

    filled_line = filled_line.replace(r"${TMPLT:AUTOMATION_FOLDER}", AUTOMATION_FOLDER)
    filled_line = filled_line.replace(r"${TMPLT:HOME}", home)
    filled_line = filled_line.replace(r"${TMPLT:PYTHON_VERSION}", PYTHON_VERSION)
    filled_line = filled_line.replace(r"${TMPLT:REPOSITORY_FOLDER}", REPOSITORY_FOLDER)
    filled_line = filled_line.replace(r"${TMPLT:VENV_FOLDER}", VENV_FOLDER)
    filled_line = filled_line.replace(r"${TMPLT:VENV_BIN_FOLDER}", VENV_BIN_FOLDER)
    filled_line = filled_line.replace(r"${TMPLT:VENV_SITEPACKAGES_FOLDER}", VENV_SITEPACKAGES_FOLDER)
    filled_line = filled_line.replace(r"${TMPLT:WORKSPACES_FOLDER}", WORKSPACES_FOLDER)

    return filled_line

def generate_devemopment_env_file():

    cache_dir = os.path.join(AUTOMATION_FOLDER, ".cache")
    if not os.path.exists(cache_dir):
        os.makedirs(cache_dir)

    dev_env_file = os.path.join(cache_dir, "development.evn")
    with open(dev_env_file, 'w') as envf:
        envf.write("PYTHONPATH={}/automation/python3/testroots:{}/automation/python3/packages:{}".format(
            REPOSITORY_FOLDER,
            REPOSITORY_FOLDER,
            VENV_SITEPACKAGES_FOLDER
        ))
        envf.write(os.linesep)

        #TODO: Add the setting of any other 'development.env' environment variables here.

        envf.write(os.linesep)

    return

def generate_vscode_workspace_files():
    # Go through all of the VSCODE workspace templates and generate the 'code-workspace' files homed to the
    # location of this cloned repository

    print("Scanning workspaces folder:")
    print(WORKSPACES_FOLDER)
    print("")

    workspace_template_files = []

    for root, dirs, files in os.walk(WORKSPACES_FOLDER):
        for np in files:
            np_full = os.path.join(root, np)
            if os.path.isfile(np_full):
                _, npext = os.path.splitext(np_full)
                if npext == ".template":
                    workspace_template_files.append(np_full)

    for template_file in workspace_template_files:

        template_file_base, template_file_ext = os.path.splitext(os.path.basename(template_file))
        template_file_dir = os.path.dirname(template_file)
        workspace_file = os.path.join(template_file_dir, "{}.code-workspace".format(template_file_base))

        print("Processing template: {}".format(template_file))

        with open(template_file, 'r') as tf:
            template_lines = tf.read().splitlines(True)

            with open(workspace_file, 'w') as wf:
                print("Generating code-workspace: {}".format(workspace_file))
                for tline in template_lines:
                    fline = replace_macros(tline)
                    wf.write(fline)

def rehome_repository_main():

    generate_devemopment_env_file()
    generate_vscode_workspace_files()

    return

if __name__ == "__main__":
    rehome_repository_main()
alanlivio commented 2 years ago

Thanks for sharing @myronsonos. But I still think that native support is very welcome.

alanlivio commented 2 years ago

HI @bpasero. Any milestones for this feature request?

erwanriou commented 2 years ago

Hi indeed that would be nice to implement that.

AndreyDodonov-EH commented 2 years ago

It would make sense if environment variables were to be referenced in the same way as in Debugging and Task configuration files, i.e. ${env:USERNAME}

https://code.visualstudio.com/docs/editor/variables-reference#_environment-variables

myronwalkersonos commented 2 years ago

Thanks for sharing @myronsonos. But I still think that native support is very welcome.

I am all for the native support. But some of us don't want to wait. :)

Poikilos commented 1 year ago

It should also be configurable to support a profile variable defined by VSCode like ${platform:home} above (so it is OS-dependent using USERPROFILE or HOME) as opposed to ${env:USERPROFILE} which is Windows-only.

Example:

{
    "settings": {
        "ruff.interpreter": [
            "${platform:home}\\virtualenvs\\kivy_venv\\Scripts\\python.exe"
        ],
    }
}

Also, both environment variable names (such as AppData) and even the overall path beyond that differs by platform, so both this issue and #5595 both need to be resolved for use cases similar to yours to be a cross-platform solution.

zsynacl commented 9 months ago

3.5 years after this feature put into backlog. Any progress yet 😢

starball5 commented 9 months ago

Related on Stack Overflow: VSCode code-workspace file - use environment variables for project home path

tony-sol commented 4 months ago

More than 6 years since issue created. Is any progress here?

juner commented 3 months ago

It would be great if we could use not only environment variables but also setting values.

{
  "folders": [
    { "path": "${config:super-project-base-path}/test", "name": "test"}
  ]
}

https://code.visualstudio.com/docs/editor/variables-reference#_configuration-variables

nrs-mparker commented 3 days ago

Like others, I ended up here because I need to use ${env:localappdata} in a workspace folder, which for me cascades in that folder being used in "python.defaultInterpreterPath". Today, this is the 114th-most upvoted open issue in vscode.