DEV Community

Anthony Leignel
Anthony Leignel

Posted on Edited on

🛠️ Local VS Code Environment Architecture: Python Scripts, Explicit Tasks, and Controlled Code Changes

Before and after comparison showing automatic code reindentation and whitespace cleanup applied to the same source file.

A development environment is more than a code editor. It also includes formatters, maintenance tools, backup mechanisms, language-specific settings, and various forms of automation.

As these components accumulate, it can become difficult to determine which tool modifies a file, when it happens, and which rules are applied.

A modification may originate from a formatter, an extension, an action triggered on save, or a project-specific setting.

VS Code Environment Pack, developed by Palks Studio, follows a different approach: organizing the development environment around independent Python scripts, explicitly triggered tasks, and project-local configuration.

The objective is not to replace existing tools, but to define their responsibilities, their execution scope, and the conditions under which they can modify code.


1. General Architecture

The system relies on three main layers:

  • A configuration layer specific to Visual Studio Code
  • An execution layer based on VS Code tasks and Python scripts
  • A local storage layer for backups and generated files

Version 1.2 presents the following structure:

vscode_pack_environnement_v1.2/
│
├── .vscode/
│   ├── extensions.json
│   ├── launch.json
│   ├── settings.json
│   ├── keybindings.json
│   └── tasks.json
│
├── clean.py
├── convert.py
├── space.py
├── backup.py
├── create.py
├── tree.py
│
├── LICENCE.md
│
└── docs/
    ├── README_COMMERCIAL.md
    ├── README_TECHNIQUE.md
    ├── INSTALL.md
    └── exemples/
Enter fullscreen mode Exit fullscreen mode

Each configuration file operates at a different level.

Component Primary responsibility
settings.json Editor behavior and configuration
tasks.json Definition of executable tasks
launch.json Running and debugging the active Python file
keybindings.json Mapping actions to keyboard shortcuts
extensions.json Extension recommendations
Python scripts Execution of technical operations

The architecture separates editor behavior from maintenance operations applied to files.

Visual Studio Code
        │
        ├── Editor configuration
        ├── Keyboard shortcuts
        └── User tasks
                  │
                  ▼
            Python scripts
                  │
                  ├── Analysis
                  ├── Cleaning
                  ├── Conversion
                  ├── Generation
                  └── Backup
                  │
                  ▼
              Local files
Enter fullscreen mode Exit fullscreen mode

The scripts can also be executed directly from a terminal.

This separation allows a significant portion of the functionality to remain independent of Visual Studio Code.


2. Local Configuration and Predictable Behavior

The .vscode/settings.json file defines workspace-specific settings.

This configuration makes it possible to share common conventions across multiple projects or developers without necessarily modifying the editor's global settings.

The main documented conventions are as follows:

Setting Configuration
Indentation 4 spaces
Reference line width 100 characters
Encoding UTF-8
Line endings LF
Format on save Disabled
Automatic saving Disabled
Visual word wrapping Enabled

The following educational configuration example illustrates this approach:

{
    "editor.formatOnSave": false,
    "editor.tabSize": 4,
    "editor.insertSpaces": true,
    "editor.detectIndentation": false,
    "editor.wordWrap": "on",
    "editor.rulers": [100],
    "files.encoding": "utf8",
    "files.eol": "\n",
    "files.autoSave": "off"
}
Enter fullscreen mode Exit fullscreen mode

The editor.detectIndentation setting is presented here as an option for enforcing a fixed indentation convention rather than allowing the editor to detect the indentation of an existing file.

This example illustrates the configuration principles. It does not reproduce the complete configuration file provided with the pack.

Disabling Automatic Formatting

The central setting is:

{
    "editor.formatOnSave": false
}
Enter fullscreen mode Exit fullscreen mode

It prevents the standard formatting operation from being triggered when a file is saved.

However, this does not mean that every automatic modification is disabled.

Other settings may still apply, including:

{
    "files.trimTrailingWhitespace": true,
    "files.insertFinalNewline": true
}
Enter fullscreen mode Exit fullscreen mode

These native editor operations remove trailing whitespace and insert a final newline when necessary.

The pack therefore distinguishes full-file formatting from basic operations performed by the editor.

This distinction is important for understanding exactly what happens when a file is saved.

Limitations of Workspace Configuration

Workspace settings do not provide complete isolation.

Language-specific settings, active extensions, and additional configurations can influence the editor's effective behavior.

For example, disabling editor.formatOnSave does not automatically disable every action defined in editor.codeActionsOnSave.

