Skip to content

chore: format with dart format #113

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 14, 2024
Merged
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
45 changes: 23 additions & 22 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,31 +19,32 @@ class MyApp extends StatelessWidget {
return MaterialApp(
title: 'flutter_dotenv Demo',
home: Scaffold(
appBar: AppBar(
title: const Text('Dotenv Demo'),
),
body: SingleChildScrollView(
child: FutureBuilder<String>(
future: rootBundle.loadString('assets/.env'),
initialData: '',
builder: (context, snapshot) => Container(
padding: const EdgeInsets.all(50),
child: Column(
children: [
Text(
'Env map: ${dotenv.env.toString()}',
),
const Divider(thickness: 5),
const Text('Original'),
const Divider(),
Text(snapshot.data ?? ''),
Text(dotenv.get('MISSING', fallback: 'Default fallback value')),
],
),
appBar: AppBar(
title: const Text('Dotenv Demo'),
),
body: SingleChildScrollView(
child: FutureBuilder<String>(
future: rootBundle.loadString('assets/.env'),
initialData: '',
builder: (context, snapshot) => Container(
padding: const EdgeInsets.all(50),
child: Column(
children: [
Text(
'Env map: ${dotenv.env.toString()}',
),
const Divider(thickness: 5),
const Text('Original'),
const Divider(),
Text(snapshot.data ?? ''),
Text(dotenv.get('MISSING',
fallback: 'Default fallback value')),
],
),
),
),
),
),
);
}
}
}
30 changes: 21 additions & 9 deletions lib/src/dotenv.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,9 @@ class DotEnv {

String get(String name, {String? fallback}) {
final value = maybeGet(name, fallback: fallback);
if(value == null){
throw AssertionError('$name variable not found. A non-null fallback is required for missing entries');
if (value == null) {
throw AssertionError(
'$name variable not found. A non-null fallback is required for missing entries');
}
return value;
}
Expand All @@ -65,7 +66,8 @@ class DotEnv {
/// exists but can not be parsed as an [int].
int getInt(String name, {int? fallback}) {
final value = maybeGet(name);
assert(value != null || fallback != null, 'A non-null fallback is required for missing entries');
assert(value != null || fallback != null,
'A non-null fallback is required for missing entries');
return value != null ? int.parse(value) : fallback!;
}

Expand All @@ -78,7 +80,8 @@ class DotEnv {
/// exists but can not be parsed as a [double].
double getDouble(String name, {double? fallback}) {
final value = maybeGet(name);
assert(value != null || fallback != null, 'A non-null fallback is required for missing entries');
assert(value != null || fallback != null,
'A non-null fallback is required for missing entries');
return value != null ? double.parse(value) : fallback!;
}

Expand All @@ -91,7 +94,8 @@ class DotEnv {
/// exists but can not be parsed as a [bool].
bool getBool(String name, {bool? fallback}) {
final value = maybeGet(name);
assert(value != null || fallback != null, 'A non-null fallback is required for missing entries');
assert(value != null || fallback != null,
'A non-null fallback is required for missing entries');
if (value != null) {
if (['true', '1'].contains(value.toLowerCase())) {
return true;
Expand All @@ -110,7 +114,10 @@ class DotEnv {
/// Loads environment variables from the env file into a map
/// Merge with any entries defined in [mergeWith]
Future<void> load(
{String fileName = '.env',Parser parser = const Parser(),Map<String, String> mergeWith = const {}, bool isOptional = false}) async {
{String fileName = '.env',
Parser parser = const Parser(),
Map<String, String> mergeWith = const {},
bool isOptional = false}) async {
clean();
List<String> linesFromFile;
try {
Expand All @@ -123,7 +130,9 @@ class DotEnv {
}
}

final linesFromMergeWith = mergeWith.entries.map((entry) => "${entry.key}=${entry.value}").toList();
final linesFromMergeWith = mergeWith.entries
.map((entry) => "${entry.key}=${entry.value}")
.toList();
final allLines = linesFromMergeWith..addAll(linesFromFile);
final envEntries = parser.parse(allLines);
_envMap.addAll(envEntries);
Expand All @@ -136,7 +145,9 @@ class DotEnv {
Map<String, String> mergeWith = const {}}) {
clean();
final linesFromFile = fileInput.split('\n');
final linesFromMergeWith = mergeWith.entries.map((entry) => "${entry.key}=${entry.value}").toList();
final linesFromMergeWith = mergeWith.entries
.map((entry) => "${entry.key}=${entry.value}")
.toList();
final allLines = linesFromMergeWith..addAll(linesFromFile);
final envEntries = parser.parse(allLines);
_envMap.addAll(envEntries);
Expand All @@ -146,7 +157,8 @@ class DotEnv {
/// True if all supplied variables have nonempty value; false otherwise.
/// Differs from [containsKey](dart:core) by excluding null values.
/// Note [load] should be called first.
bool isEveryDefined(Iterable<String> vars) => vars.every((k) => _envMap[k]?.isNotEmpty ?? false);
bool isEveryDefined(Iterable<String> vars) =>
vars.every((k) => _envMap[k]?.isNotEmpty ?? false);

Future<List<String>> _getEntriesFromFile(String filename) async {
try {
Expand Down
2 changes: 0 additions & 2 deletions lib/src/errors.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,3 @@ class NotInitializedError extends Error {}
class FileNotFoundError extends Error {}

class EmptyEnvFileError extends Error {}


9 changes: 6 additions & 3 deletions lib/src/parser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ class Parser {
}

/// Parses a single line into a key-value pair.
Map<String, String> parseOne(String line, {Map<String, String> env = const {}}) {
Map<String, String> parseOne(String line,
{Map<String, String> env = const {}}) {
var stripped = strip(line);
if (!_isValid(stripped)) return {};

Expand All @@ -48,7 +49,8 @@ class Parser {
}

/// Substitutes $bash_vars in [val] with values from [env].
String interpolate(String val, Map<String, String?> env) => val.replaceAllMapped(_bashVar, (m) {
String interpolate(String val, Map<String, String?> env) =>
val.replaceAllMapped(_bashVar, (m) {
if ((m.group(1) ?? "") == "\\") {
return m.input.substring(m.start, m.end);
} else {
Expand Down Expand Up @@ -84,5 +86,6 @@ class Parser {
bool _isValid(String s) => s.isNotEmpty && s.contains('=');

/// [ null ] is a valid value in a Dart map, but the env var representation is empty string, not the string 'null'
bool _has(Map<String, String?> map, String key) => map.containsKey(key) && map[key] != null;
bool _has(Map<String, String?> map, String key) =>
map.containsKey(key) && map[key] != null;
}
16 changes: 12 additions & 4 deletions test/dotenv_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ void main() {
group('dotenv', () {
setUp(() {
print(Directory.current.toString());
dotenv.testLoad(fileInput: File('test/.env').readAsStringSync()); // mergeWith: Platform.environment
dotenv.testLoad(
fileInput: File('test/.env')
.readAsStringSync()); // mergeWith: Platform.environment
});
test('when .env is loaded we should be able to get the .env variables', () {
expect(dotenv.env['FOO'], 'foo');
Expand Down Expand Up @@ -46,15 +48,21 @@ void main() {
expect(dotenv.env['USERNAME'], '[email protected]');
expect(dotenv.env['SPACED_KEY'], 'parsed');
});
test('when getting a vairable that is not in .env, we should get the fallback we defined', () {
test(
'when getting a vairable that is not in .env, we should get the fallback we defined',
() {
expect(dotenv.get('FOO', fallback: 'bar'), 'foo');
expect(dotenv.get('COMMENTS', fallback: 'sample'), 'sample');
expect(dotenv.get('EQUAL_SIGNS', fallback: 'sample'), 'equals==');
});
test('when getting a vairable that is not in .env, we should get an error thrown', () {
test(
'when getting a vairable that is not in .env, we should get an error thrown',
() {
expect(() => dotenv.get('COMMENTS'), throwsAssertionError);
});
test('when getting a vairable using the nullable getter, we should get null if no fallback is defined', () {
test(
'when getting a vairable using the nullable getter, we should get null if no fallback is defined',
() {
expect(dotenv.maybeGet('COMMENTS'), null);
expect(dotenv.maybeGet('COMMENTS', fallback: 'sample'), 'sample');
expect(dotenv.maybeGet('EQUAL_SIGNS', fallback: 'sample'), 'equals==');
Expand Down