Compare commits

...

34 Commits
v0.2.2 ... main

Author SHA1 Message Date
Dmitriy Pleshevskiy be61316444
nix: fix overlays 2022-11-14 14:12:45 +03:00
Dmitriy Pleshevskiy 9eebd41db0
nix: use colored version by default 2022-11-12 17:07:01 +03:00
Dmitriy Pleshevskiy f4d4d46390
doc: update rules in readme 2022-11-12 17:06:43 +03:00
Dmitriy Pleshevskiy 4f583c160d
doc: update docker readme 2022-11-12 17:06:19 +03:00
Dmitriy Pleshevskiy 1f9e1d0e9e
bump vnetod version 2022-11-12 16:56:08 +03:00
Dmitriy Pleshevskiy c4e30fb179
cli: polish help output 2022-11-12 16:53:32 +03:00
Dmitriy Pleshevskiy 542d7f1d5c
nix: use colored version for docker 2022-11-12 16:37:16 +03:00
Dmitriy Pleshevskiy 8f81bddeaa
cli: add message for dry-run option 2022-11-12 16:36:53 +03:00
Dmitriy Pleshevskiy bbd1d47ba5
cli: add color option 2022-11-12 16:25:35 +03:00
Dmitriy Pleshevskiy 4e9ea6c683
add colors 2022-11-10 00:29:28 +03:00
Dmitriy Pleshevskiy 2be25a330f
domain: add optional on_line callback 2022-11-08 00:07:21 +03:00
Dmitriy Pleshevskiy 25d28531a1
cli: fallback to environment variable 2022-11-07 23:41:52 +03:00
Dmitriy Pleshevskiy 6eddd4c2a0
nix: use overlays instead of deprecated overlay 2022-11-07 23:38:51 +03:00
Dmitriy Pleshevskiy 7983beaea3
chore: change nix version format 2022-11-07 23:36:54 +03:00
Dmitriy Pleshevskiy 5f0c94af77
chore: change email 2022-11-07 23:29:25 +03:00
Dmitriy Pleshevskiy dc66d1a643
nix: move overlay to the top level 2022-09-25 17:02:16 +03:00
Dmitriy Pleshevskiy 1f57ca0c97
chore: update lock 2022-09-18 23:37:35 +03:00
Dmitriy Pleshevskiy 97b2897edc
bump version 2022-09-18 23:36:25 +03:00
Dmitriy Pleshevskiy ac3f245a1c
build docker via nix 2022-09-18 23:34:38 +03:00
Dmitriy Pleshevskiy 21e9e89de2
nix: add overlays to flake 2022-09-18 17:35:14 +03:00
Dmitriy Pleshevskiy 38be5079ff
nix: don't use naersik to build package 2022-09-18 17:23:59 +03:00
Dmitriy Pleshevskiy c0b010e279
deps/clap: disable default features...
- color - moved to a feature . To enable install vnetod with
- suggestions
2022-08-02 15:53:29 +03:00
Dmitriy Pleshevskiy 570a39734b
doc: update header 2022-08-02 15:41:38 +03:00
Dmitriy Pleshevskiy 6095b4cd3c
doc: add contact information 2022-08-02 15:13:50 +03:00
Dmitriy Pleshevskiy b67662f6ac
bump version 2022-08-02 11:56:56 +03:00
Dmitriy Pleshevskiy ca299ad81d
add help for each argument 2022-08-02 11:43:42 +03:00
Dmitriy Pleshevskiy 1a6dfb8d46
add dry-run option
Closes #2
2022-08-02 11:32:12 +03:00
Dmitriy Pleshevskiy 146c0697f2
add section info struct with computed values
Closes #13
2022-08-02 11:10:03 +03:00
Dmitriy Pleshevskiy 8f786cfd36
add support of comments
Closes #5
2022-08-02 00:07:44 +03:00
Dmitriy Pleshevskiy c6a7217ebd
docker: add cache to dockerfile
Closes #11
2022-08-01 23:26:44 +03:00
Dmitriy Pleshevskiy 6b23168d84
doc: fix copying url 2022-08-01 16:35:34 +03:00
Dmitriy Pleshevskiy e8f17add36
add docker hub readme 2022-08-01 16:28:04 +03:00
Dmitriy Pleshevskiy 73dd2d4883
doc: add missed -f flag to the command 2022-08-01 12:49:52 +03:00
Dmitriy Pleshevskiy 925f446cb1
add missed GPL header to each file 2022-08-01 00:26:38 +03:00
21 changed files with 398 additions and 190 deletions