A predictable configuration therefore also requires reviewing save actions, active extensions, and potential language-specific overrides.


3. VS Code Tasks as an Orchestration Layer

The tasks.json file allows commands to be executed directly from Visual Studio Code.

In this architecture, tasks act as an intermediary between the editor and the Python scripts.

User action
     │
     ▼
 tasks.json
     │
     ▼
Python command
     │
     ▼
Maintenance script
     │
     ▼
Analysis or modification
Enter fullscreen mode Exit fullscreen mode

The user does not need to memorize every command or manually navigate between directories.

The task defines the program to execute, its arguments, and its working directory.

The pack already provides configured tasks for its maintenance tools. These operations are accessible directly from:

Terminal → Run Task…
Enter fullscreen mode Exit fullscreen mode

The user selects the required operation and execution scope without having to enter commands manually.

The following educational example illustrates how a task can execute the space.py analysis script:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Analyze whitespace",
            "type": "process",
            "command": "python",
            "args": [
                "${workspaceFolder}/space.py"
            ],
            "options": {
                "cwd": "${workspaceFolder}"
            },
            "problemMatcher": []
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

The ${workspaceFolder} variable constructs the script path from the folder opened in Visual Studio Code.

The working directory is also defined explicitly.

This example uses a process task, which passes arguments directly to the executable without relying on a shell to interpret an entire command string.

The Python executable must correspond to the environment being used. Depending on the operating system, it may be necessary to use python3, a virtual environment, or an explicit interpreter path.

The example illustrates the underlying integration mechanism. The tasks themselves are already configured in the pack.


4. Three Execution Scopes

The clean.py, convert.py, and space.py scripts support three execution modes.

Mode Scope
Global Supported files across the project
Active file File currently open in the editor
Custom selection Manually defined list of files

This organization separates the nature of an operation from its execution scope.

The same tool can analyze an entire project or operate on a single file.

Maintenance script
        │
        ├── Global mode
        │       └── Project
        │
        ├── Active file mode
        │       └── Open file
        │
        └── Custom mode
                └── Selected files
Enter fullscreen mode Exit fullscreen mode

Custom mode relies on a selection defined in tasks.json.

The different modes are accessible through the VS Code task interface, allowing users to choose the appropriate scope before execution.

Active File Execution Example

Visual Studio Code provides the ${file} variable, which represents the path of the active file.

A task can pass this value to a Python script:

{
    "label": "Clean active file",
    "type": "process",
    "command": "python",
    "args": [
        "${workspaceFolder}/clean.py",
        "${file}"
    ],
    "options": {
        "cwd": "${workspaceFolder}"
    },
    "problemMatcher": []
}
Enter fullscreen mode Exit fullscreen mode

This example illustrates how a target file can be passed to a Python script. The exact arguments depend on the interface implemented by the script.

Why Limit the Execution Scope?

A cleaning operation may be straightforward when it affects a single file.

Applied to hundreds of files, however, it can produce a large number of modifications, complicate Git reviews, and introduce changes in files that were not intended to be affected.

Execution scope therefore becomes an important aspect of operational safety.

A maintenance tool must be able to determine:

  • Which files are allowed
  • Which directories must be excluded
  • Which file extensions are supported
  • Whether the operation actually requires writing to a file

Global execution should remain an explicit decision rather than an unintended consequence of launching a script.


5. Separating Analysis from Modification

One of the important distinctions within the pack concerns the space.py and clean.py scripts.

The first analyzes files. The second can modify them.

Script Primary function Modifies files
space.py Detect formatting issues No
clean.py Clean whitespace Yes

This separation makes it possible to identify issues before deciding whether to apply corrections.

Analysis with space.py

The script detects several types of formatting issues, including:

  • Multiple spaces
  • Tabs
  • Trailing whitespace
  • Excessive consecutive blank lines

The analysis tasks are already available from the VS Code task menu.

The script can also be executed independently from a terminal:

python space.py
Enter fullscreen mode Exit fullscreen mode

The following educational example illustrates how trailing whitespace can be detected:

from pathlib import Path


def analyze_file(path):

    content = Path(path).read_text(
        encoding="utf-8"
    )

    issues = []

    for number, line in enumerate(
        content.splitlines(),
        start=1
    ):

        if line.endswith((" ", "\t")):

            issues.append({
                "line": number,
                "type": "trailing_whitespace"
            })

    return issues
Enter fullscreen mode Exit fullscreen mode

Example output:

