Compare commits

...

5 Commits

Author SHA1 Message Date
Simon C
4d34215aa5 docs: Ajout de documentation autour de l'auto-reload et du livereload 2024-08-08 23:42:12 +02:00
Simon C
237bbe789f feat: Add livereload 2024-08-08 22:19:24 +02:00
Simon C
1ae80c161f feat: Add auto-reload on development environment 2024-08-08 22:18:26 +02:00
668a91941b Merge pull request 'style: Format code with fmt' (#48) from fmt into main
### Détails

`fmt` permet de formater le code Rust, je pense que c'est une bonne chose que l'on utilise l'utilitaire aevc la commande `cargo fmt` nous pourrons mettre en place un test de validation des DAs quand nous aurons une CI avec la commande suivante `cargo fmt --all -- --check`.

### Pourquoi ?

Pour rendre le code plus lisible

### Documentation

https://rust-lang.github.io/rustfmt/

Reviewed-on: #48
Reviewed-by: theo <theo.lettermann@gmail.com>
2024-08-08 15:08:03 +02:00
Simon C
0eaf238735 style: Format code with fmt 2024-08-08 15:01:28 +02:00
13 changed files with 238 additions and 25 deletions

5
.ignore Normal file
View File

@ -0,0 +1,5 @@
# Ignorer les fichiers dont ne dépent pas la compilation
*.md
tailwind.config.js
*.example
scripts

135
Cargo.lock generated
View File

@ -69,9 +69,12 @@ dependencies = [
"askama", "askama",
"askama_axum", "askama_axum",
"axum", "axum",
"listenfd",
"notify",
"serde", "serde",
"tokio", "tokio",
"tower-http", "tower-http",
"tower-livereload",
] ]
[[package]] [[package]]
@ -867,6 +870,18 @@ dependencies = [
"rustc_version", "rustc_version",
] ]
[[package]]
name = "filetime"
version = "0.2.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ee447700ac8aa0b2f2bd7bc4462ad686ba06baa6727ac149a2d6277f0d240fd"
dependencies = [
"cfg-if",
"libc",
"redox_syscall 0.4.1",
"windows-sys 0.52.0",
]
[[package]] [[package]]
name = "flate2" name = "flate2"
version = "1.0.30" version = "1.0.30"
@ -919,6 +934,15 @@ dependencies = [
"percent-encoding", "percent-encoding",
] ]
[[package]]
name = "fsevent-sys"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "futf" name = "futf"
version = "0.1.5" version = "0.1.5"
@ -1539,6 +1563,26 @@ dependencies = [
"cfb", "cfb",
] ]
[[package]]
name = "inotify"
version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8069d3ec154eb856955c1c0fbffefbf5f3c40a104ec912d4797314c1801abff"
dependencies = [
"bitflags 1.3.2",
"inotify-sys",
"libc",
]
[[package]]
name = "inotify-sys"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "instant" name = "instant"
version = "0.1.13" version = "0.1.13"
@ -1642,6 +1686,26 @@ dependencies = [
"unicode-segmentation", "unicode-segmentation",
] ]
[[package]]
name = "kqueue"
version = "1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7447f1ca1b7b563588a205fe93dea8df60fd981423a768bc1c0ded35ed147d0c"
dependencies = [
"kqueue-sys",
"libc",
]
[[package]]
name = "kqueue-sys"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed9625ffda8729b85e45cf04090035ac368927b8cebc34898e7c120f52e4838b"
dependencies = [
"bitflags 1.3.2",
"libc",
]
[[package]] [[package]]
name = "kuchikiki" name = "kuchikiki"
version = "0.8.2" version = "0.8.2"
@ -1717,6 +1781,17 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "listenfd"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0500463acd96259d219abb05dc57e5a076ef04b2db9a2112846929b5f174c96"
dependencies = [
"libc",
"uuid",
"winapi",
]
[[package]] [[package]]
name = "lock_api" name = "lock_api"
version = "0.4.12" version = "0.4.12"
@ -1845,6 +1920,18 @@ dependencies = [
"simd-adler32", "simd-adler32",
] ]
[[package]]
name = "mio"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c"
dependencies = [
"libc",
"log",
"wasi 0.11.0+wasi-snapshot-preview1",
"windows-sys 0.48.0",
]
[[package]] [[package]]
name = "mio" name = "mio"
version = "1.0.1" version = "1.0.1"
@ -1927,6 +2014,25 @@ dependencies = [
"minimal-lexical", "minimal-lexical",
] ]
[[package]]
name = "notify"
version = "6.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6205bd8bb1e454ad2e27422015fb5e4f2bcc7e08fa8f27058670d208324a4d2d"
dependencies = [
"bitflags 2.6.0",
"crossbeam-channel",
"filetime",
"fsevent-sys",
"inotify",
"kqueue",
"libc",
"log",
"mio 0.8.11",
"walkdir",
"windows-sys 0.48.0",
]
[[package]] [[package]]
name = "nu-ansi-term" name = "nu-ansi-term"
version = "0.46.0" version = "0.46.0"
@ -2171,7 +2277,7 @@ checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"libc", "libc",
"redox_syscall", "redox_syscall 0.5.3",
"smallvec", "smallvec",
"windows-targets 0.52.6", "windows-targets 0.52.6",
] ]
@ -2567,6 +2673,15 @@ version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
[[package]]
name = "redox_syscall"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa"
dependencies = [
"bitflags 1.3.2",
]
[[package]] [[package]]
name = "redox_syscall" name = "redox_syscall"
version = "0.5.3" version = "0.5.3"
@ -3010,7 +3125,7 @@ dependencies = [
"objc2-foundation", "objc2-foundation",
"objc2-quartz-core", "objc2-quartz-core",
"raw-window-handle 0.6.2", "raw-window-handle 0.6.2",
"redox_syscall", "redox_syscall 0.5.3",
"wasm-bindgen", "wasm-bindgen",
"web-sys", "web-sys",
"windows-sys 0.52.0", "windows-sys 0.52.0",
@ -3505,7 +3620,7 @@ dependencies = [
"backtrace", "backtrace",
"bytes", "bytes",
"libc", "libc",
"mio", "mio 1.0.1",
"pin-project-lite", "pin-project-lite",
"socket2", "socket2",
"tokio-macros", "tokio-macros",
@ -3653,6 +3768,20 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0" checksum = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0"
[[package]]
name = "tower-livereload"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57d7d9fecf1242d1c6a3cf8f7f3c2da94e6aac553bb7062ab6d03e16b9872fd0"
dependencies = [
"bytes",
"http",
"http-body",
"pin-project-lite",
"tokio",
"tower",
]
[[package]] [[package]]
name = "tower-service" name = "tower-service"
version = "0.3.2" version = "0.3.2"

View File

@ -47,6 +47,17 @@ Si vous souhaitez lancer les composants séparément, les indications de lanceme
- [app](crates/app/README.md) - [app](crates/app/README.md)
- [sesam-vitale](crates/sesam-vitale/README.md) - [sesam-vitale](crates/sesam-vitale/README.md)
## Rechargement automatique
Pour permettre de développer plus rapidement, il existe une librairie qui recompile automatiquement nos modifications en cours : [`cargo-watch`](https://github.com/watchexec/cargo-watch) permet de relancer une commande _Rust_ lorsqu'un fichier est modifié (example: `cargo run` --> `cargo watch -x run`).
La librairie ne fait pas partie des dépendances du projet, il faut donc l'installer avec la commande suivante :
```bash
cargo install cargo-watch
```
Le fichier [`.ignore`](./ignore) permet d'ignorer certains fichiers pour éviter de relancer la recompilation inutilement.
## Build ## Build
Packager le client desktop Packager le client desktop

View File

@ -7,7 +7,9 @@ edition = "2021"
askama = "0.12.1" askama = "0.12.1"
askama_axum = "0.4.0" askama_axum = "0.4.0"
axum = "0.7.5" axum = "0.7.5"
listenfd = "1.0.1"
notify = "6.1.1"
serde = { version = "1.0.204", features = ["derive"] } serde = { version = "1.0.204", features = ["derive"] }
tokio = { version = "1.39.1", features = ["macros", "rt-multi-thread"] } tokio = { version = "1.39.1", features = ["macros", "rt-multi-thread"] }
tower-http = { version = "0.5.2", features = ["fs"] } tower-http = { version = "0.5.2", features = ["fs"] }
tower-livereload = "0.9.3"

View File

@ -13,3 +13,28 @@
```bash ```bash
cargo run --bin app cargo run --bin app
``` ```
## Rechargement automatique (_auto-reload_)
Pour le projet `app`, nous utilisons en plus de `cargo-watch` ses librairies :
- [`systemfd`](https://github.com/mitsuhiko/systemfd) permet de redémarrer un serveur sans interrompre les connexions en cours, il transmet le descripteur de fichier du socket à une nouvelle instance du serveur (exemple: `cargo watch -x run` --> `systemfd --no-pid -s http::3000 -- cargo watch -x run`). Si le port est déjà pris il en prendra un autre.
- [`listenfd`](https://github.com/mitsuhiko/listenfd) permet, côté _Rust_, de démarrer un serveur en utilisant des connexions déjà ouvertes.
La librairie `systemfd` ne fait pas partie des dépendances du projet, il faut donc l'installer avec la commande suivante :
```bash
cargo install systemfd
```
Pour notre application voici la commande à lancer :
```bash
systemfd --no-pid -s http::3000 -- cargo watch -x 'run --bin app'
```
## Chargement à chaud (_livereload_)
Pour que notre navigateur rafraîchisse automatique notre page lorsque le serveur a été recompilé, nous utilisons la librairie [`tower-livereload`](https://github.com/leotaku/tower-livereload).
A chaque changement, que ça soit sur du code en _Rust_, _HTML_, _CSS_ ou _JS_ alors le navigateur va recharger entièrement la page.
En Rust, il n'existe pas encore d'outil de _Hot Reload_ complet et intégré comme on en trouve dans d'autres environnements de développement web, comme pour _Node.js_.

View File

@ -1,15 +1,48 @@
use ::app::get_router; use ::app::get_router;
use axum::http::Request;
use listenfd::ListenFd;
use notify::Watcher;
use std::env; use std::env;
use std::path::Path; use std::path::Path;
use tokio::net::TcpListener;
use tower_livereload::LiveReloadLayer;
fn not_htmx_predicate<T>(req: &Request<T>) -> bool {
!req.headers().contains_key("hx-request")
}
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let assets_path = Path::new(&manifest_dir).join("assets"); let assets_path = Path::new(&manifest_dir).join("assets");
let router = get_router(assets_path.as_path()); let templates_path = Path::new(&manifest_dir).join("templates");
// TODO: select port based on available port (or ask in CLI) let livereload = LiveReloadLayer::new();
let listener = tokio::net::TcpListener::bind("localhost:3000").await.unwrap(); let reloader = livereload.reloader();
println!("Listening on: http://{}", listener.local_addr().unwrap());
axum::serve(listener, router).await.unwrap(); let router =
get_router(assets_path.as_path()).layer(livereload.request_predicate(not_htmx_predicate));
let mut watcher = notify::recommended_watcher(move |_| reloader.reload()).unwrap();
watcher
.watch(&templates_path, notify::RecursiveMode::Recursive)
.unwrap();
let mut listenfd = ListenFd::from_env();
let listener = match listenfd.take_tcp_listener(0).unwrap() {
// if we are given a tcp listener on listen fd 0, we use that one
Some(listener) => {
listener.set_nonblocking(true).unwrap();
TcpListener::from_std(listener).unwrap()
}
// otherwise fall back to local listening
None => TcpListener::bind("localhost:3000").await.unwrap(),
};
println!("Listening on: http://{}", listener.local_addr().unwrap());
// Run the server with the router
axum::serve(listener, router.into_make_service())
.await
.unwrap();
} }

View File

@ -11,10 +11,10 @@ struct HelloResponse {
async fn hello() -> impl IntoResponse { async fn hello() -> impl IntoResponse {
HelloResponse { HelloResponse {
name: "Theo".to_string(), name: "Theo".to_string(),
}.into_response() }
.into_response()
} }
pub fn get_routes() -> Router { pub fn get_routes() -> Router {
Router::new() Router::new().route("/", routing::get(hello))
.route("/", routing::get(hello))
} }

View File

@ -25,7 +25,9 @@ impl MenuResponse {
fn get_classes(&self, is_current_item: &bool) -> String { fn get_classes(&self, is_current_item: &bool) -> String {
let common_classes = match self.mobile { let common_classes = match self.mobile {
true => "block border-l-4 py-2 pl-3 pr-4 text-base font-medium".to_string(), true => "block border-l-4 py-2 pl-3 pr-4 text-base font-medium".to_string(),
false => "inline-flex items-center border-b-2 px-1 pt-1 text-sm font-medium".to_string(), false => {
"inline-flex items-center border-b-2 px-1 pt-1 text-sm font-medium".to_string()
}
}; };
match (self.mobile, is_current_item) { match (self.mobile, is_current_item) {
(true, true) => common_classes + " border-indigo-500 bg-indigo-50 text-indigo-700", (true, true) => common_classes + " border-indigo-500 bg-indigo-50 text-indigo-700",
@ -51,10 +53,10 @@ async fn menu(Query(params): Query<MenuParameters>) -> impl IntoResponse {
current: false, current: false,
}, },
], ],
}.into_response() }
.into_response()
} }
pub fn get_routes() -> Router { pub fn get_routes() -> Router {
Router::new() Router::new().route("/menu", routing::get(menu))
.route("/menu", routing::get(menu))
} }

View File

@ -56,10 +56,10 @@ async fn menu(Query(params): Query<MenuParameters>) -> impl IntoResponse {
current: false, current: false,
}, },
], ],
}.into_response() }
.into_response()
} }
pub fn get_routes() -> Router { pub fn get_routes() -> Router {
Router::new() Router::new().route("/menu", routing::get(menu))
.route("/menu", routing::get(menu))
} }

