Skip to content

Commit

Permalink
## 2.0.1
Browse files Browse the repository at this point in the history
* Update pubspec
* Remove asset loader
* Remove  flag in
�[31mInvalid argument(s): Option input is mandatory.�[0m

-i, --input (mandatory)    Input path of the .env file
-o, --output               Output path for the encrypted .env file
-s, --key                  Secret key for encryption & decryption
    --model                Generate dart model to your desired file path
    --null-safety          Make the model null safety
    --[no-]obfuscate       Obfuscating generated values of model
                           (defaults to on)
    --[no-]pubspec         Inserting asset path to pubspec.yaml
                           (defaults to on)
    --[no-]gitignore       Inserting .env input & output file into .gitignore
                           (defaults to on)
-h, --help                 Print this usage information

�[32mdart run�[0m �[36menv_reader�[0m --input=�[33m".env"�[0m --password=�[33m"MyStrongPassword"�[0m --model=�[33m"lib/src/env_model.dart"�[0m --null-safety cli
  • Loading branch information
Nialixus committed Oct 16, 2023
1 parent 23c69c1 commit e0020a6
Show file tree
Hide file tree
Showing 12 changed files with 138 additions and 183 deletions.
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,9 @@
## 2.0.0
* Split between reader for dart as `env_reader_core` and `env_reader` for flutter
* Add `sdk` flag option in `env_reader` cli
* Change `encryptor` to `cryptography`
* Change `encryptor` to `cryptography`

## 2.0.1
* Update pubspec
* Remove asset loader
* Remove `sdk` flag in `env_reader` cli
22 changes: 11 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,46 +38,47 @@ DEBUG=true
PORT=8080
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
```
---

### 2. Run the command (Optional)
Now, if you want to generate encrypted env file, run this command in your terminal:
```bash
dart run env_reader --input=".env" --output="assets/env/" --key="MyOptionalSecretKey"
env_reader --input=".env" --output="assets/env/" --key="MyOptionalSecretKey"
```
> [!NOTE]
> **`output:`** .env successfully encrypted into assets/env/.env 🚀
also if you want to generate dart model from this env file, use tihs:
```bash
dart run env_reader --input-".env" --model="lib/src/env_model.dart" --null-safety
env_reader --input-".env" --model="lib/src/env_model.dart" --null-safety
```
> [!NOTE]
> **`output:`** .env successfully generated into lib/src/env_model.dart 🎉
---

### 3. Loading your .env
Load the env_reader instance:
```dart
import 'package:env_reader/env_reader.dart';
// If you want to use env_reader for dart projects only, call this instead ↓↓
import 'package:env_reader/env_reader_core.dart';
import 'package:flutter/services.dart';
await Env.load(
EnvAssetLoader('assets/env/.env'),
EnvStringLoader(await rootBundle.loadString('assets/env/.env')),
"MyOptionalSecretKey");
// Or you can load by creating your own `EnvReader` instance.
EnvReader production = EnvReader();
await production.load(
EnvAssetLoader(asset),
EnvStringLoader(await rootBundle.loadString('assets/env/.env')),
"MyOptionalSecretKey");
```
---

### 4. Access your configuration
To get and read the value of your env:
```dart
import 'package:env_reader/env_reader.dart'; // for flutter project
import 'package:env_reader/env_reader_core.dart'; // for dart project
import 'package:env_reader/env_reader.dart';
import 'package:my_package/src/env_model.dart';
String api = Env.read("API_KEY") ?? "Got'cha 😎";
Expand All @@ -100,6 +101,7 @@ Text(
EnvModel.debug ? "🤫 pssst, this is my api key y'all \n\n ${EnvModel.apiKey}" : "Nothing to see here 🤪",
);
```
---

## Env Reader Command 🚀
Available commands:
Expand All @@ -113,8 +115,6 @@ Available commands:
| --null-safety | Make the model null safety |
| --[no-]obfuscate | Obfuscating generated values of model |
| | (defaults to on) |
| --sdk | Choose between generating model for flutter or dart project |
| | [dart, flutter (default)] |
| --[no-]pubspec | Insert asset path to pubspec.yaml |
| | (defaults to on) |
| --[no-]gitignore | Insert .env input & output file into .gitignore |
Expand All @@ -123,7 +123,7 @@ Available commands:

Example usage:
```bash
dart run env_reader -i ".env" -o "assets/env/" -s "MyOptionalSecretKey" --model="lib/src/env_model.dart" --null-safety --sdk flutter
env_reader -i ".env" -o "assets/env/" -s "MyOptionalSecretKey" --model="lib/src/env_model.dart" --null-safety
```


Expand Down
7 changes: 1 addition & 6 deletions bin/env_reader.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
// ignore_for_file: avoid_print
import 'dart:io';

import 'package:args/args.dart';
import 'package:env_reader/env_reader_core.dart' show EnvEncryption;
import 'package:env_reader/env_reader.dart' show EnvEncryption;

part 'src/file.dart';
part 'src/pubspec.dart';
Expand All @@ -23,10 +22,6 @@ void main(List<String> arguments) async {
defaultsTo: false, negatable: false, help: 'Make the model null safety')
..addFlag('obfuscate',
defaultsTo: true, help: 'Obfuscating generated values of model')
..addOption('sdk',
help: 'Choose between generating model for flutter or dart project',
allowed: ['dart', 'flutter'],
defaultsTo: 'flutter')
..addFlag('pubspec',
defaultsTo: true, help: 'Inserting asset path to pubspec.yaml')
..addFlag('gitignore',
Expand Down
3 changes: 1 addition & 2 deletions bin/src/json.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ part of '../env_reader.dart';
/// A function to generate dart model out of .env file
void insertJson({required ArgResults from}) {
String? model = from["model"]?.toString();
bool isFlutter = from["sdk"] == 'flutter';
if (model != null) {
// Fetching arguments
String path = model.replaceAll(RegExp(r'/[^/]+$'), "/");
Expand Down Expand Up @@ -55,7 +54,7 @@ void insertJson({required ArgResults from}) {
// Env Reader Auto-Generated Model File
// Created at ${DateTime.now()}
// 🍔 [Buy me a coffee](https://www.buymeacoffee.com/nialixus) 🚀
${obfuscate ? "import 'package:env_reader/env_reader${isFlutter ? '' : '_core'}.dart';\n" : ''}
${obfuscate ? "import 'package:env_reader/env_reader.dart';\n" : ''}
${obfuscate ? "/// This class represents environment variables parsed from the .env file.\n/// Each static variable corresponds to an environment variable,${nullSafety ? "\n/// with default values provided for safety\n/// `false` for [bool], `0` for [int], `0.0` for [double] and `VARIABLE_NAME` for [String]." : ""}" : "/// Class wrapper for duplicated values copied directly from env file"}
class $name {
$cast
Expand Down
3 changes: 2 additions & 1 deletion example/lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import 'package:env_reader/env_reader.dart';
import 'package:example/src/env_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

Future<void> main(List<String> arguments) async {
WidgetsFlutterBinding.ensureInitialized();
await Env.load(
const EnvAssetLoader('assets/env/.env'),
EnvStringLoader(await rootBundle.loadString('assets/env/.env')),
"MyOptionalSecretKey",
);
runApp(
Expand Down
109 changes: 101 additions & 8 deletions lib/env_reader.dart
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
/// A simple utility for reading and parsing environment variables from a .env file.
/// A simple utility for reading and parsing environment variables from a .env file
///
/// This library provides a way to load environment variables from a .env file
/// and parse them into a Map<String, dynamic>, allowing you to easily access environment values
/// in your Flutter application.
/// in your Dart application.
///
/// Example:
/// ```dart
/// // Loading env data
/// await Env.load(
/// EnvAssetLoader('assets/env/.env'),
/// 'MyOptionalSecretKey');
/// EnvFileLoader(File('.env'))
/// );
///
/// // Using env data
/// String? api = Env.read<String>("API_KEY");
Expand All @@ -19,7 +19,100 @@
library env_reader;

import 'dart:async';
import 'package:flutter/services.dart';
import 'env_reader_core.dart';
export 'env_reader_core.dart' hide EnvParser, EnvEncryption;
part 'src/flutter/env_loader.dart';
import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'dart:typed_data';
import 'package:cryptography/cryptography.dart';
import 'package:http/http.dart';

export 'env_reader.dart' hide EnvParser, EnvEncryption;

part 'package:env_reader/src/env_loader.dart';
part 'package:env_reader/src/env_parser.dart';
part 'package:env_reader/src/env_encryption.dart';

/// A utility class for reading environment variables from .env source into your dart project.
class Env {
/// Default instance of [EnvReader] used to read environment variables.
static EnvReader instance = EnvReader();

/// Loads environment variables from .env source.
///
/// The [source] parameter specifies where's the .env took place.
///
/// ```dart
/// await Env.load(
/// EnvFileLoader(File('.env')),
/// 'MyOptionalSecretKey'
/// );
/// ```
static Future<void> load(EnvLoader source, [String? key]) =>
instance.load(source, key);

/// Reads an environment variable value of type [T] from the loaded environment.
///
/// Returns the value associated with the specified [key], or `null` if the key
/// is not found or there was an error while reading the environment.
///
/// ```dart
/// // example
/// String? api = Env.read("API_KEY");
/// int port = Env.read<int>("PORT") ?? 8080;
/// ```
static T? read<T extends Object>(String key) => instance.read<T>(key);
}

/// An instance to load and parse environment variables from .env into dart object.
class EnvReader {
/// Loaded value of .env
///
/// ```dart
/// String? rawValue = EnvReader().value;
/// ```
String? value;

/// Loads environment variables from .env source.
///
/// The [source] parameter specifies where's the .env file took place.
///
/// ```dart
/// await Env.load(
/// EnvFileLoader(File('.env')),
/// 'MyOptionalSecretKey'
/// );
/// ```
Future<void> load(EnvLoader source, [String? key]) async {
try {
value = await source.data(key);
} catch (e) {
log("\n\n\u001b[1m[ENV_READER]\u001b[31m 💥 Unable to load data\u001b[0m 💥\n$e\n\n");
}
}

/// Parse environment variables into a json structured map.
///
/// ```dart
/// Map<String, dynamic> json = EnvReader().toJson;
/// ```
Map<String, dynamic> get toJson => EnvParser(input: value ?? '').output;

/// Reads an environment variable value of type [T] from the loaded environment.
///
/// Returns the value associated with the specified [key], or `null` if the key
/// is not found or there was an error while reading the environment.
///
/// ```dart
/// // example
/// final env = EnvReader();
/// String? api = env.read("API_KEY");
/// int port = env.read<int>("PORT") ?? 8080;
/// ```
T? read<T extends Object>(String key) {
try {
return toJson[key];
} catch (e) {
return null;
}
}
}
118 changes: 0 additions & 118 deletions lib/env_reader_core.dart

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
part of '../../env_reader_core.dart';
part of 'package:env_reader/env_reader.dart';

/// A utility class for encrypting and decrypting data using AES-GCM encryption.
///
Expand Down
Loading

0 comments on commit e0020a6

Please sign in to comment.