[
    {
        "line": 12,
        "type": "trailing_whitespace"
    },
    {
        "line": 28,
        "type": "trailing_whitespace"
    }
]
Enter fullscreen mode Exit fullscreen mode

This function reads a file and returns detected issues without performing any write operation.

It illustrates the principle of a read-only analyzer without reproducing the exact implementation of space.py.

Analysis and Correction Are Not Equivalent

The presence of multiple spaces does not necessarily mean that a file requires correction.

In some cases, whitespace is part of the structure or content:

message = "Name:    Example"
Enter fullscreen mode Exit fullscreen mode

In other cases, it may be used for intentional alignment.

An analyzer can report a situation without automatically concluding that it represents an error.

This distinction prevents a formatting convention from becoming a systematic modification of file content.


6. File Cleaning with clean.py

The clean.py script operates on file types supported by the system:

.html
.css
.js
.json
.py
.txt
Enter fullscreen mode Exit fullscreen mode

Its responsibilities include removing unnecessary spaces and tabs, and limiting sequences of blank lines to two consecutive lines.

The pack provides dedicated cleaning tasks for the entire project, the active file, or a custom selection.

These tasks can be launched directly from:

Terminal → Run Task…
Enter fullscreen mode Exit fullscreen mode

The script also remains available for independent execution:

python clean.py
Enter fullscreen mode Exit fullscreen mode

Transforming Content Before Writing

A cleaning architecture can separate three operations:

Read file
    │
    ▼
Transform content
    │
    ▼
Compare original and transformed content
    │
    ├── No changes → no write
    │
    └── Changes detected → write file
Enter fullscreen mode Exit fullscreen mode

This separation makes it possible to test transformations independently of filesystem operations.

The following educational example illustrates the removal of trailing whitespace while preserving line endings:

def clean_trailing_whitespace(content):

    result = []

    for line in content.splitlines(
        keepends=True
    ):

        body = line.rstrip("\r\n")

        ending = line[len(body):]

        result.append(
            body.rstrip(" \t") + ending
        )

    return "".join(result)
Enter fullscreen mode Exit fullscreen mode

A separate writing function can compare the original content with the transformed content before modifying the file:

from pathlib import Path


def update_file(path, transform):

    path = Path(path)

    original = path.read_bytes()

    updated = transform(original)

    if updated == original:
        return False

    path.write_bytes(updated)

    return True
Enter fullscreen mode Exit fullscreen mode

This second function expects a transformation operating on bytes. A text-based transformation therefore requires an explicit decoding and encoding step.

These examples illustrate the separation between transformation and writing. They do not reproduce the source code of clean.py.

Preserving Code Semantics

Cleaning source files requires more care than cleaning ordinary text documents.

In Python, indentation is part of the program's structure.

if authorized:
    process_request()
Enter fullscreen mode Exit fullscreen mode

Incorrectly modifying this indentation can change program behavior or make the file invalid.

Whitespace can also be meaningful in:

  • Python multiline strings
  • JavaScript strings
  • HTML <pre> elements
  • Markdown documents
  • Strings stored in JSON files

A generic cleaning tool must therefore consider the formats being processed and the contexts in which whitespace is significant.

A rule applied to every line of a file is not automatically safe for every programming language.

Cleaning should remain a controlled operation, accompanied by a review of modifications when necessary.


7. Python Formatting and Reindentation

The pack provides a dedicated Python formatting task combining autopep8 and clean.py.

These tools address two different requirements.

Tool Responsibility
autopep8 Formatting according to PEP 8 rules
clean.py Additional whitespace cleaning

Python formatting is manually triggered on the active file.

The workflow can be represented as follows:

Active Python file
        │
        ▼
     autopep8
        │
        ▼
      clean.py
        │
        ▼
   Processed file
Enter fullscreen mode Exit fullscreen mode

Execution Through VS Code Tasks

The pack includes a dedicated task for formatting and cleaning the active Python file.

This task is directly accessible from:

Terminal → Run Task…
Enter fullscreen mode Exit fullscreen mode

The required commands are already configured in tasks.json. The user simply selects the Python formatting task without having to enter a command in the terminal.

Behind the scenes, the formatting operation relies on a command such as:

python -m autopep8 --in-place app.py
Enter fullscreen mode Exit fullscreen mode

The target file is automatically determined from the active file in the editor. The clean.py script then performs the additional cleaning operation.

This integration makes command-line tools accessible directly from VS Code while preserving manual execution and a clearly defined scope.

The task requires autopep8 to be installed in the selected Python environment.

Formatting and Syntax Correction