View File

@ -16,7 +16,10 @@ fn main() {
// Add local lib directory to the linker search path (for def files and static libs) // Add local lib directory to the linker search path (for def files and static libs)
let static_lib_path = manifest_path.join("lib"); let static_lib_path = manifest_path.join("lib");
println!("cargo::rustc-link-search=native={}", static_lib_path.display()); println!(
"cargo::rustc-link-search=native={}",
static_lib_path.display()
);
// Add the SESAM_FSV_LIB_PATH to the linker search path // Add the SESAM_FSV_LIB_PATH to the linker search path
let fsv_lib_path = PathBuf::from(env::var("SESAM_FSV_LIB_PATH").unwrap()); let fsv_lib_path = PathBuf::from(env::var("SESAM_FSV_LIB_PATH").unwrap());
@ -31,6 +34,9 @@ fn main() {
} }
// Link the SESAM_FSV_SSVLIB dynamic library // Link the SESAM_FSV_SSVLIB dynamic library
println!("cargo::rustc-link-lib=dylib={}", env::var("SESAM_FSV_SSVLIB").unwrap()); println!(
"cargo::rustc-link-lib=dylib={}",
env::var("SESAM_FSV_SSVLIB").unwrap()
);
// TODO : try `raw-dylib` instead of `dylib` on Windows to avoid the need of the `lib` headers compiled from the `def` // TODO : try `raw-dylib` instead of `dylib` on Windows to avoid the need of the `lib` headers compiled from the `def`
} }