View File

@ -1,4 +0,0 @@
/target
.env*
!.envrc

1
.envrc
View File

@ -1 +0,0 @@
use flake

7
.gitignore vendored
View File

@ -1,4 +1,11 @@
# build
/target
/result
# environments
.env*
!.env.example
# direnv
.envrc
.direnv

11
Cargo.lock generated
View File

@ -37,7 +37,6 @@ dependencies = [
"clap_lex",
"indexmap",
"once_cell",
"strsim",
"termcolor",
"textwrap",
]
@ -155,12 +154,6 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "syn"
version = "1.0.98"
@ -201,9 +194,11 @@ checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "vnetod"
version = "0.1.0"
version = "0.4.0"
dependencies = [
"atty",
"clap",
"termcolor",
]
[[package]]

View File

@ -1,9 +1,10 @@
[package]
name = "vnetod"
description = "Dotenv state switcher"
version = "0.2.2"
description = "Are you still switching sections in your dotenv file manually? Try this dotenv section switcher"
version = "0.4.0"
edition = "2021"
license = "GPL-3.0+"
homepage = "https://github.com/pleshevskiy/vnetod/discussions"
repository = "https://git.pleshevski.ru/pleshevskiy/vnetod.git"
keywords = ["env", "dotenv", "switcher", "change"]
categories = ["command-line-interface", "config", "development-tools"]
@ -11,6 +12,9 @@ categories = ["command-line-interface", "config", "development-tools"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = { version = "3.2.15", features = ["derive"] }
clap = { version = "3.2.15", default-features = false, features = ["std", "env", "derive"] }
atty = { version = "0.2.14", optional = true }
termcolor = { version = "1.1.3", optional = true }
[features]
color = ["clap/color", "dep:atty", "dep:termcolor"]

View File

@ -1,16 +0,0 @@
FROM rust:1.62.0-slim-buster
WORKDIR /app
COPY Cargo.* ./
COPY ./src ./src
RUN cargo install --bin vnetod --path . \
&& rm -rf ./src Cargo.*
VOLUME ["/data"]
WORKDIR /data
ENTRYPOINT ["/usr/local/cargo/bin/vnetod"]

View File

@ -1,17 +1,20 @@
# vnetod
# vnetod*
Dotenv state switcher
<small><strong>*</strong> inverted word "dotenv"</small>
You can create many states in your `.env` and switch between them.
Are you still switching sections in your dotenv file manually? Try this dotenv
section switcher!
You can create many sections in your `.env` and switch between them.
Rules:
- State name starts on a new line with `###` symbols (Ex. `### local`)
- State name can contain multiple comma-separated sections (Ex.
- Section name starts on a new line with `###` symbols (Ex. `### local`)
- Section can contain multiple comma-separated names (Ex.
`### local,staging`)
- Each section may specify a namespace (Ex. `### debug:on,dev:on`). If a section
doesn't contain a namespace, it's a global namespace.
- State ends if line is empty or contains a new state name.
- Each section name may specify a namespace (Ex. `### debug:on,dev:on`). If a
section doesn't contain a namespace, it's a global namespace.
- Section ends if line is empty or contains a new section name.
You can see the [full example].
@ -34,7 +37,7 @@ behavior with the `-f` (`--file`) flag.
```sh
cp .env.example .env.properties
vnetod .env.properties local
vnetod -f .env.properties local
```
And you can also change the output file with the `-o` (`--output`) flag, if you
@ -82,10 +85,17 @@ docker run --rm -it -v $PWD:/data pleshevskiy/vnetod --help
nix run git+https://git.pleshevski.ru/pleshevskiy/vnetod -- --help
```
# Contact me
- [send feedback](https://github.com/pleshevskiy/vnetod/discussions)
- [make an issue](https://github.com/pleshevskiy/vnetod/issues)
- matrix: @pleshevskiy:matrix.org
- email: dmitriy@pleshevski.ru
# License
GNU General Public License v3.0 or later
See [COPYING](./COPYING) to see the full text.
See [COPYING] to see the full text.
[COPYING]: https://git.pleshevski.ru/pleshevskiy/vnetod/src/branch/main/COPYING

38
docker/README.md Normal file
View File

@ -0,0 +1,38 @@
# Supported tags
- latest
- 0.4
# vnetod*
<small><strong>*</strong> inverted word "dotenv"</small>
Are you still switching sections in your dotenv file manually? Try this dotenv
section switcher!
You can create many sections in your `.env` and switch between them.
Rules:
- Section name starts on a new line with `###` symbols (Ex. `### local`)
- Section can contain multiple comma-separated names (Ex.
`### local,staging`)
- Each section name may specify a namespace (Ex. `### debug:on,dev:on`). If a
section doesn't contain a namespace, it's a global namespace.
- Section ends if line is empty or contains a new section name.
# Usage
```sh
docker run --rm -it -v $PWD:/data pleshevskiy/vnetod -f .env.example -o .env staging db:local debug:on
```
For more details see [the repo](https://git.pleshevski.ru/pleshevskiy/vnetod)
# License
GNU General Public License v3.0 or later
See [COPYING] to see the full text.
[COPYING]: https://git.pleshevski.ru/pleshevskiy/vnetod/src/branch/main/COPYING

View File

@ -1,39 +1,21 @@
{
"nodes": {
"naersk": {
"inputs": {
"nixpkgs": "nixpkgs"
},
"flake-utils": {
"locked": {
"lastModified": 1655042882,
"narHash": "sha256-9BX8Fuez5YJlN7cdPO63InoyBy7dm3VlJkkmTt6fS1A=",
"owner": "nix-community",
"repo": "naersk",
"rev": "cddffb5aa211f50c4b8750adbec0bbbdfb26bb9f",
"lastModified": 1667395993,
"narHash": "sha256-nuEHfE/LcWyuSWnS8t12N1wc105Qtau+/OdUAjtQ0rA=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "5aed5285a952e0b949eb3ba02c12fa4fcfef535f",
"type": "github"
},
"original": {
"owner": "nix-community",
"ref": "master",
"repo": "naersk",
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1659190188,
"narHash": "sha256-LudYrDFPFaQMW0l68TYkPWRPKmqpxIFU1nWfylIp9AQ=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "a3fddd46a7f3418d7e3940ded94701aba569161d",
"type": "github"
},
"original": {
"id": "nixpkgs",
"type": "indirect"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1659190188,
"narHash": "sha256-LudYrDFPFaQMW0l68TYkPWRPKmqpxIFU1nWfylIp9AQ=",
@ -51,24 +33,8 @@
},
"root": {
"inputs": {
"naersk": "naersk",
"nixpkgs": "nixpkgs_2",
"utils": "utils"
}
},
"utils": {
"locked": {
"lastModified": 1656928814,
"narHash": "sha256-RIFfgBuKz6Hp89yRr7+NR5tzIAbn52h8vT6vXkYjZoM=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "7e2a3b3dfd9af950a856d66b0a7d01e3c18aa249",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
}
}
},

View File

@ -1,46 +1,77 @@
{
inputs = {
naersk.url = "github:nix-community/naersk/master";
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
utils.url = "github:numtide/flake-utils";
flake-utils.url = "github:numtide/flake-utils";
};
outputs = { self, nixpkgs, utils, naersk }:
utils.lib.eachDefaultSystem (system:
outputs = { self, nixpkgs, flake-utils }:
let
inherit (builtins) fromTOML readFile substring;
cargoToml = fromTOML (readFile ./Cargo.toml);
version = "${cargoToml.package.version}+${substring 0 8 self.lastModifiedDate}.${self.shortRev or "dirty"}";
mkVnetod = { lib, rustPlatform, vnetodFeatures ? [ ], ... }:
rustPlatform.buildRustPackage {
name = "vnetod-${version}";
src = lib.cleanSource ./.;
cargoLock.lockFile = ./Cargo.lock;
buildFeatures = vnetodFeatures;
doCheck = true;
};
in
{
overlays = {
minimal = final: prev: {
vnetod = final.callPackage mkVnetod { };
};
default = final: prev: {
vnetod = final.callPackage mkVnetod {
vnetodFeatures = [ "color" ];
};
};
};
}
// flake-utils.lib.eachDefaultSystem (system:
let
name = "vnetod";
pkgs = import nixpkgs { inherit system; };
naersk-lib = pkgs.callPackage naersk { };
vnetod = pkgs.callPackage mkVnetod { vnetodFeatures = [ "color" ]; };
minimalVnetod = pkgs.callPackage mkVnetod { };
docker = pkgs.dockerTools.buildLayeredImage {
name = "pleshevskiy/vnetod";
tag = cargoToml.package.version;
config = {
Volumes."/data" = { };
WorkingDir = "/data";
Entrypoint = [ "${vnetod}/bin/vnetod" ];
};
};
mkApp = prog: {
type = "app";
program = "${vnetod}/bin/vnetod";
};
in
rec {
# Executes by `nix build .#<name>`
packages = {
${name} = naersk.lib.${system}.buildPackage {
pname = name;
root = ./.;
};
};
# Executes by `nix build .`
packages.default = packages.${name};
# the same but deprecated in Nix 2.7
defaultPackage = packages.default;
# Executes by `nix run .#<name> -- <args?>`
{
apps = {
${name} = utils.lib.mkApp {
inherit name;
drv = packages.${name};
};
default = mkApp vnetod;
minimal = mkApp minimalVnetod;
};
# Executes by `nix run . -- <args?>`
apps.default = apps.${name};
# the same but deprecated in Nix 2.7
defaultApp = apps.default;
# Used by `nix develop`
devShell = with pkgs; mkShell {
buildInputs = [ cargo rustc rustfmt pre-commit rustPackages.clippy ];
RUST_SRC_PATH = rustPlatform.rustLibSrc;
packages = {
inherit docker vnetod;
default = vnetod;
minimal = minimalVnetod;
};
devShell = pkgs.mkShell {
packages = with pkgs; [ cargo rustc rustfmt clippy rust-analyzer ];
RUST_SRC_PATH = pkgs.rustPlatform.rustLibSrc;
};
});
}

View File

@ -1,4 +1,4 @@
//! Copyright (C) 2022, Dmitriy Pleshevskiy <dmitriy@ideascup.me>
//! Copyright (C) 2022, Dmitriy Pleshevskiy <dmitriy@pleshevski.ru>
//!
//! vnetod is free software: you can redistribute it and/or modify
//! it under the terms of the GNU General Public License as published by
@ -20,14 +20,14 @@ use std::path::PathBuf;
use clap::Parser;
#[derive(Parser)]
#[derive(Parser, Debug)]
#[clap(
author,
version,
about = "\
Dotenv state switcher
---------------------------------------------------------------------
vnetod Copyright (C) 2022 Dmitriy Pleshevskiy <dmitriy@ideascup.me>
vnetod Copyright (C) 2022 Dmitriy Pleshevskiy <dmitriy@pleshevski.ru>
This program comes with ABSOLUTELY NO WARRANTY;
This is free software, and you are welcome to redistribute it
under certain conditions;
@ -35,12 +35,90 @@ under certain conditions;
"
)]
pub struct Args {
#[clap(short = 'f', long, default_value = ".env")]
#[clap(
short = 'f',
long,
default_value = ".env",
env = "VNETOD_FILE",
help = "Change source file with environment variables."
)]
pub file: PathBuf,
#[clap(short = 'o', long)]
#[clap(
short = 'o',
long,
help = "Change output file with modified environment variables. It uses `file` argument by default if the output is not specified."
)]
pub output: Option<PathBuf>,
#[clap(value_parser)]
#[clap(
long,
help = "Writes modified environment variables to stdout instead of a file. `Output` argument will be ignored."
)]
pub dry_run: bool,
#[clap(
value_parser,
help = "Environment varible sections that will be enabled."
)]
pub sections: Vec<String>,
#[cfg(feature = "color")]
#[clap(
long,
value_enum,
default_value = "auto",
help = "This flag controls when to use colors.",
long_help = "
This flag controls when to use colors. The default setting is 'auto', which
means vnetod will try to guess when to use colors. For example, if vnetod is
printing to a terminal, then it will use colors, but if it is redirected to a
file or a pipe, then it will suppress color output. vnetod will suppress color
output in some other circumstances as well. For example, if the TERM
environment variable is not set or set to 'dumb', then vnetod will not use
colors.
The possible values for this flag are:
never Colors will never be used.
auto The default. vnetod tries to be smart.
always Colors will always be used regardless of where output is sent.
ansi Like 'always', but emits ANSI escapes (even in a Windows console).
"
)]
pub color: ColorVariant,
}
#[cfg(feature = "color")]
#[derive(clap::ValueEnum, Clone, Debug)]
pub enum ColorVariant {
Auto,
Always,
Ansi,
Never,
}
#[cfg(feature = "color")]
impl From<ColorVariant> for termcolor::ColorChoice {
fn from(col: ColorVariant) -> Self {
match col {
ColorVariant::Never => Self::Never,
ColorVariant::Always => Self::Always,
ColorVariant::Ansi => Self::AlwaysAnsi,
ColorVariant::Auto => {
if atty::is(atty::Stream::Stdout) {
// Otherwise let's `termcolor` decide by inspecting the environment. From the [doc]:
// - If `NO_COLOR` is set to any value, then colors will be suppressed.
// - If `TERM` is set to dumb, then colors will be suppressed.
// - In non-Windows environments, if `TERM` is not set, then colors will be suppressed.
//
// [doc]: https://github.com/BurntSushi/termcolor#automatic-color-selection
Self::Auto
} else {
// Colors should be deactivated if the terminal is not a tty.
Self::Never
}
}
}
}
}