A formatter cannot always determine the developer's intention when a file contains an inconsistent structure.

Consider the following example:

def process_order(order):
if order:
    validate(order)
    save(order)
Enter fullscreen mode Exit fullscreen mode

Several corrections are possible depending on the intended behavior.

def process_order(order):
    if order:
        validate(order)
        save(order)
Enter fullscreen mode Exit fullscreen mode

Or:

def process_order(order):
    if order:
        validate(order)

    save(order)
Enter fullscreen mode Exit fullscreen mode

Both versions can be syntactically valid, but they do not produce the same behavior.

In the first version, saving depends on the condition. In the second, it occurs independently of that condition.

Correcting invalid indentation may therefore require a business logic decision.

A formatter cannot replace that decision.

Checking Syntax Before and After

Syntax validation can complement a formatting operation.

Python provides the ast module for analyzing source code.

import ast

from pathlib import Path


def validate_python(path):

    source = Path(path).read_text(
        encoding="utf-8"
    )

    ast.parse(source)

    return True
Enter fullscreen mode Exit fullscreen mode

This function verifies that the source can be parsed successfully.

Comparing abstract syntax trees before and after a transformation can also provide an additional safeguard for certain types of formatting.

However, it does not replace functional testing and cannot independently guarantee that behavior remains unchanged.

These checks represent possible additional safeguards rather than confirmed features of the current pack.


8. Line Ending Normalization with convert.py

Line endings are a common source of differences between development environments.

Two representations are particularly widespread.

Format Sequence Historical environment
CRLF \r\n Windows
LF \n Unix, Linux, macOS

The same file can appear identical visually while containing different byte sequences.

CRLF : 0D 0A
LF   : 0A
Enter fullscreen mode Exit fullscreen mode

These differences can produce extensive Git changes, compatibility issues with certain scripts, or inconsistencies between operating systems.

The convert.py script normalizes CRLF line endings to LF.

The corresponding conversion tasks are available directly through the VS Code task menu, with the same three execution scopes.

The script can also be executed independently:

python convert.py
Enter fullscreen mode Exit fullscreen mode

The documentation specifies that the script writes to a file only when conversion is necessary.

Byte-Level Conversion Example

An educational implementation can operate directly on the binary content of a file:

from pathlib import Path


def convert_to_lf(path):

    path = Path(path)

    original = path.read_bytes()

    updated = original.replace(
        b"\r\n",
        b"\n"
    )

    if updated == original:
        return False

    path.write_bytes(updated)

    return True
Enter fullscreen mode Exit fullscreen mode

This approach avoids implicit line ending conversion through Python's text mode.

It also preserves the remaining bytes of the file.

However, the function must be limited to supported text files. Applying this replacement to binary files could corrupt their content.

Files using different encodings, particularly UTF-16, also require an appropriate strategy.

An Idempotent Operation

CRLF-to-LF conversion has an interesting property: idempotence.

An operation is idempotent when repeating it produces no additional changes after the first successful execution.

First execution:

CRLF → LF

Second execution:

LF → LF
Enter fullscreen mode Exit fullscreen mode

This property is particularly useful for maintenance scripts.

It allows an operation to be repeated without generating unnecessary additional modifications.

Editor Configuration and Existing Files

The following setting defines the editor's line ending convention:

{
    "files.eol": "\n"
}
Enter fullscreen mode Exit fullscreen mode

It does not necessarily replace a normalization operation across existing project files.

In a collaborative project using Git, a .gitattributes file can also define normalization rules:

* text=auto

*.py   text eol=lf
*.html text eol=lf
*.css  text eol=lf
*.js   text eol=lf
*.json text eol=lf
Enter fullscreen mode Exit fullscreen mode

This configuration represents a possible complement to the pack, extending the convention to the Git repository level.


9. Project Structure Generation with create.py

Version 1.2 introduces a script for automatically generating a directory structure from a structure.txt file.

The principle is to describe a project's structure before creating it on the filesystem.

my_project
    README.md
    app
        app.py
    static
        css
            style.css
Enter fullscreen mode Exit fullscreen mode

The expected result is a directory structure such as:

my_project/
├── README.md
├── app/
│   └── app.py
└── static/
    └── css/
        └── style.css
Enter fullscreen mode Exit fullscreen mode

This approach separates the project description from its actual creation.

structure.txt
      │
      ▼
Parse structure
      │
      ▼
Resolve paths
      │
      ▼
Create directories
      │
      ▼
Create files
Enter fullscreen mode Exit fullscreen mode

