27 Commits

Author SHA1 Message Date
7912e9a516 chore(release): v0.3.2 2025-07-01 17:37:36 +02:00
568d126fc2 test: add imports to doc snippets 2025-07-01 17:36:36 +02:00
3ce4cbfad7 chore(release): v0.3.1 2025-02-12 16:53:28 +01:00
36fcc84881 feat: don't read DJANGO_SETTINGS_MODULE 2025-02-12 16:52:50 +01:00
c8b3a817f0 chore: correctly document env variables in README 2025-02-12 16:52:09 +01:00
f7737ea00d fix: dump from database db 2024-11-27 20:00:37 +01:00
f56965abc2 chore: add completion and configuration to readme 2024-11-27 18:48:20 +01:00
e7308bd5c6 feat: control default services via env vars
Read default postgres compose service name and default django compose
service name from env variables.

AHAB_POSTGRES_CONTAINER - defaults to `appserver`
AHAB_DJANGO_CONATINER - defaults to `postgresdb`

Default values are there for 100% backwards compatibility.
2024-11-27 18:13:12 +01:00
3077420db2 feat!: respect COMPOSE_FILE env and remove docker command
Read COMPOSE_FILE from env and use it if it is set. Default is still
docker/local/docker-compose.yaml.

BREAKING CHANGE: Removed docker subcommand. Added deprecation notice to
compose subcommand.
2024-10-25 09:37:13 +02:00
73a0b87c31 feat: swap println for eprintln or debug_eprintln
Unified expected output to always eprintln so outputs can be piped to
other processes. Added debug_eprintln and switched all occurances of
debug_println.
2024-10-25 09:03:49 +02:00
6fcf48ed61 feat: redirect pg_isready output to /dev/null
Fixed bug where restore commands were called inside pg_isready loop.
Made CommandBuilder::build public. Redirected stdout for pg_isready
calls to /dev/null via Stdio::null().
2023-11-27 20:58:28 +01:00
0b0ca06398 chore: update README with install info
Added install instructions to README; both normal and debug install.
2023-11-27 20:40:37 +01:00
98f02c1c08 feat: pg_isready in postgres import
Fixed issue where arguments passed to `compose stop` weren't passed to
the underlying command. Added pg_isready call between each command call
in restore script.
2023-11-27 20:40:24 +01:00
2754a3bb30 feat: compile time completion generation
Removed `completion` command in favor of compile time completion
generation. This tool will only be build from source for the foreseeable
future so this makes sense for now.
2023-08-09 14:45:07 +02:00
e061d6dc6c feat: add compose ps command
Ps is new command scoped under compose. It is just proxy to `docker
compose ps`.
2023-08-09 13:59:58 +02:00
b45cfd3e0a feat: add compose exec and compose bash commands
Exec is new command scoped under compose. It allows sending commands
directly into appserver container. I will make this
customizable/controllable in the future.
2023-06-15 19:58:43 +02:00
7bf76d3ff2 release: v0.3.0
Various qol improvements and custom CommandBuilder mark v0.3.0 release
2023-06-02 17:20:19 +02:00
316b37cd05 feat: custom command builder
Implemented custom command builder with nicer api suited for my needs.
Also returned error if there are no containers in
`scripts::postgres::get_containers`.
2023-06-02 17:18:25 +02:00
e3306c494d feat: prepulate command in make-command
Fixed bug where created command file didn't end with `.py` and
prepopulate created file with minimal example of django management command.
2023-06-02 17:16:15 +02:00
5d45eccfef feat: add django test command
Added django's manage.py test command as a shortcut
2023-06-02 17:15:39 +02:00
251826c048 feat: print $DJANGO_SETTINGS_MODULE when it's needed 2023-06-02 17:07:13 +02:00
63b4b60f9a fix: duplicated help message
Django subcommand had the same help message as compose.
2023-06-02 16:56:26 +02:00
55d4ae3f6f release: version 0.2.0
Command renamings and compltion generation marks v0.2.0 of `ahab`.
2023-05-27 13:32:46 +02:00
de5e6b4d10 feat: rename commands and remove aliases in favour of completion
BREAKING CHANGE: changed commands as follows
D -> Docker
Dc -> Compose
Dj -> Django
Pg -> Postgres
2023-05-27 13:30:09 +02:00
61e7556997 feat: add clap_complete for generating completion files
`ahab generate <shell>` can now be used to generte completion files for
this tool.
2023-05-27 13:28:05 +02:00
a9a5e401dc refactor: create library with simple entrypoint in main
Create a library entrypoint 'src/lib.rs' and refactor binary entrypoint
'src/main.rs' accordingly.
2023-05-27 12:52:10 +02:00
423badfe07 fix: all django management command related subcommands
We just called `manage` inside docker instead of
`exec appserver python manage.py`. Now we make assumption that django
app is running in docker-compose in service named `appserver`.