View File

@ -1,17 +1,37 @@
//! Copyright (C) 2022, Dmitriy Pleshevskiy <dmitriy@pleshevski.ru>
//!
//! vnetod is free software: you can redistribute it and/or modify
//! it under the terms of the GNU General Public License as published by
//! the Free Software Foundation, either version 3 of the License, or
//! (at your option) any later version.
//!
//! vnetod is distributed in the hope that it will be useful,
//! but WITHOUT ANY WARRANTY; without even the implied warranty of
//! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//! GNU General Public License for more details.
//!
//! You should have received a copy of the GNU General Public License
//! along with vnetod. If not, see <https://www.gnu.org/licenses/>.
//!
#[cfg(feature = "color")]
use termcolor::{Color, ColorSpec, StandardStream, WriteColor};
use crate::{cli::Args, domain};
use std::fs::File;
use std::io::Write;
#[derive(Debug)]
pub enum Error {
OpenFile,
Switch(domain::switch::Error),
WriteFile,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::OpenFile => f.write_str("Cannot open file"),
Error::Switch(inner) => write!(f, "Cannot switch between states: {}", inner),
Error::WriteFile => f.write_str("Cannot write file"),
}
}
}
@ -20,13 +40,52 @@ impl std::error::Error for Error {}
pub fn execute(args: &Args) -> Result<(), Error> {
let content = std::fs::read_to_string(&args.file).map_err(|_| Error::OpenFile)?;
let writer =
File::create(args.output.as_ref().unwrap_or(&args.file)).map_err(|_| Error::OpenFile)?;
domain::switch::execute(domain::switch::Request {
content: &content,
writer,
if args.dry_run {
println!("Your file will be changed to the following")
}
let fs_writer = (!args.dry_run)
.then(|| {
File::create(args.output.as_ref().unwrap_or(&args.file)).map_err(|_| Error::OpenFile)
})
.transpose()?;
#[cfg(feature = "color")]
let color = args.color.clone();
println!();
let new_content = domain::switch::execute(domain::switch::Request {
content: &content.trim(),
sections: &args.sections,
})
.map_err(Error::Switch)
on_line: Some(Box::new(move |line| {
#[cfg(feature = "color")]
print_line(line, color.clone());
#[cfg(not(feature = "color"))]
print!("{}", line)
})),
});
println!();
if let Some(mut fs_writer) = fs_writer {
fs_writer
.write_all(new_content.as_bytes())
.map_err(|_| Error::WriteFile)?;
}
Ok(())
}
#[cfg(feature = "color")]
fn print_line(line: &String, color: crate::cli::ColorVariant) {
let mut stdout = StandardStream::stdout(color.into());
let color = line
.starts_with("###")
.then_some(Color::Yellow)
.or_else(|| (!line.starts_with("#")).then_some(Color::Green));
stdout.set_color(ColorSpec::new().set_fg(color)).ok();
write!(&mut stdout, "{}", line).unwrap();
stdout.reset().ok();
}