The structure.txt file becomes a reusable representation of the project's initial architecture.

The pack provides a configured VS Code task that executes create.py. Once the structure has been defined, the user can generate the hierarchy directly from the task menu without manually entering Python commands.

A Declarative Structure

This approach defines what should exist rather than requiring every creation operation to be repeated manually.

An educational example using an explicit Python representation could be:

from pathlib import Path


structure = [
    ("app", "directory"),
    ("app/app.py", "file"),
    ("static/css", "directory"),
    ("static/css/style.css", "file"),
    ("README.md", "file")
]


def create_structure(root, entries):

    root = Path(root)

    for relative_path, entry_type in entries:

        target = root / relative_path

        if entry_type == "directory":

            target.mkdir(
                parents=True,
                exist_ok=True
            )

        elif entry_type == "file":

            target.parent.mkdir(
                parents=True,
                exist_ok=True
            )

            if not target.exists():
                target.touch()
Enter fullscreen mode Exit fullscreen mode

This example represents a possible stage after parsing the structure.txt file.

It does not reproduce the exact parsing and interpretation mechanism implemented by create.py.

Path Safety and Protection of Existing Files

Automatic file generation introduces several constraints.

An incorrectly defined structure may contain an absolute path, a reference to a parent directory, or a destination outside the project.

A robust architecture must verify that generated paths remain within the authorized directory.

It must also define what happens when a file already exists.

Overwriting an existing source file when regenerating a project structure could result in data loss.

Conditional file creation, illustrated in the previous example, provides an initial safeguard. Additional checks are still necessary for untrusted paths and concurrent access.

The purpose of this type of tool is to prepare a structure, not silently replace an existing project.


10. Architecture Documentation with tree.py

Understanding a project often begins with identifying its components and how they are organized.

The tree.py script automatically generates a file named:

PROJECT_TREE.txt
Enter fullscreen mode Exit fullscreen mode

This file represents the existing project structure.

my_project/
├── app/
│   ├── app.py
│   └── controllers/
├── static/
│   ├── css/
│   └── js/
├── README.md
└── requirements.txt
Enter fullscreen mode Exit fullscreen mode

Automatic generation provides a representation of the project's state at the time of execution.

It avoids manually maintaining a file listing that can quickly become outdated.

The corresponding VS Code task is already configured in the pack. A single execution generates the documentation file directly from the current project.

Recursive Directory Traversal

Python provides several mechanisms for traversing a directory hierarchy, including pathlib and os.walk().

An educational example can be constructed using pathlib:

from pathlib import Path


def generate_tree(path, prefix=""):

    path = Path(path)

    entries = sorted(
        path.iterdir(),
        key=lambda entry: (
            not entry.is_dir(),
            entry.name.lower()
        )
    )

    lines = []

    for index, entry in enumerate(entries):

        last = index == len(entries) - 1

        branch = "└── " if last else "├── "

        lines.append(
            prefix + branch + entry.name
        )

        if entry.is_dir() and not entry.is_symlink():

            extension = (
                "    " if last else "│   "
            )

            lines.extend(
                generate_tree(
                    entry,
                    prefix + extension
                )
            )

    return lines
Enter fullscreen mode Exit fullscreen mode

The result can then be written to a text file:

root = Path("my_project")

lines = [root.name + "/"]

lines.extend(generate_tree(root))

Path("PROJECT_TREE.txt").write_text(
    "\n".join(lines) + "\n",
    encoding="utf-8"
)
Enter fullscreen mode Exit fullscreen mode

This example illustrates recursive traversal with sorted entries and a visual representation of the directory hierarchy.

It avoids following symbolic links to directories, reducing the risk of unexpected recursive traversal.

Defining the Documentation Scope

A complete directory tree can become difficult to use when it contains thousands of generated files or dependencies.

A documentation strategy may exclude certain directories:

.git/
node_modules/
__pycache__/
.venv/
.backups/
Enter fullscreen mode Exit fullscreen mode

These exclusions represent a possible approach to producing a more readable structure.

The public documentation does not specify the exact exclusion list applied by tree.py.

Project structure documentation must also be distinguished from publication of project content.

Even without displaying file contents, a directory tree can reveal configuration names, internal paths, or the organization of sensitive components.

A review is therefore necessary before sharing a PROJECT_TREE.txt file publicly.


11. Timestamped Local Backups with backup.py

Version 1.2 introduces a local backup system integrated into the development workflow.

The documentation describes a backup triggered when a file is saved through a VS Code task named Auto-Backup.

Copies are stored in:

