F2Starters et scripts

Starter Nix/Python

Flake, justfile, pyproject et pre-commit pour démarrer un projet Python reproductible.

nixpythonflakepre-commit
Versionstarter v1
Typemarkdown
Source~/Projects/100_MYNIX/mynix

Starter Nix + Python

Socle minimal pour un projet Python reproductible.

Fichiers

  • flake.nix : environnement Python 3.12, pytest, black, ruff, isort.
  • justfile : commandes just test, just format, just check.
  • pyproject.toml : packaging, tests, formatage. La licence est volontairement Propriétaire ; à remplacer.
  • .pre-commit-config.yaml : hooks de formatage et de contrôle.

Mise en route

nix develop
pre-commit install
just check

Limites

Le flake.nix source contient encore des messages d'interface avec un encodage ancien. Il est conservé comme point de départ ; nettoyer les chaînes avant publication.

flake.nix

{
  description = "MYNIX - Mon Environnement Reproductible";

  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    flake-utils.url = "github:numtide/flake-utils";
  };

  outputs = { self, nixpkgs, flake-utils }:
    flake-utils.lib.eachDefaultSystem (system:
      let
        pkgs = import nixpkgs { inherit system; };
        python = pkgs.python312;
        
        pythonEnv = python.withPackages (ps: with ps; [
          # Core dependencies (versions gérées par Nix)
          pandas      # 2.3.3
          numpy       # 2.3.5
          pyyaml

          # Optional dependencies
          scipy
          matplotlib
          seaborn
          
          # Dev tools
          pytest
          pytest-cov       # AJOUTÉ : Pour coverage reports
          black
          ruff
          isort
          autopep8
          mypy
          ipython
          pip
          virtualenv
          python-dotenv
          
          # Build tools (CRITIQUE pour 'python -m build')
          build
          setuptools
          wheel
          twine
        ]);
        
        checkIntegrity = pkgs.writeShellScriptBin "check-integrity" ''
          #!/usr/bin/env bash
          set -euo pipefail
          
          REQUIRED=("flake.nix" "flake.lock" ".envrc" ".gitignore" "justfile")
          MISSING=()
          for f in "''${REQUIRED[@]}"; do
            [ ! -f "$f" ] && MISSING+=("$f")
          done
          
          if [ ''${#MISSING[@]} -gt 0 ]; then
            echo "❌ Fichiers manquants: ''${MISSING[@]}"
            return 1
          fi
          echo "✅ Intégrité OK"
        '';
        
        autoFormat = pkgs.writeShellScriptBin "auto-format" ''
          #!/usr/bin/env bash
          set -euo pipefail
          
          ${pythonEnv}/bin/ruff check . --select F841 --fix --unsafe-fixes --quiet || true
          ${pythonEnv}/bin/isort . --profile black --quiet || true
          ${pythonEnv}/bin/black . --quiet || true
          ${pythonEnv}/bin/ruff check . --fix --exit-zero --quiet || true
          echo "✅ Formatage terminé"
        '';
        
        smartTest = pkgs.writeShellScriptBin "smart-test" ''
          #!/usr/bin/env bash
          ${autoFormat}/bin/auto-format
          ${pythonEnv}/bin/pytest tests/ -v "$@"
        '';
        
      in {
        devShells.default = pkgs.mkShell {
          buildInputs = [
            pythonEnv
            pkgs.git
            pkgs.just
            pkgs.pre-commit
            checkIntegrity
            autoFormat
            smartTest
            pkgs.python3Packages.python-dotenv
          ];
          
          shellHook = ''
            echo "🌟 mif-dqf - Environnement activé"
            export PYTHONPATH="''${PYTHONPATH:-}:$(pwd)"
            
            # Vérifier versions critiques
            echo ""
            echo "📦 Versions Python:"
            python --version
            python -c "import numpy; print('  numpy:', numpy.__version__)"
            python -c "import pandas; print('  pandas:', pandas.__version__)"
            
            check-integrity || echo "⚠️  Problèmes détectés"
            
            echo ""
            echo "📋 Commandes: check-integrity, auto-format, smart-test, just"
          '';
        };
      }
    );
}

justfile

# Justfile for synX project
# Usage: just <command>

default: status

# === MEMORY INDEXATION ===

# Index all files in memory/
index:
    @echo "🔍 Indexing memory/..."
    @python scripts/memory_indexer.py
    @echo "✅ Indexation complete"

# Test database connection
test-db:
    @echo "🧪 Testing memory.db..."
    @python -c "import sqlite3; import sqlite_vec; conn = sqlite3.connect('memory.db'); conn.enable_load_extension(True); sqlite_vec.load(conn); print('✅ Database OK'); conn.close()"

# Show indexed chunks
show-index:
    @echo "📊 Indexed chunks:"
    @sqlite3 memory.db "SELECT filepath, COUNT(*) as chunks FROM concepts GROUP BY filepath;"

# Search in memory (keyword-based for now)
search QUERY:
    @python scripts/memory_search.py "{{QUERY}}"

# === CODE QUALITY ===

# Format code with black
format:
    @echo "🎨 Formatting..."
    @black scripts/ || true
    @isort scripts/ || true
    @echo "✅ Formatting complete"

# Lint code
lint:
    @echo "🔍 Linting..."
    @ruff check scripts/
    @echo "✅ Linting OK"

# === UTILITIES ===

# Show project status
status:
    @echo "🧠 synX Project Status"
    @echo "======================"
    @echo ""
    @echo "Memory files:"
    @ls -1 memory/*.md 2>/dev/null | wc -l || echo "0"
    @echo ""
    @echo "Database:"
    @[ -f memory.db ] && echo "✅ memory.db exists" || echo "❌ memory.db missing (run 'just index')"
    @echo ""
    @echo "Indexed chunks:"
    @[ -f memory.db ] && sqlite3 memory.db "SELECT COUNT(*) FROM concepts;" 2>/dev/null || echo "0"

# Clean generated files
clean:
    @echo "🧹 Cleaning..."
    @rm -f memory.db
    @find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
    @echo "✅ Clean complete"

# === GIT ===

# Git sync (commit + push)
sync MESSAGE:
    @echo " Git sync..."
    python scripts/git_sync.py "{{MESSAGE}}"
    @echo " Sync complete"

# Create git tag
tag VERSION:
    @echo "  Creating tag {{VERSION}}..."
    git tag -a {{VERSION}} -m "Release {{VERSION}}"
    git push origin {{VERSION}}
    @echo " Tag {{VERSION}} created"

# List available commands
help:
    @just --list

pyproject.toml

[build-system]
requires = ["setuptools>=61.0", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "project-starter"
version = "0.1.0"
description = "Starter Python reproductible pour un projet mynix"
authors = [{name = "Projet", email = "templates@example.invalid"}]
license = {text = "Propriétaire"}
requires-python = ">=3.10"
dependencies = [
    "pandas",
    "numpy",
    "pyyaml",
    "scipy",
    "matplotlib",
    "seaborn",
    "click",
    "rich",
    "colorama",
]

[project.optional-dependencies]
dev = [
    "pytest>=7.0",
    "pytest-cov>=4.0",
    "black>=23.0",
    "ruff>=0.1.0",
    "isort>=5.12",
]

[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py"]
addopts = ["-v", "--cov=src", "--cov-report=html"]

[tool.black]
line-length = 88
target-version = ["py310"]

[tool.ruff]
line-length = 88
select = ["E", "F", "W"]

[tool.isort]
profile = "black"

.pre-commit-config.yaml

# Pre-commit hooks pour Grid Bot
repos:
  - repo: https://github.com/psf/black
    rev: 24.1.0
    hooks:
      - id: black
        language_version: python3.12
        
  - repo: https://github.com/pycqa/isort
    rev: 5.13.2
    hooks:
      - id: isort
        args: ["--profile", "black"]
        
  - repo: https://github.com/pycqa/flake8
    rev: 7.0.0
    hooks:
      - id: flake8
        args: ["--max-line-length=88", "--extend-ignore=E203,W503"]
        
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.5.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-added-large-files
        args: ['--maxkb=500']