Skip to content

Commit

Permalink
Prerelase env_reader v1.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
Nialixus committed Aug 26, 2023
1 parent 16f0f7e commit 2cd7610
Show file tree
Hide file tree
Showing 6 changed files with 69 additions and 19 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@
* Add .env parser
* Add .env encryption
* Add .env sample
* Add .env reader
* Add .env reader
* Add readme
* Add license
1 change: 1 addition & 0 deletions bin/env_reader.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:universal_file/universal_file.dart';
part 'src/pubspec.dart';
part 'src/asset.dart';

/// Dart runner for [EnvReader] library.
void main(List<String> arguments) async {
ArgParser runner = ArgParser()
..addOption('path', help: 'Path to the .env file')
Expand Down
7 changes: 5 additions & 2 deletions bin/src/asset.dart
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
// ignore_for_file: avoid_print
part of '../env_reader.dart';

/// A function to take the .env file from given [path] into a more secured version inside [directory].
void insertAsset({required ArgResults argument}) {
String path = argument['path']!.toString();
String password = argument['password']!.toString();
String data = File(path).readAsStringSync();
Directory directory = Directory('assets/env/')..createSync(recursive: true);
String name = path.contains("/") ? path.split("/").last : path;
File asset = File(directory.path + name)..writeAsStringSync(Encryptor.encrypt(password, data));
print("\x1B[32m$name\x1B[0m successfully secured into \x1B[34m${asset.path}\x1B[0m 🚀");
File asset = File(directory.path + name)
..writeAsStringSync(Encryptor.encrypt(password, data));
print(
"\x1B[32m$name\x1B[0m successfully secured into \x1B[34m${asset.path}\x1B[0m 🚀");
}
5 changes: 4 additions & 1 deletion bin/src/pubspec.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
part of '../env_reader.dart';

/// A function to check wether `- assets/env/` already exist in `pubspec.yaml` or not.
/// If not its inserting the path giver, and if its already there, this will do nothing.
void insertPubspec() {
File pubspecFile = File('pubspec.yaml');
List<String> lines = pubspecFile.readAsLinesSync();
Expand All @@ -16,7 +18,8 @@ void insertPubspec() {
}

if (!foundAssets) {
int lastFlutterLineIndex = lines.lastIndexWhere((line) => line.trim() == 'flutter:');
int lastFlutterLineIndex =
lines.lastIndexWhere((line) => line.trim() == 'flutter:');
if (lastFlutterLineIndex != -1) {
lines.insert(lastFlutterLineIndex + 1, ' assets:');
lines.insert(lastFlutterLineIndex + 2, ' - assets/env/');
Expand Down
6 changes: 4 additions & 2 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ import 'package:flutter/material.dart';
Future<void> main(List<String> arguments) async {
WidgetsFlutterBinding.ensureInitialized();
await Env.instance.load(password: "my strong password");
runApp(const MaterialApp(title: "Env Reader", debugShowCheckedModeBanner: false, home: MyApp()));
runApp(const MaterialApp(
title: "Env Reader", debugShowCheckedModeBanner: false, home: MyApp()));
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return Scaffold(body: Center(child: Text(Env.read<String>("MY_STRING") ?? "Oops")));
return Scaffold(
body: Center(child: Text(Env.read<String>("MY_STRING") ?? "Oops")));
}
}
65 changes: 52 additions & 13 deletions lib/env_reader.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,15 @@
///
/// Example:
/// ```dart
/// await Env.instance.load();
/// String? myValue = Env.read<String>("MY_VALUE");
/// int? myInt = Env.read<int>("MY_INT");
/// bool? myBool = Env.read<bool>("MY_BOOL");
/// Future<void> main(List<String> arguments) async {
/// WidgetsFlutterBinding.ensureInitialized();
/// await Env.instance.load(password: "my strong password");
/// runApp(...);
/// }
///
/// String? api = Env.read<String>("API_KEY");
/// int port = Env.read<int>("PORT") ?? 8080;
/// bool isDebug = Env.read<bool>("DEBUG") ?? false;
/// ```
library env_reader;

Expand All @@ -27,33 +32,57 @@ class Env {
///
/// 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 api = Env.read("API_KEY");
/// int port = Env.read<int>("PORT") ?? 8080;
/// ```
static T? read<T extends Object>(String key) => instance.read<T>(key);
}

/// A class for loading and parsing environment variables from a .env file.
class EnvReader {
/// The content of the loaded .env file.
/// The raw content of the loaded .env file.
///
/// ```dart
/// String? env = Env.instance.value;
/// ```
String? value;

/// Loads environment variables from a .env file.
///
/// The [asset] parameter specifies the path to the .env file in asset/env/ directory. By default, it
/// sets to look for the assets/env/.env file.
Future<void> load({String asset = 'assets/env/.env', required String password}) async {
/// sets to look for the `assets/env/.env` file.
///
/// ```dart
/// Future<void> main(List<String> arguments) async {
/// WidgetsFlutterBinding.ensureInitialized();
/// await Env.instance.load(
/// asset: "assets/env/.env",
/// password: "my strong password");
/// runApp(...);
/// }
/// ```
Future<void> load(
{String asset = 'assets/env/.env', required String password}) async {
try {
String data = await rootBundle.loadString(asset);
value = Encryptor.decrypt(password, data);
} catch (e) {
if (kDebugMode) print("\n\n\u001b[1m[ENV_READER]\u001b[31m 💥 Unable to load data\u001b[0m 💥\n$e\n\n");
if (kDebugMode) {
print(
"\n\n\u001b[1m[ENV_READER]\u001b[31m 💥 Unable to load data\u001b[0m 💥\n$e\n\n");
}
value = null;
}
}

/// Parses environment variables into a map.
/// Parses environment variables into a json structured map.
///
/// This method reads the environment variables from the loaded .env file,
/// parses their values, and stores them in a map. It returns the map of
/// environment variable names and their parsed values.
/// ```dart
/// Map<String, dynamic> json = Env.instance.toJson();
/// ```
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
final lines = (value ?? "").trim().split('\n');
Expand All @@ -80,7 +109,10 @@ class EnvReader {
}
}
} catch (e) {
if (kDebugMode) print("\n\n\u001b[1m[ENV_READER]\u001b[31m 💥 Parsing failed\u001b[0m 💥\n$e\n\n");
if (kDebugMode) {
print(
"\n\n\u001b[1m[ENV_READER]\u001b[31m 💥 Parsing failed\u001b[0m 💥\n$e\n\n");
}
}
}
return data;
Expand All @@ -90,6 +122,13 @@ class EnvReader {
///
/// 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();
/// final api = env.read("API_KEY");
/// int port = env.read<int>("PORT") ?? 8080;
/// ```
T? read<T extends Object>(String key) {
try {
return toJson()[key];
Expand Down

0 comments on commit 2cd7610

Please sign in to comment.