.backups/filename/
Enter fullscreen mode Exit fullscreen mode

Each backup is timestamped.

A possible organization is illustrated below:

.backups/
└── app.py/
    ├── app_20260701_142501.py
    ├── app_20260701_143212.py
    └── app_20260701_144037.py
Enter fullscreen mode Exit fullscreen mode

These filenames illustrate the timestamping principle. They do not necessarily reproduce the exact naming convention used by backup.py.

Saving and Backing Up Files

The system distinguishes the working file from its successive copies.

Working file
      │
      ▼
Save with Ctrl + S
      │
      ▼
Auto-Backup task
      │
      ▼
Timestamped copy
      │
      ▼
.backups/ directory
Enter fullscreen mode Exit fullscreen mode

The backup script does not need to modify the source file.

It produces an independent copy that can be used to restore a previously saved version.

The following educational example illustrates a backup operation:

from datetime import datetime
from pathlib import Path
from shutil import copy2


def backup_file(source, backup_root):

    source = Path(source)

    backup_root = Path(backup_root)

    destination = backup_root / source.name

    destination.mkdir(
        parents=True,
        exist_ok=True
    )

    timestamp = datetime.now().strftime(
        "%Y%m%d_%H%M%S_%f"
    )

    backup = destination / (
        f"{source.stem}_{timestamp}"
        f"{source.suffix}"
    )

    copy2(source, backup)

    return backup
Enter fullscreen mode Exit fullscreen mode

The function creates a dedicated directory, generates a timestamped filename, and copies the source file.

Including microseconds reduces the risk of collisions between backups created within the same second.

This example illustrates a possible strategy without reproducing the source code of backup.py.

A Specific Aspect of VS Code Integration

Tasks defined in tasks.json do not, by themselves, provide a generic native trigger that executes a task every time a file is saved.

A backup integration can therefore rely on a command sequence, a custom keyboard shortcut, or another mechanism connecting the save operation to script execution.

The pack's documentation describes an integration with Ctrl + S without an external extension, but does not present the complete triggering mechanism in the public README.

It is also important to distinguish a backup performed before saving from one performed afterward.

Backup timing Content preserved
Before saving Previous version stored on disk
After saving Newly saved version

Both approaches can preserve previous versions, but their restoration behavior is not identical.

The order of operations must therefore be clearly defined.


12. Local Backups, VS Code History, and Git

Timestamped backups do not address exactly the same requirements as a version control system.

Mechanism Primary responsibility
Git Structured project version history
Local History Local history integrated into VS Code
Hot Exit Recovery of unsaved modifications
backup.py Timestamped copies of saved files

Git preserves coherent versions of a project, supports change comparisons and branching, and enables collaboration between developers.

Local backups make it possible to recover intermediate versions that may not have been committed.

Hot Exit addresses a different requirement: recovering unsaved modifications after the editor is closed or restarted.

These mechanisms can therefore complement one another.

Limitations of Per-File Backups

A timestamped copy of a file does not necessarily represent a consistent state of the entire project.

A modification may involve several interdependent files:

app.py
config.py
models.py
Enter fullscreen mode Exit fullscreen mode

Restoring only app.py to a previous version could introduce incompatibilities with the other files.

A local per-file backup provides a quick recovery mechanism, but does not replace Git commits or complete project backups.

Managing Backup Storage

Creating a copy every time a file is saved can gradually increase disk usage.

For example:

Average file size : 200 KB
Number of backups : 100
Total storage     : approximately 20 MB
Enter fullscreen mode Exit fullscreen mode

Across several projects and months of development, this volume can become significant.

A retention strategy could introduce a maximum retention period, a per-file limit, or different retention rules depending on backup age.

These mechanisms are not presented as current features of the pack. They represent possible improvements for managing storage.

Finally, backups stored on the same disk as the source files do not protect against complete disk failure.


13. Exclusions and Filesystem Protection

Maintenance scripts must distinguish source files from technical or generated directories.

The documentation includes exclusions for common directories such as:

.git/
node_modules/
__pycache__/
Enter fullscreen mode Exit fullscreen mode

The cleaning and conversion scripts also ignore the following directory:

.backups/
Enter fullscreen mode Exit fullscreen mode

This last exclusion is particularly important.

A backup should preserve the content recorded at a specific point in time. If a global cleaning operation also modifies previous copies, those backups no longer accurately represent historical versions.

Project
   │
   ├── Source files  → processing allowed
   │
   ├── .git/         → excluded
   ├── node_modules/ → excluded
   ├── __pycache__/  → excluded
   └── .backups/     → excluded