While fixing this bug we also refactored for `shell`, `makemigrations`
and `migrate` to all call `manage` under the hood to avoid repeating code.
2023-05-24 00:21:04 +02:00
18 changed files with 462 additions and 315 deletions

251
Cargo.lock generated
View File

@@ -1,36 +1,37 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
version = 4
[[package]]
name = "ahab"
version = "0.1.0"
version = "0.3.2"
dependencies = [
"anyhow",
"clap",
"clap_complete",
"dotenvy",
]
[[package]]
name = "anstream"
version = "0.3.2"
version = "0.6.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ca84f3628370c59db74ee214b3263d58f9aadd9b4fe7e711fd87dc452b7f163"
checksum = "23a1e53f0f5d86382dafe1cf314783b2044280f406e7e1506368220ad11b1338"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is-terminal",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.0"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41ed9a86bf92ae6580e0a31281f65a1b1d867c0cc68d5346e2ae128dddfa6a7d"
checksum = "8365de52b16c035ff4fcafe0092ba9390540e3e352870ac09933bebcaa2c8c56"
[[package]]
name = "anstyle-parse"
@@ -47,66 +48,61 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b"
dependencies = [
"windows-sys",
"windows-sys 0.48.0",
]
[[package]]
name = "anstyle-wincon"
version = "1.0.1"
version = "3.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "180abfa45703aebe0093f79badacc01b8fd4ea2e35118747e5811127f926e188"
checksum = "2109dbce0e72be3ec00bed26e6a7479ca384ad226efdd66db8fa2e3a38c83125"
dependencies = [
"anstyle",
"windows-sys",
"windows-sys 0.59.0",
]
[[package]]
name = "anyhow"
version = "1.0.71"
version = "1.0.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c7d0618f0e0b7e8ff11427422b64564d5fb0be1940354bfe2e0529b18a9d9b8"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "cc"
version = "1.0.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f"
checksum = "c042108f3ed77fd83760a5fd79b53be043192bb3b9dba91d8c574c0ada7850c8"
[[package]]
name = "clap"
version = "4.3.0"
version = "4.5.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93aae7a4192245f70fe75dd9157fc7b4a5bf53e88d30bd4396f7d8f9284d5acc"
checksum = "b97f376d85a664d5837dbae44bf546e6477a679ff6610010f17276f686d867e8"
dependencies = [
"clap_builder",
"clap_derive",
"once_cell",
]
[[package]]
name = "clap_builder"
version = "4.3.0"
version = "4.5.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f423e341edefb78c9caba2d9c7f7687d0e72e89df3ce3394554754393ac3990"
checksum = "19bc80abd44e4bed93ca373a0704ccbd1b710dc5749406201bb018272808dc54"
dependencies = [
"anstream",
"anstyle",
"bitflags",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.3.0"
name = "clap_complete"
version = "4.5.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "191d9573962933b4027f932c600cd252ce27a8ad5979418fe78e43c07996f27b"
checksum = "07a13ab5b8cb13dbe35e68b83f6c12f9293b2f601797b71bc9f23befdb329feb"
dependencies = [
"clap",
]
[[package]]
name = "clap_derive"
version = "4.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab"
dependencies = [
"heck",
"proc-macro2",
@@ -116,9 +112,9 @@ dependencies = [
[[package]]
name = "clap_lex"
version = "0.5.0"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2da6da31387c7e4ef160ffab6d5e7f00c42626fe39aea70a7b0f1773f7dd6c1b"
checksum = "1462739cb27611015575c0c11df5df7601141071f07518d56fcc1be504cbec97"
[[package]]
name = "colorchoice"
@@ -132,85 +128,23 @@ version = "0.15.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
[[package]]
name = "errno"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a"
dependencies = [
"errno-dragonfly",
"libc",
"windows-sys",
]
[[package]]
name = "errno-dragonfly"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf"
dependencies = [
"cc",
"libc",
]
[[package]]
name = "heck"
version = "0.4.1"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hermit-abi"
version = "0.3.1"
name = "is_terminal_polyfill"
version = "1.70.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286"
[[package]]
name = "io-lifetimes"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c66c74d2ae7e79a5a8f7ac924adbe38ee42a859c6539ad869eb51f0b52dc220"
dependencies = [
"hermit-abi",
"libc",
"windows-sys",
]
[[package]]
name = "is-terminal"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adcf93614601c8129ddf72e2d5633df827ba6551541c6d8c59520a371475be1f"
dependencies = [
"hermit-abi",
"io-lifetimes",
"rustix",
"windows-sys",
]
[[package]]
name = "libc"
version = "0.2.144"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b00cc1c228a6782d0f076e7b232802e0c5689d41bb5df366f2a6b6621cfdfe1"
[[package]]
name = "linux-raw-sys"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519"
[[package]]
name = "once_cell"
version = "1.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3"
checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
[[package]]
name = "proc-macro2"
version = "1.0.58"
version = "1.0.89"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa1fb82fc0c281dd9671101b66b771ebbe1eaf967b96ac8740dcba4b70005ca8"
checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e"
dependencies = [
"unicode-ident",
]
@@ -224,25 +158,11 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "rustix"
version = "0.37.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acf8729d8542766f1b2cf77eb034d52f40d375bb8b615d0b147089946e16613d"
dependencies = [
"bitflags",
"errno",
"io-lifetimes",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]]
name = "strsim"
version = "0.10.0"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "syn"
@@ -273,7 +193,16 @@ version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
dependencies = [
"windows-targets",
"windows-targets 0.48.0",
]
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
@@ -282,13 +211,29 @@ version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
"windows_aarch64_gnullvm 0.48.0",
"windows_aarch64_msvc 0.48.0",
"windows_i686_gnu 0.48.0",
"windows_i686_msvc 0.48.0",
"windows_x86_64_gnu 0.48.0",
"windows_x86_64_gnullvm 0.48.0",
"windows_x86_64_msvc 0.48.0",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
]
[[package]]
@@ -297,38 +242,86 @@ version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"

View File

@@ -2,15 +2,21 @@
name = "ahab"
description = "docker cli wrapper"
readme = "README.md"
version = "0.1.0"
version = "0.3.2"
edition = "2021"
license = "MIT"
authors = ["Matej Janežič <janezic.mj@gmail.com>"]
repository = "https://github.com/janezicmatej/ahab.git"
build = "build.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = { version = "4.3.0", features = ["derive"] }
anyhow = "1.0.71"
clap = { version = "4.5.20", features = ["derive"] }
# clap_complete = "4.5.35"
anyhow = "1.0.91"
dotenvy = "0.15.7"
[build-dependencies]
clap = { version = "4.5.20", features = ["derive"] }
clap_complete = "4.5.35"

View File

@@ -1 +1,25 @@
# ahab
## installing
You will need rust installed. Clone repo and run:
```bash
cargo install --path .
```
To print underlying commands build with `debug` flag.
```bash
cargo install --path . --debug
```
## shell completion
Completion files are generated **during build process** in `target/*/build/*/out/*`. Depending on your shell of choice move generated file to correct place in you file system.
## configuration
Currently `ahab` respects three environment variables.
- `COMPOSE_FILE`: control which docker-compose file is used - defaults to `docker/local/docker-compose.yaml`
- `AHAB_DJANGO_CONTAINER`: control which compose service is used for sending django commands - defaults to `appserver`
- `AHAB_POSTGRES_CONTAINER`: control which compose service is used for sending postgres commands - defaults to `postgresdb`

22
build.rs Normal file
View File

@@ -0,0 +1,22 @@
use clap::{CommandFactory, ValueEnum};
use clap_complete::{generate_to, Shell};
use std::{env, io::Error};
include!("src/cli/mod.rs");
fn main() -> Result<(), Error> {
let outdir = match env::var_os("OUT_DIR") {
None => return Ok(()),
Some(outdir) => outdir,
};
let mut cmd = ahab::Ahab::command();
for shell in Shell::value_variants() {
let path = generate_to(*shell, &mut cmd, "ahab", &outdir)?;
println!("cargo:warning=completion file is generated: {path:?}");
}
Ok(())
}

View File

@@ -1,4 +1,4 @@
use super::{Django, Docker, DockerCompose, Postgres};
use super::{Django, DockerCompose, Postgres};
use clap::{Parser, Subcommand};
/// A program for interacting with various dockerized applications.
@@ -11,26 +11,20 @@ pub struct Ahab {
#[derive(Debug, Subcommand)]
pub enum Commands {
/// Docker related subcommands
D {
#[command(subcommand)]
command: Docker,
},
/// Docker compose related subcommands
Dc {
Compose {
#[command(subcommand)]
command: DockerCompose,
},
/// Docker compose related subcommands
Dj {
/// Django related subcommands
Django {
#[command(subcommand)]
command: Django,
},
/// Postgres related subcommands
Pg {
Postgres {
#[command(subcommand)]
command: Postgres,
},

View File

@@ -7,7 +7,6 @@ use clap::Parser;
#[derive(Parser, Debug)]
pub enum Django {
/// Prepare empty management command 'command' in app 'app'.
#[clap(alias("mc"))]
MakeCommand {
#[arg(value_enum)]
app: PathBuf,
@@ -16,24 +15,23 @@ pub enum Django {
},
/// Run Django's manage.py makemigrations.
#[clap(alias("mm"))]
Makemigrations,
/// Pass arguments to Django's manage.py.
#[clap(alias("m"))]
Manage {
#[arg(value_enum)]
rest: Vec<String>,
},
/// Run Django's manage.py migrate.
#[clap(alias("mg"))]
Migrate {
#[arg(value_enum)]
rest: Vec<String>,
},
/// Run Django's manage.py shell.
#[clap(alias("s"))]
Shell,
/// Run Django's manage.py test.
Test,
}

View File

@@ -1,8 +0,0 @@
use clap::Parser;
#[derive(Parser, Debug)]
pub enum Docker {
/// Stop all containers via `docker stop $(docker ps -q)`
#[clap(alias("sa"))]
StopAll,
}

View File

@@ -5,31 +5,36 @@ use clap::Subcommand;
/// Wraper for docker compose; autodiscover compose file and source .env file.
#[derive(Subcommand, Debug)]
pub enum DockerCompose {
/// Start bash session inside container
Bash,
/// Build containers.
#[clap(alias("b"))]
Build,
/// Down containers.
#[clap(alias("d"))]
Down,
/// Exec command inside container.
Exec {
#[arg(value_enum)]
rest: Vec<String>,
},
/// Print services
Ps,
/// Stop, build and start containers.
#[clap(alias("rb"))]
Rebuild,
/// Stop and start containers.
#[clap(alias("rs"))]
Restart,
/// Start containers.
#[clap(alias("st"))]
Start,
/// Stop containers.
#[clap(alias("s"))]
Stop,
/// Up containers.
#[clap(alias("u"))]
Up,
}

View File

@@ -1,11 +1,9 @@
mod ahab;
mod django;
mod docker;
mod docker_compose;
mod postgres;
pub use ahab::{Ahab, Commands};
pub use django::Django;
pub use docker::Docker;
pub use docker_compose::DockerCompose;
pub use postgres::Postgres;

View File

@@ -5,14 +5,12 @@ use clap::Subcommand;
#[derive(Subcommand, Debug)]
pub enum Postgres {
/// Import dump via pg_restore
#[clap(alias("i"))]
Import {
#[arg(value_enum)]
path: PathBuf,
},
/// Dump via pg_dump with format=c
#[clap(alias("d"))]
Dump {
#[arg(value_enum)]
path: PathBuf,

101
src/command_builder.rs Normal file
View File

@@ -0,0 +1,101 @@
use anyhow::{anyhow, Context, Result};
use std::{
collections::VecDeque,
env,
ffi::OsStr,
fmt::Display,
fs::{File, OpenOptions},
os::unix::process::CommandExt,
path::PathBuf,
process::{Child, Command, Stdio},
};
use crate::debug_eprintln;
pub struct Args(Vec<String>);
impl From<&str> for Args {
fn from(value: &str) -> Self {
Self(Vec::from_iter(value.split_whitespace().map(String::from)))
}
}
impl From<&String> for Args {
fn from(value: &String) -> Self {
Self(Vec::from_iter(value.split_whitespace().map(String::from)))
}
}
impl From<&[String]> for Args {
fn from(value: &[String]) -> Self {
Self(value.to_vec())
}
}
fn get_compose_file() -> Result<String> {
let cf = env::var("COMPOSE_FILE")?;
Ok(cf)
}
#[derive(Default)]
pub struct CommandBuilder {
args: Vec<String>,
}
impl Display for CommandBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.args.join(" "))
}
}
impl CommandBuilder {
pub fn new(args: &str) -> Self {
Self::default().args("docker")
}
pub fn docker() -> Self {
Self::default().args("docker")
}
pub fn docker_compose() -> Self {
let cf =
get_compose_file().unwrap_or_else(|_| "docker/local/docker-compose.yaml".to_string());
Self::default().args("docker compose -f").args(&cf)
}
pub fn args<T>(mut self, args: T) -> Self
where
Args: From<T>,
{
self.args.extend(Args::from(args).0);
self
}
pub fn build(self) -> Result<Command> {
debug_eprintln!("running `{self}`");
let (first, rest) = self.args.split_first().context("empty args")?;
let mut command = Command::new(first);
command.args(rest);
Ok(command)
}
pub fn exec_get_stdout(mut self) -> Result<String> {
Ok(String::from_utf8(self.build()?.output()?.stdout)?)
}
pub fn exec(mut self) -> Result<()> {
self.build()?.spawn()?.wait()?;
Ok(())
}
pub fn spawn(mut self) -> Result<(Child)> {
Ok(self.build()?.spawn()?)
}
pub fn exec_redirect_stdout(mut self, stdio: Stdio) -> Result<()> {
self.build()?.stdout(stdio).spawn()?.wait()?;
Ok(())
}
}

24
src/lib.rs Normal file
View File

@@ -0,0 +1,24 @@
#![allow(unused)]
use std::{
fs::{File, OpenOptions},
path::PathBuf,
};
pub mod cli;
pub mod command_builder;
pub mod scripts;
// NOTE: stolen from https://docs.rs/debug_print/latest/debug_print/
#[macro_export]
macro_rules! debug_eprintln {
($($arg:tt)*) => (#[cfg(debug_assertions)] eprintln!($($arg)*));
}
fn safe_create_file(path: PathBuf) -> Result<File, std::io::Error> {
OpenOptions::new().write(true).create_new(true).open(path)
}
fn create_file(path: PathBuf) -> Result<File, std::io::Error> {
OpenOptions::new().write(true).create(true).open(path)
}

View File

@@ -1,44 +1,45 @@
#![allow(unused)]
mod cli;
mod scripts;
use ahab::{cli, scripts};
use anyhow::Result;
use clap::Parser;
use std::env;
fn main() -> Result<()> {
// always load dotenv on start
dotenvy::dotenv().ok();
// TODO: (matej) some prints about project
// eg: DJANGO_SETTINGS_MODULE for django projects, used docker-compose, etc.
let args = cli::Ahab::parse();
match args.command {
cli::Commands::D { command } => match command {
cli::Docker::StopAll => scripts::docker::stop_all(),
},
cli::Commands::Dc { command } => match command {
cli::Commands::Compose { command } => {
eprintln!("DEPRECATION NOTICE: this is deprecated in favor of docker compose COMPOSE_FILE env");
match command {
cli::DockerCompose::Bash => scripts::docker_compose::bash(),
cli::DockerCompose::Build => scripts::docker_compose::build(),
cli::DockerCompose::Down => scripts::docker_compose::down(),
cli::DockerCompose::Exec { rest } => scripts::docker_compose::exec(&rest),
cli::DockerCompose::Ps => scripts::docker_compose::ps(),
cli::DockerCompose::Rebuild => scripts::docker_compose::rebuild(),
cli::DockerCompose::Restart => scripts::docker_compose::restart(),
cli::DockerCompose::Start => scripts::docker_compose::start(None),
cli::DockerCompose::Stop => scripts::docker_compose::stop(),
cli::DockerCompose::Up => scripts::docker_compose::up(),
},
cli::Commands::Dj { command } => match command {
}
}
cli::Commands::Django { command } => match command {
cli::Django::MakeCommand { app, name } => scripts::django::make_command(&app, &name),
cli::Django::Makemigrations => scripts::django::makemigrations(),
cli::Django::Manage { rest } => scripts::django::manage(&rest),
cli::Django::Migrate { rest } => scripts::django::migrate(&rest),
cli::Django::Shell => scripts::django::shell(),
cli::Django::Test => scripts::django::test(),
},
cli::Commands::Pg { command } => match command {
cli::Postgres::Import { path } => scripts::postgres::import(&path),
cli::Postgres::Dump { path } => scripts::postgres::dump(&path),
},
cli::Commands::Postgres { command } => {
let db_container =
std::env::var("AHAB_POSTGRES_CONTAINER").unwrap_or("postgresdb".to_string());
match command {
cli::Postgres::Import { path } => scripts::postgres::import(&db_container, &path),
cli::Postgres::Dump { path } => scripts::postgres::dump(&db_container, &path),
}
}
}
}

View File

@@ -1,14 +1,20 @@
use crate::scripts::{create_file, safe_create_file};
use super::DockerCommand;
use anyhow::{anyhow, Result};
use std::env;
use std::fs::create_dir;
use std::io::Write;
use std::path::{Path, PathBuf};
fn get_django_settings_module() -> Result<String> {
Ok(env::var("DJANGO_SETTINGS_MODULE")?)
}
use anyhow::{anyhow, Result};
use crate::command_builder::CommandBuilder;
use crate::{create_file, safe_create_file};
const DEBUG_TEMPLATE: &str = r#"from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
pass
"#;
pub fn make_command(app: &PathBuf, name: &str) -> Result<()> {
let app_name = app.to_string_lossy();
@@ -19,7 +25,7 @@ pub fn make_command(app: &PathBuf, name: &str) -> Result<()> {
return Err(anyhow!("directory {app_name} does not exist"));
}
println!("found app {app_name}");
eprintln!("found app {app_name}");
let management_dir = app_dir.join("management");
@@ -28,7 +34,7 @@ pub fn make_command(app: &PathBuf, name: &str) -> Result<()> {
create_dir(&management_dir)?;
create_file(management_dir.join("__init__.py"))?;
println!("created module {app_name}.management")
eprintln!("created module {app_name}.management")
};
let commands_dir = management_dir.join("commands");
@@ -38,36 +44,39 @@ pub fn make_command(app: &PathBuf, name: &str) -> Result<()> {
create_dir(&commands_dir)?;
create_file(commands_dir.join("__init__.py"))?;
println!("created module {app_name}.management.commands")
eprintln!("created module {app_name}.management.commands")
};
safe_create_file(commands_dir.join(name))?;
println!("created command {app_name}.management.commands.{name}");
let mut file = safe_create_file(commands_dir.join(format!("{name}.py")))?;
file.write_all(DEBUG_TEMPLATE.as_bytes())?;
eprintln!("created command {app_name}.management.commands.{name}");
Ok(())
}
pub fn makemigrations() -> Result<()> {
let dsm = get_django_settings_module()?;
let command = format!("manage makemigrations --settings={dsm}");
DockerCommand::docker_compose().args(&command).spawn_wait()
pub fn manage(rest: &[String]) -> Result<()> {
let container = env::var("AHAB_DJANGO_CONTAINER").unwrap_or("appserver".to_string());
let joined = rest.join(" ");
let command = format!("run --rm {container} python manage.py {joined}");
CommandBuilder::docker_compose().args(&command).exec()
}
pub fn manage(rest: &[String]) -> Result<()> {
let dsm = get_django_settings_module()?;
let joined = rest.join(" ");
let command = format!("manage {joined} --settings={dsm}");
DockerCommand::docker_compose().args(&command).spawn_wait()
// shortcuts
pub fn makemigrations() -> Result<()> {
manage(&["makemigrations".to_string()])
}
pub fn migrate(rest: &[String]) -> Result<()> {
let dsm = get_django_settings_module()?;
let joined = rest.join(" ");
let command = format!("manage migrate {joined} --settings={dsm}");
DockerCommand::docker_compose().args(&command).spawn_wait()
let mut full_rest = vec!["migrate".to_string()];
full_rest.extend_from_slice(rest);
manage(&full_rest)
}
pub fn shell() -> Result<()> {
let dsm = get_django_settings_module()?;
let command = format!("manage shell --settings={dsm}");
DockerCommand::docker_compose().args(&command).spawn_wait()
manage(&["shell".to_string()])
}
pub fn test() -> Result<()> {
manage(&["test".to_string()])
}

View File

@@ -1,14 +1,15 @@
use super::DockerCommand;
use anyhow::Result;
use crate::command_builder::CommandBuilder;
pub fn stop_all() -> Result<()> {
let running_containers = DockerCommand::docker().args("ps -q").stdout()?;
let running_containers = CommandBuilder::docker().args("ps -q").exec_get_stdout()?;
if running_containers.is_empty() {
return Ok(());
}
DockerCommand::docker()
CommandBuilder::docker()
.args(&format!("stop {running_containers}"))
.spawn_wait()
.exec()
}

View File

@@ -1,42 +1,61 @@
use super::DockerCommand;
use anyhow::Result;
use crate::command_builder::CommandBuilder;
// simple commands
pub fn build() -> Result<()> {
DockerCommand::docker_compose().args("build").spawn_wait()
CommandBuilder::docker_compose().args("build").exec()
}
pub fn down() -> Result<()> {
DockerCommand::docker_compose().args("down").spawn_wait()
CommandBuilder::docker_compose().args("down").exec()
}
pub fn exec(rest: &[String]) -> Result<()> {
let container = std::env::var("AHAB_DJANGO_CONTAINER").unwrap_or("appserver".to_string());
CommandBuilder::docker_compose()
.args("exec")
.args(&container)
.args(rest)
.exec()
}
pub fn ps() -> Result<()> {
CommandBuilder::docker_compose().args("ps").exec()
}
/// Start containers via `docker compose start`. Optionally pass containers to be started.
/// ```
/// # use ahab::scripts::docker_compose::start;
/// start(None);
/// ```
/// is roughly the same as
/// `docker compose --env-file ./.env -f docker/local/docker-compose.yaml up start`
pub fn start(containers: Option<&str>) -> Result<()> {
let args = format!("start {}", containers.unwrap_or(""));
DockerCommand::docker_compose().args("start").spawn_wait()
CommandBuilder::docker_compose().args(&args).exec()
}
pub fn stop() -> Result<()> {
DockerCommand::docker_compose().args("stop").spawn_wait()
CommandBuilder::docker_compose().args("stop").exec()
}
pub fn up() -> Result<()> {
DockerCommand::docker_compose().args("up -d").spawn_wait()
CommandBuilder::docker_compose().args("up -d").exec()
}
// shortcuts
pub fn bash() -> Result<()> {
exec(&["bash".to_string()])
}
pub fn rebuild() -> Result<()> {
stop()?;
build()?;
start(None)
up()
}
pub fn restart() -> Result<()> {
stop()?;
start(None)
up()
}

View File

@@ -2,63 +2,3 @@ pub mod django;
pub mod docker;
pub mod docker_compose;
pub mod postgres;
use std::{
ffi::OsStr,
fs::{File, OpenOptions},
path::PathBuf,
process::{Command, Stdio},
};
use anyhow::{Context, Result};
struct DockerCommand {
command: Command,
}
impl DockerCommand {
fn new<T>(program: T) -> Self
where
T: AsRef<OsStr>,
{
DockerCommand {
command: Command::new(program),
}
}
fn docker() -> Self {
Self::new("docker")
}
fn docker_compose() -> Self {
Self::new("docker").args("compose -f docker/local/docker-compose.yaml")
}
fn args(mut self, args: &str) -> Self {
self.command.args(args.split_whitespace());
self
}
fn stdout(mut self) -> Result<String> {
Ok(String::from_utf8(self.command.output()?.stdout)?)
}
fn spawn_wait(mut self) -> Result<()> {
self.command.spawn()?.wait()?;
Ok(())
}
fn write_stdout(mut self, stdio: Stdio) -> Result<()> {
self.command.stdout(stdio);
self.spawn_wait()?;
Ok(())
}
}
fn safe_create_file(path: PathBuf) -> Result<File, std::io::Error> {
OpenOptions::new().write(true).create_new(true).open(path)
}
fn create_file(path: PathBuf) -> Result<File, std::io::Error> {
OpenOptions::new().write(true).create(true).open(path)
}

View File

@@ -1,25 +1,33 @@
use super::{docker_compose, DockerCommand};
use anyhow::{Context, Result};
use anyhow::{anyhow, Context, Result};
use std::{
fs::File,
path::{Path, PathBuf},
process::Stdio,
thread,
time::Duration,
};
fn get_containers() -> Result<[String; 2]> {
use super::docker_compose;
use crate::{command_builder::CommandBuilder, debug_eprintln};
fn get_containers(container: &str) -> Result<[String; 2]> {
// get db container
// FIX: we assume we are running db in service named "postgresbd"
let db_container = DockerCommand::docker_compose()
.args("ps -q postgresdb")
.stdout()?
let db_container = CommandBuilder::docker_compose()
.args("ps -q")
.args(container)
.exec_get_stdout()?
.trim()
.to_string();
let no_result = db_container.is_empty();
if no_result {
return Err(anyhow!("no container"));
}
// get all containers and filter out db container
let app_containers = DockerCommand::docker_compose()
let app_containers = CommandBuilder::docker_compose()
.args("ps -q")
.stdout()?
.exec_get_stdout()?
.split_whitespace()
.filter(|x| x != &db_container)
.collect::<Vec<&str>>()
@@ -28,46 +36,60 @@ fn get_containers() -> Result<[String; 2]> {
Ok([db_container, app_containers])
}
pub fn import(file: &Path) -> Result<()> {
let [db_container, app_containers] = get_containers()?;
pub fn import(container: &str, file: &Path) -> Result<()> {
let [db_container, app_containers] = get_containers(container)?;
let dump_file = file.to_string_lossy();
println!("stopping all containers");
eprintln!("stopping all containers");
docker_compose::stop()?;
println!("starting db container");
docker_compose::start(Some(&db_container))?;
eprintln!("starting db container");
docker_compose::start(Some(container))?;
println!("restoring database");
eprintln!("restoring database");
let commands = [
format!("cp {dump_file} {db_container}:/tmp/dbdump"),
format!("exec {db_container} dropdb -U db db"),
format!("exec {db_container} createdb -U db -E utf8 -T template0 db"),
format!("exec {db_container} pg_restore -U db --dbname=db /tmp/dbdump"),
];
for command in commands {
DockerCommand::docker().args(&command).spawn_wait()?;
debug_eprintln!("waiting until pg_isready");
while !CommandBuilder::docker()
.args(&format!(
"exec {db_container} pg_isready -h {container} -p 5432 -U db",
))
.build()?
.stdout(Stdio::null())
.spawn()?
.wait()?
.success()
{
thread::sleep(Duration::from_secs(1));
}
CommandBuilder::docker().args(&command).exec()?;
}
println!("restarting containers");
eprintln!("restarting containers");
docker_compose::stop()?;
docker_compose::up()?;
Ok(())
}
pub fn dump(file: &PathBuf) -> Result<()> {
let [db_container, _] = get_containers()?;
pub fn dump(container: &str, file: &PathBuf) -> Result<()> {
let [db_container, _] = get_containers(container)?;
println!("dumping to local file {}", file.to_string_lossy());
eprintln!("dumping to local file {}", file.to_string_lossy());
let file = File::create(file)?;
let stdout = Stdio::from(file);
let command = format!("exec {db_container} pg_dump -U db --format=c db");
DockerCommand::docker()
CommandBuilder::docker()
.args(&command)
.write_stdout(stdout)?;
.exec_redirect_stdout(stdout)?;
Ok(())
}