View File

@ -1,3 +1,19 @@
//! Copyright (C) 2022, Dmitriy Pleshevskiy <dmitriy@pleshevski.ru>
//!
//! vnetod is free software: you can redistribute it and/or modify
//! it under the terms of the GNU General Public License as published by
//! the Free Software Foundation, either version 3 of the License, or
//! (at your option) any later version.
//!
//! vnetod is distributed in the hope that it will be useful,
//! but WITHOUT ANY WARRANTY; without even the implied warranty of
//! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//! GNU General Public License for more details.
//!
//! You should have received a copy of the GNU General Public License
//! along with vnetod. If not, see <https://www.gnu.org/licenses/>.
//!
pub mod switch;
#[derive(Debug, Clone, PartialEq, Eq)]
@ -27,3 +43,8 @@ impl Section {
.map_or_else(|| Self::new(s), |(ns, name)| Self::with_namespace(ns, name))
}
}
pub struct SectionInfo {
enable_variable: bool,
disable_variable: bool,
}

View File

@ -1,60 +1,58 @@
use std::io::{BufWriter, Write};
//! Copyright (C) 2022, Dmitriy Pleshevskiy <dmitriy@pleshevski.ru>
//!
//! vnetod is free software: you can redistribute it and/or modify
//! it under the terms of the GNU General Public License as published by
//! the Free Software Foundation, either version 3 of the License, or
//! (at your option) any later version.
//!
//! vnetod is distributed in the hope that it will be useful,
//! but WITHOUT ANY WARRANTY; without even the implied warranty of
//! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//! GNU General Public License for more details.
//!
//! You should have received a copy of the GNU General Public License
//! along with vnetod. If not, see <https://www.gnu.org/licenses/>.
//!
use super::Section;
use super::{Section, SectionInfo};
#[derive(Debug)]
pub enum Error {
WriteData,
}
pub type OnLineFn = Box<dyn Fn(&String)>;
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::WriteData => f.write_str("Cannot write data"),
}
}
}
impl std::error::Error for Error {}
pub struct Request<'args, W>
where
W: Write,
{
pub struct Request<'args> {
pub content: &'args str,
pub writer: W,
pub sections: &'args [String],
pub on_line: Option<OnLineFn>,
}
pub fn execute<W>(req: Request<W>) -> Result<(), Error>
where
W: Write,
{
let mut writer = BufWriter::new(req.writer);
pub fn execute(req: Request) -> String {
let choose_sections = req
.sections
.iter()
.map(|s| Section::parse(s.as_str()))
.collect::<Vec<_>>();
let mut current_sections: Option<Vec<Section>> = None;
let mut current_section: Option<SectionInfo> = None;
let mut new_content = String::new();
for line in req.content.split_inclusive('\n') {
let new_line = if is_section_end(line) {
current_sections = None;
current_section = None;
line.to_string()
} else if let Some(section_info) = line.strip_prefix("### ") {
current_sections = section_info
.split_whitespace()
.next()
.map(|r| r.split(',').map(Section::parse).collect());
current_section = section_info.split_whitespace().next().map(|r| {
let current_sections = r.split(',').map(Section::parse).collect::<Vec<_>>();
SectionInfo {
enable_variable: should_enable_variable(&choose_sections, &current_sections),
disable_variable: should_disable_variable(&choose_sections, &current_sections),
}
});
line.to_string()
} else if let Some(cur_sections) = current_sections.clone() {
} else if let Some(section_info) = current_section.as_ref() {
let trimmed_line = line.trim_start_matches(['#', ' ']);
if should_enable_variable(&choose_sections, &cur_sections) {
let is_var = is_variable(trimmed_line);
if is_var && section_info.enable_variable {
String::from(trimmed_line)
} else if should_disable_variable(&choose_sections, &cur_sections) {
} else if is_var && section_info.disable_variable {
format!("# {}", trimmed_line)
} else {
line.to_string()
@ -63,12 +61,22 @@ where
line.to_string()
};
writer
.write_all(new_line.as_bytes())
.map_err(|_| Error::WriteData)?;
new_content.push_str(&new_line);
if let Some(on_line) = req.on_line.as_ref() {
on_line(&new_line);
}
}
writer.flush().map_err(|_| Error::WriteData)
new_content
}
fn is_variable(trimmed_line: &str) -> bool {
trimmed_line
.chars()
.filter(|ch| (*ch != '_' && ch.is_ascii_punctuation()) || ch.is_whitespace())
.enumerate()
.find(|(_, ch)| *ch == '=')
.map_or(false, |(i, _)| i == 0)
}
fn is_section_end(line: &str) -> bool {
@ -115,28 +123,19 @@ fn should_disable_variable(choose_sections: &[Section], current_sections: &[Sect
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
const BASE_ENV: &str = include_str!("../../test_data/base_env");
fn make_test(input: &str, expected_output: &str, sections: Vec<&str>) {
let mut output_data = vec![];
let writer = Cursor::new(&mut output_data);
match execute(Request {
let output_data = execute(Request {
content: input,
writer,
sections: &sections.into_iter().map(String::from).collect::<Vec<_>>(),
}) {
Ok(()) => {
let output = String::from_utf8(output_data).unwrap();
assert_eq!(
output.lines().collect::<Vec<_>>(),
expected_output.lines().collect::<Vec<_>>()
);
}
_ => unreachable!(),
}
on_line: None,
});
assert_eq!(
output_data.lines().collect::<Vec<_>>(),
expected_output.lines().collect::<Vec<_>>()
);
}
#[test]
@ -258,5 +257,20 @@ mod tests {
&[Section::with_namespace("debug", "off")]
));
}
#[test]
fn should_check_line_on_variable() {
let test_cases = [
("VAR=10", true),
("THIS_IS_MY_VAR='hello world'", true),
("hello world", false),
("staging/production", false),
("staging/production=value", false),
];
for (input, expected) in test_cases {
assert_eq!(is_variable(input), expected);
}
}
}
}

View File

@ -1,4 +1,4 @@
//! Copyright (C) 2022, Dmitriy Pleshevskiy <dmitriy@ideascup.me>
//! Copyright (C) 2022, Dmitriy Pleshevskiy <dmitriy@pleshevski.ru>
//!
//! vnetod is free software: you can redistribute it and/or modify
//! it under the terms of the GNU General Public License as published by

View File

@ -2,6 +2,7 @@ VITE_STRIPE_PK=
VITE_SENTRY_ENABLED=
VITE_SENTRY_DSN=
### local,staging
# staging/production
VITE_SENTRY_ENV=staging
### prod
VITE_SENTRY_ENV=production

View File

@ -2,6 +2,7 @@ VITE_STRIPE_PK=
VITE_SENTRY_ENABLED=
VITE_SENTRY_DSN=
### local,staging
# staging/production
# VITE_SENTRY_ENV=staging
### prod
# VITE_SENTRY_ENV=production

View File

@ -2,6 +2,7 @@ VITE_STRIPE_PK=
VITE_SENTRY_ENABLED=
VITE_SENTRY_DSN=
### local,staging
# staging/production
VITE_SENTRY_ENV=staging
### prod
# VITE_SENTRY_ENV=production

View File

@ -2,6 +2,7 @@ VITE_STRIPE_PK=
VITE_SENTRY_ENABLED=
VITE_SENTRY_DSN=
### local,staging
# staging/production
VITE_SENTRY_ENV=staging
### prod
# VITE_SENTRY_ENV=production

View File

@ -2,6 +2,7 @@ VITE_STRIPE_PK=
VITE_SENTRY_ENABLED=
VITE_SENTRY_DSN=
### local,staging
# staging/production
VITE_SENTRY_ENV=staging
### prod
# VITE_SENTRY_ENV=production

View File

@ -2,6 +2,7 @@ VITE_STRIPE_PK=
VITE_SENTRY_ENABLED=
VITE_SENTRY_DSN=
### local,staging
# staging/production
VITE_SENTRY_ENV=staging
### prod
# VITE_SENTRY_ENV=production