Enter fullscreen mode Exit fullscreen mode

File Filtering

An educational file selection approach could be represented as follows:

from pathlib import Path


SUPPORTED = {
    ".py",
    ".html",
    ".css",
    ".js",
    ".json",
    ".txt"
}

EXCLUDED = {
    ".git",
    "node_modules",
    "__pycache__",
    ".backups"
}


def is_supported(path, root):

    path = Path(path)

    relative = path.relative_to(root)

    if any(
        part in EXCLUDED
        for part in relative.parts
    ):
        return False

    return (
        path.is_file()
        and path.suffix.lower() in SUPPORTED
    )
Enter fullscreen mode Exit fullscreen mode

This filter checks a file's extension and the components of its relative path.

It does not provide complete protection on its own.

A robust implementation must also account for symbolic links, resolved paths, inaccessible files, and permission errors.

Visually excluding a directory from the VS Code explorer does not guarantee that a Python script will exclude it.

Selection rules must be enforced by the component that actually performs the operation.


14. Write Operations, Errors, and File Integrity

Maintenance scripts operate directly on project files.

An interruption during a write operation, a permission issue, or insufficient disk space can therefore affect file integrity.

A more robust writing strategy consists of creating a temporary file before replacing the target file.

Original file
      │
      ▼
Transformation
      │
      ▼
Temporary file
      │
      ▼
Verification
      │
      ▼
Replace target file
Enter fullscreen mode Exit fullscreen mode

The following educational example uses tempfile and os.replace():

import os
import tempfile

from pathlib import Path


def atomic_write(path, content):

    path = Path(path)

    temporary = None

    try:

        with tempfile.NamedTemporaryFile(
            mode="wb",
            dir=path.parent,
            delete=False
        ) as file:

            temporary = Path(file.name)

            file.write(content)

            file.flush()

            os.fsync(file.fileno())

        os.replace(temporary, path)

    finally:

        if temporary and temporary.exists():
            temporary.unlink()
Enter fullscreen mode Exit fullscreen mode

The temporary file is created in the same directory as the destination, allowing the operation to remain on the same filesystem.

This approach reduces the risk of leaving a partially written file if execution is interrupted before replacement.

However, it does not guarantee complete protection against every possible failure.

Preserving permissions, handling concurrent modifications, maintaining metadata, and ensuring durability after a system failure require additional precautions.

This strategy represents a possible improvement for maintenance scripts. The public documentation does not confirm its use in the current pack.


15. Cross-Platform Compatibility

The pack is designed to operate on Windows, macOS, and Linux.

Python and Visual Studio Code allow a significant portion of the configuration to be shared across these environments.

However, several differences remain important.

Element Consideration
Paths Separators and absolute paths
Python interpreter Executable name and location
Line endings CRLF and LF conventions
Permissions Read and write access
Keyboard shortcuts Operating system shortcut conflicts
Case sensitivity Filesystem behavior

The pathlib module makes it possible to manipulate paths without manually constructing operating-system-specific strings.

from pathlib import Path


workspace = Path.cwd()

backup_directory = workspace / ".backups"

backup_directory.mkdir(
    parents=True,
    exist_ok=True
)
Enter fullscreen mode Exit fullscreen mode

The same code can therefore construct a path appropriate to the environment in which it runs.

Keyboard Shortcut Management

The pack documents two shortcuts:

Shortcut Action
Alt + M Toggle the minimap
Alt + R Reindent the active file

Visual Studio Code allows commands to be associated with keyboard shortcuts in keybindings.json.

An example configuration is:

[
    {
        "key": "alt+m",
        "command": "editor.action.toggleMinimap"
    },
    {
        "key": "alt+r",
        "command": "editor.action.reindentlines",
        "when": "editorTextFocus"
    }
]
Enter fullscreen mode Exit fullscreen mode

The when condition restricts shortcut activation to a particular context.

However, workspace settings must be distinguished from user keyboard shortcuts.

Unlike settings.json and tasks.json, a keybindings.json file placed inside .vscode/ is not automatically loaded as a native project-specific keyboard shortcut configuration.

Its contents must be integrated into the user's Visual Studio Code keyboard shortcut settings or handled through an appropriate mechanism.

This distinction is important when deploying the pack across multiple development machines.


16. Optional Extensions and Controlled Dependencies

The pack provides configuration compatible with several common extensions:

  • Prettier
  • ErrorLens
  • Indent-Rainbow
  • Auto-Rename-Tag

These extensions remain optional.

