Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
akbyrd opened this issue Feb 28, 2018 · 24 comments
Open

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

akbyrd opened this issue Feb 28, 2018 · 24 comments
Labels
feature-request Request for new features or functionality workbench-multiroot Multi-root (multiple folders) issues
Milestone

Comments

@akbyrd
Copy link
Contributor

akbyrd commented Feb 28, 2018

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 (f88bbf9, 2018-02-13T15:34:36.336Z)
OS version: Windows_NT x64 10.0.16299

@akbyrd
Copy link
Contributor Author

akbyrd commented Feb 28, 2018

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,

@bpasero bpasero added feature-request Request for new features or functionality workbench-multiroot Multi-root (multiple folders) issues labels Mar 1, 2018
@bpasero bpasero removed their assignment Mar 1, 2018
@bpasero bpasero changed the title Support environment variables in .code-workspace files Support environment variables for paths in .code-workspace files Mar 17, 2018
@Gubith
Copy link

Gubith commented Oct 30, 2018

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
Copy link

nghtstr commented Jan 23, 2019

@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
Copy link

cawoodm commented May 19, 2019

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
Copy link

@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.

@bpasero bpasero added this to the Backlog milestone Oct 24, 2019
@bpasero bpasero modified the milestones: Backlog, Backlog Candidates Nov 3, 2019
@markm77
Copy link

markm77 commented Jan 16, 2020

People on this thread might also be interested in upvoting #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
Copy link

vscodebot bot commented Jan 22, 2020

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.

Happy Coding!

@vscodebot
Copy link

vscodebot bot commented Feb 14, 2020

🙂 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.

Happy Coding!

@schperplata
Copy link

schperplata commented Aug 20, 2020

@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
Copy link
Member

bpasero commented Aug 20, 2020

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
Copy link

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
Copy link

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
Copy link

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
Copy link

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

@myronwalkersonos
Copy link

myronwalkersonos commented Oct 22, 2021

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
Copy link

myronwalkersonos commented Dec 2, 2021

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
Copy link

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

@alanlivio
Copy link

HI @bpasero. Any milestones for this feature request?

@erwanriou
Copy link

Hi indeed that would be nice to implement that.

@AndreyDodonov-EH
Copy link

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
Copy link

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
Copy link

Poikilos commented May 4, 2023

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
Copy link

zsynacl commented Nov 28, 2023

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

@starball5
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature-request Request for new features or functionality workbench-multiroot Multi-root (multiple folders) issues
Projects
None yet
Development

No branches or pull requests