Search code examples
pythongithubgithub-codespaces

How to automatically start a GitHub Codespace with some Python packages?


I started using Codespaces for small modifications in my open-source Python repositories. Most of them require only 2 core dependencies, pre-commit and nox. Is it possible to save a codespace configuration where these 2 libraries are automatically installed every time I create a new codespace?

Even better if this configuration can be scoped for each repository for small adjustments.


Solution

  • To trigger the build of a custom codespace you need to configure the devcontainer. Create a .devcontainer directory at the root of your repository. in this folder create a .devcontainer.json file. Here is the minimal container I use to build an environment with Python tools:

    //.devcontainer/devcontainer.json
    {
      "name": "Python 3",
      // use the latest python image
      "image": "mcr.microsoft.com/devcontainers/python",
      // install libs after the creation of the environement 
      // by using a simple bash command
      "postCreateCommand": "python -m pip install nox pre-commit && pre-commit install"
    }
    

    GitHub Codespaces cannot handle multiple-line post create commands, thus the use of &&. As suggested in this issue, you can also use a .devcontainer/postCreateCommand.sh:

    #.devcontainer/postCreateCommand.sh
    pip install nox pre-commit &&
    pre-commit install
    
    //.devcontainer/devcontainer.json
    {
      "name": "Python 3",
      // use the latest python image
      "image": "mcr.microsoft.com/devcontainers/python",
      // install libs after the creation of the environement 
      // by using a simple bash command
      "postCreateCommand": "./.devcontainer/postCreateCommand.sh"
    }
    

    Instead of using the classic pip install xxx you can also search if the libraries you need to include exist in the image features by using the codespace VS Code extension as suggested in GitHub's documentation. The previous JSON file would become:

    //.devcontainer/devcontainer.json
    {
        "name": "Python 3",
        "image": "mcr.microsoft.com/devcontainers/python",
        "features": {
            "ghcr.io/devcontainers-contrib/features/nox:2": {},
            "ghcr.io/devcontainers-contrib/features/pre-commit:2": {}
        },
        "postCreateCommand": "pre-commit install"
    }