The objective is to maintain a separation between the tools required for core functionality and those that improve the editing experience.

Component Function
Python Execution of local scripts
VS Code Editor and task orchestration
autopep8 Python formatting through a dedicated task
Prettier Formatting of supported languages
ErrorLens Displaying diagnostics in the editor

The presence of a Prettier configuration does not mean that the formatter executes automatically.

Similarly, the .vscode/extensions.json file can define extension recommendations and unwanted recommendations.

{
    "unwantedRecommendations": [
        "esbenp.prettier-vscode"
    ]
}
Enter fullscreen mode Exit fullscreen mode

This setting does not technically disable an extension that is already installed and active.

Disabling an extension within a workspace is handled through Visual Studio Code's extension management features.

Three mechanisms must therefore remain distinct:

  • Recommending or not recommending an extension
  • Enabling or disabling an extension within a workspace
  • Configuring the actions an extension can trigger

A consistent configuration must account for all three levels.

The absence of a dependency on an external service does not mean the absence of software dependencies. Python is required to execute the scripts, and autopep8 must be available for the Python formatting task.


17. A Local Environment Without Remote Service Dependencies

The pack's scripts execute their operations directly on the local filesystem.

Development machine
         │
         ├── Visual Studio Code
         ├── Python interpreter
         ├── Maintenance scripts
         ├── Source files
         └── Local backups
Enter fullscreen mode Exit fullscreen mode

Cleaning, line ending conversion, structure generation, and backup creation do not require communication with a remote server.

This architecture allows the scripts to operate in isolated or offline environments, provided the required tools are already installed.

However, the behavior of the scripts must be distinguished from that of the complete development environment.

Visual Studio Code, its extensions, synchronization features, and dependency management tools may perform network communications independently of the pack.

Local script execution therefore does not guarantee a complete absence of network traffic on the development machine.

For a strictly isolated environment, synchronization settings, active extensions, and other components must also be controlled.


18. An Explicit and Verifiable Workflow

The organization of the pack makes it possible to build a workflow in which individual operations remain identifiable.

Project creation
       │
       ▼
Development
       │
       ▼
Saving and backup
       │
       ▼
File analysis
       │
       ▼
Execution scope selection
       │
       ▼
Cleaning or formatting
       │
       ▼
Review modifications
       │
       ▼
Generate structure documentation
Enter fullscreen mode Exit fullscreen mode

These operations do not necessarily need to be executed during every development session.

Their value lies in the ability to select the operations appropriate to the current context.

For example, before a code review, a developer can analyze whitespace, clean only the relevant files, and review the modifications with Git.

The analysis and cleaning operations are available directly through the VS Code task menu.

Git can then be used to review the resulting changes:

git diff --stat
Enter fullscreen mode Exit fullscreen mode

And inspect the detailed modifications:

git diff
Enter fullscreen mode Exit fullscreen mode

Directory tree generation can be executed whenever technical documentation needs to be updated.

Local backups remain available independently of these operations.

One Responsibility per Tool

The entire architecture relies on specialized components.

Script Responsibility
create.py Project structure creation
tree.py Directory structure documentation
space.py Whitespace and formatting analysis
clean.py File cleaning
convert.py Line ending normalization
backup.py Timestamped local backups

This organization allows one script to evolve without systematically modifying the others.

It also facilitates reuse outside Visual Studio Code.

A conversion script can be integrated into another workflow. A directory tree generator can document an independent project. An analyzer can be executed from a terminal without loading the entire development environment.

Modularity is therefore not simply about separating files. It involves defining responsibilities precisely enough for each component to remain understandable, testable, and reusable.


Conclusion

VS Code Environment Pack illustrates an approach to development environments in which editor configuration, maintenance operations, and backup mechanisms remain distinct.

VS Code tasks provide an orchestration layer, while Python scripts perform operations on local files.

The separation between analysis and modification, the three execution scopes, line ending normalization, and timestamped backups contribute to a more predictable workflow.

This architecture does not eliminate the risks associated with automated modifications. It makes it easier to identify operations, limit their scope, and maintain recovery mechanisms.

A controlled development environment does not necessarily rely on the absence of automation.

It relies on a clear distinction between authorized automatic actions, explicitly triggered operations, and transformations that require verification.

The objective is to make the behavior of development tools as understandable as the code they help maintain.


Technical Documentation

The pack's structure, available scripts, configuration settings, and operating principles for version 1.2 are described in its public documentation.

View the technical documentation on GitHub


https://palks-studio.com

Top comments (0)