Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.

# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml

# analyzer:
# errors:
# avoid_print: ignore

linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at https://dart.dev/tools/linter-rules.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule

# Additional information about this file can be found at
# https://dart.dev/tools/analysis
76 changes: 49 additions & 27 deletions bin/env_reader.dart
Original file line number Diff line number Diff line change
@@ -1,40 +1,62 @@
// ignore_for_file: avoid_print
import 'dart:io';

import 'package:args/args.dart';
import 'package:env_reader/src/env_encryption.dart';

part 'src/file.dart';
part 'src/pubspec.dart';
part 'src/json.dart';
part 'src/gitignore.dart';
part 'src/json.dart';
part 'src/pubspec.dart';

/// Dart runner for `EnvReader` library.
void main(List<String> arguments) async {
ArgParser runner = ArgParser()
..addOption('input',
abbr: 'i', help: 'Input path of the .env file', mandatory: true)
..addOption('output',
abbr: 'o', help: 'Output path for the encrypted .env file')
..addOption('key',
abbr: 's', help: 'Secret key for encryption & decryption')
final runner = ArgParser()
..addOption(
'input',
abbr: 'i',
help: 'Input path of the .env file',
mandatory: true,
)
..addOption(
'output',
abbr: 'o',
help: 'Output path for the encrypted .env file',
)
..addOption(
'key',
abbr: 's',
help: 'Secret key for encryption & decryption',
)
..addOption('model', help: 'Generate dart model to your desired file path')
..addFlag('null-safety',
defaultsTo: false, negatable: false, help: 'Make the model null safety')
..addFlag('obfuscate',
defaultsTo: true, help: 'Obfuscating generated values of model')
..addFlag('pubspec',
defaultsTo: true, help: 'Inserting asset path to pubspec.yaml')
..addFlag('gitignore',
defaultsTo: true,
help: 'Inserting .env input & output file into .gitignore')
..addFlag('help',
defaultsTo: false,
abbr: 'h',
negatable: false,
help: 'Print this usage information');
..addFlag(
'null-safety',
negatable: false,
help: 'Make the model null safety',
)
..addFlag(
'obfuscate',
defaultsTo: true,
help: 'Obfuscating generated values of model',
)
..addFlag(
'pubspec',
defaultsTo: true,
help: 'Inserting asset path to pubspec.yaml',
)
..addFlag(
'gitignore',
defaultsTo: true,
help: 'Inserting .env input & output file into .gitignore',
)
..addFlag(
'help',
abbr: 'h',
negatable: false,
help: 'Print this usage information',
);
try {
ArgResults argument = runner.parse(arguments);
if (argument["help"]) {
final argument = runner.parse(arguments);
if (argument['help']) {
throw '\u001b[0mAvailable commands:';
} else {
insertJson(from: argument);
Expand All @@ -43,7 +65,7 @@ void main(List<String> arguments) async {
insertFile(from: argument);
}
} catch (e) {
print("\n\u001b[31m$e\u001b[0m\n");
print('\n\u001b[31m$e\u001b[0m\n');
print(runner.usage);
print('\n\u001b[32mdart run\u001b[0m '
'\u001b[36menv_reader\u001b[0m '
Expand Down
32 changes: 16 additions & 16 deletions bin/src/gitignore.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,24 @@ part of '../env_reader.dart';

/// A function to add your [input] into .gitignore file in the same directory.
void insertGitignore({required ArgResults from}) {
bool insert = from["pubspec"];
final bool insert = from['pubspec'];
if (insert) {
File gitignore = File('.gitignore');
String input = from["input"]!.toString();
String? output = from["output"]?.toString();
List<String> lines = gitignore.readAsLinesSync();
bool inputExisted = false;
bool outputExisted = false;
final gitignore = File('.gitignore');
final input = from['input']!.toString();
final output = from['output']?.toString();
final lines = gitignore.readAsLinesSync();
var inputExisted = false;
var outputExisted = false;

for (int i = 0; i < lines.length; i++) {
for (var i = 0; i < lines.length; i++) {
if (lines[i].contains(input)) {
inputExisted = true;
break;
}
}

if (output != null) {
for (var item in lines) {
for (final item in lines) {
if (item.contains(output)) {
outputExisted = true;
break;
Expand All @@ -28,25 +28,25 @@ void insertGitignore({required ArgResults from}) {
}

if (!inputExisted) {
String comment = "# Env Reader related";
int index =
const comment = '# Env Reader related';
final index =
lines.lastIndexWhere((line) => line.trim().startsWith(comment));
if (index != -1) {
lines.insert(index + 1, input);
} else {
lines.insert(0, "$comment\n$input");
lines.insert(0, '$comment\n$input');
}
}

if (!outputExisted && output != null) {
String comment = "# Env Reader related";
int index =
const comment = '# Env Reader related';
final index =
lines.lastIndexWhere((line) => line.trim().startsWith(comment));
String export = outputExisted ? "" : output;
final export = outputExisted ? '' : output;
if (index != -1) {
lines.insert(index + 1, export);
} else {
lines.insert(0, "$comment\n$export");
lines.insert(0, '$comment\n$export');
}
}

Expand Down
47 changes: 24 additions & 23 deletions bin/src/json.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,32 @@ 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();
final model = from['model']?.toString();
if (model != null) {
// Fetching arguments
String path = model.replaceAll(RegExp(r'/[^/]+$'), "/");
String name = model
.split("/")
final path = model.replaceAll(RegExp(r'/[^/]+$'), '/');
final name = model
.split('/')
.last
.split(".")
.split('.')
.first
.split("_")
.map((e) => capitalize(e))
.join("");
String input = from["input"]!.toString();
bool obfuscate = from['obfuscate'];
String data = File(input).readAsStringSync();
bool nullSafety = from["null-safety"];
.split('_')
.map(capitalize)
.join();
final input = from['input']!.toString();
final bool obfuscate = from['obfuscate'];
final data = File(input).readAsStringSync();
final bool nullSafety = from['null-safety'];

// Parsing .env toJson
Map<String, dynamic> json = toJson(data);
final json = toJson(data);

// Generating model
String cast = json.entries.map((e) {
Type type = e.value.runtimeType;
String name = dartNamed(e.key);
final cast = json.entries.map((e) {
final type = e.value.runtimeType;
final name = dartNamed(e.key);
if (obfuscate) {
String variable = nullSafety
final variable = nullSafety
? "Env.read<$type>('${e.key}') ?? ${type == bool ? 'false' : type == int ? '0' : type == double ? '0.0' : "'${e.key}'"}"
: "Env.read<$type>('${e.key}')";

Expand All @@ -49,8 +49,8 @@ void insertJson({required ArgResults from}) {
static const $type $name = ${type == String ? "'${e.value}'" : e.value ?? 'e.key'};
""";
}
}).join("\n");
String write = """
}).join('\n');
final write = """
// Env Reader Auto-Generated Model File
// Created at ${DateTime.now()}
// 🍔 [Buy me a coffee](https://www.buymeacoffee.com/nialixus) 🚀
Expand All @@ -65,7 +65,8 @@ $cast
Directory(path).createSync(recursive: true);
File(model).writeAsStringSync(write);
print(
"\x1B[32m$input\x1B[0m successfully generated into \x1B[34m$model\x1B[0m 🎉");
'\x1B[32m$input\x1B[0m successfully generated into \x1B[34m$model\x1B[0m 🎉',
);
}
}

Expand Down Expand Up @@ -110,8 +111,8 @@ String capitalize(String text) {

/// A function to generate dart naming style of [String].
String dartNamed(String input) {
List<String> words = input.split('_');
String firstWord = words.first.toLowerCase();
String restOfWords = words.sublist(1).map((word) => capitalize(word)).join();
final words = input.split('_');
final firstWord = words.first.toLowerCase();
final restOfWords = words.sublist(1).map(capitalize).join();
return '$firstWord$restOfWords';
}
32 changes: 17 additions & 15 deletions bin/src/pubspec.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,28 @@ part of '../env_reader.dart';
/// A function to check wether the output path (if its's an assets directory) already exist in `pubspec.yaml` or not.
/// If it hasn't, this function inserting the output path given into your pubspec.yaml, and if its already there, this will do nothing.
void insertPubspec({required ArgResults from}) {
bool insert = from["pubspec"] ?? true;
String input = from["input"]!.toString();
String? output = from['output']?.toString();
final bool insert = from['pubspec'] ?? true;
final input = from['input']!.toString();
final output = from['output']?.toString();
if (insert && output != null) {
String output =
from["output"]!.toString().replaceAll(RegExp(r'/[^/]+$'), "/");
if (output.startsWith("assets/")) {
File pubspec = File('pubspec.yaml');
List<String> lines = pubspec.readAsLinesSync();
bool existed = false;
final output =
from['output']!.toString().replaceAll(RegExp(r'/[^/]+$'), '/');
if (output.startsWith('assets/')) {
final pubspec = File('pubspec.yaml');
final lines = pubspec.readAsLinesSync();
var existed = false;

for (int i = 0; i < lines.length; i++) {
if (lines[i].contains("- $output")) {
for (var i = 0; i < lines.length; i++) {
if (lines[i].contains('- $output')) {
existed = true;
break;
}
}

if (!existed) {
int flutterIndex =
final flutterIndex =
lines.lastIndexWhere((line) => line.trim() == 'flutter:');
int assetsIndex =
final assetsIndex =
lines.lastIndexWhere((line) => line.trim() == 'assets:');
if (flutterIndex == -1) {
lines.insert(lines.length - 1, 'flutter:\n assets:\n - $output');
Expand All @@ -41,9 +41,11 @@ void insertPubspec({required ArgResults from}) {
}
} else {
print(
"\u001b[33m--pubspec\u001b[0m \u001b[2mflag ignored, due to output not in assets directory\u001b[0m");
'\u001b[33m--pubspec\u001b[0m \u001b[2mflag ignored, due to output not in assets directory\u001b[0m',
);
print(
"\u001b[2mThis make the $input not accesible for every flutter platform\u001b[0m");
'\u001b[2mThis make the $input not accesible for every flutter platform\u001b[0m',
);
}
}
}
Loading