Skip to content

Commit

Permalink
chore: improve code style
Browse files Browse the repository at this point in the history
  • Loading branch information
robert-virkus committed Jan 5, 2024
1 parent 7587d07 commit 301ddab
Show file tree
Hide file tree
Showing 27 changed files with 994 additions and 489 deletions.
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
"unflagged",
"Unforwarded",
"UNKEYWORD",
"Unselectable",
"writeln",
"xoauth"
],
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,9 @@ The following SMTP extensions are supported:
The following security extensions are supported:
* ✅ Partial signing of messages using [DKIM](https://tools.ietf.org/html/rfc6376)

### Other
*[Mailto](https://tools.ietf.org/html/rfc6068) parsing mailto links
*[Email provider auto-discovery](https://tools.ietf.org/html/rfc6186) Discover settings for an email address

### Supported encodings
Character encodings:
Expand Down
36 changes: 24 additions & 12 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,29 @@ analyzer:
todo: ignore
plugins:
- dart_code_metrics # https://github.com/dart-code-checker/dart-code-metrics
exclude:
- '**/*.g.*'

dart_code_metrics:
anti-patterns:
- long-method
- long-parameter-list
metrics:
cyclomatic-complexity: 20
maximum-nesting-level: 7
number-of-parameters: 10
source-lines-of-code: 100
metrics-exclude:
- test/**
rules:
- newline-before-return
- no-boolean-literal-compare
- no-empty-block
- prefer-trailing-comma
- prefer-conditional-expressions
- no-equal-then-else
- avoid-non-null-assertion

linter:
rules:
- always_declare_return_types
Expand Down Expand Up @@ -148,15 +171,4 @@ linter:
- use_to_and_as_if_applicable
- valid_regexps
- void_checks
dart_code_metrics:
metrics:
# disable metrics
cyclomatic-complexity: 50
maximum-nesting-level: 50
number-of-parameters: 50
source-lines-of-code: 500
number-of-methods: 100
metrics-exclude:
- test/**
rules:
- avoid-non-null-assertion # comply to engineering standards and avoid !

8 changes: 5 additions & 3 deletions example/discover.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ void main(List<String> args) async {
onlyPreferred = arguments.remove('--preferred');
email = arguments.last;
if (arguments.length != 1) {
email = args.firstWhere((arguments) => arguments.contains('@'),
orElse: () => '');
email = args.firstWhere(
(arguments) => arguments.contains('@'),
orElse: () => '',
);
arguments.remove(email);
print('Invalid arguments: $arguments');
_usage();
Expand All @@ -38,7 +40,7 @@ void main(List<String> args) async {
print('Unable to discover settings for $email');
} else {
print('Settings for $email:');
for (final provider in config.emailProviders!) {
for (final provider in config.emailProviders ?? []) {
print('provider: ${provider.displayName}');
print('provider-domains: ${provider.domains}');
print('documentation-url: ${provider.documentationUrl}');
Expand Down
34 changes: 24 additions & 10 deletions example/enough_mail_example.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Future<void> discoverExample() async {
print('Unable to discover settings for $email');
} else {
print('Settings for $email:');
for (final provider in config.emailProviders!) {
for (final provider in config.emailProviders ?? []) {
print('provider: ${provider.displayName}');
print('provider-domains: ${provider.domains}');
print('documentation-url: ${provider.documentationUrl}');
Expand All @@ -56,8 +56,9 @@ MimeMessage buildMessage() {
..from = [const MailAddress('Personal Name', 'sender@domain.com')]
..to = [
const MailAddress('Recipient Personal Name', 'recipient@domain.com'),
const MailAddress('Other Recipient', 'other@domain.com')
const MailAddress('Other Recipient', 'other@domain.com'),
];

return builder.buildMimeMessage();
}

Expand All @@ -67,14 +68,15 @@ Future<MimeMessage> buildMessageWithAttachment() async {
..from = [const MailAddress('Personal Name', 'sender@domain.com')]
..to = [
const MailAddress('Recipient Personal Name', 'recipient@domain.com'),
const MailAddress('Other Recipient', 'other@domain.com')
const MailAddress('Other Recipient', 'other@domain.com'),
]
..addMultipartAlternative(
plainText: 'Hello world!',
htmlText: '<p>Hello world!</p>',
);
final file = File.fromUri(Uri.parse('file://./document.pdf'));
await builder.addFile(file, MediaSubtype.applicationPdf.mediaType);

return builder.buildMimeMessage();
}

Expand All @@ -90,6 +92,7 @@ Future<void> mailExample() async {
// and [MailAccount.fromManualSettingsWithAuth]
// factory constructors for details.
print('Unable to auto-discover settings for $email');

return;
}
print('connecting to ${config.displayName}.');
Expand Down Expand Up @@ -127,15 +130,20 @@ Future<void> mailExample() async {
Future<void> imapExample() async {
final client = ImapClient(isLogEnabled: false);
try {
await client.connectToServer(imapServerHost, imapServerPort,
isSecure: isImapServerSecure);
await client.connectToServer(
imapServerHost,
imapServerPort,
isSecure: isImapServerSecure,
);
await client.login(userName, password);
final mailboxes = await client.listMailboxes();
print('mailboxes: $mailboxes');
await client.selectInbox();
// fetch 10 most recent messages:
final fetchResult = await client.fetchRecentMessages(
messageCount: 10, criteria: 'BODY.PEEK[]');
messageCount: 10,
criteria: 'BODY.PEEK[]',
);
fetchResult.messages.forEach(printMessage);
await client.logout();
} on ImapException catch (e) {
Expand All @@ -147,8 +155,11 @@ Future<void> imapExample() async {
Future<void> smtpExample() async {
final client = SmtpClient('enough.de', isLogEnabled: true);
try {
await client.connectToServer(smtpServerHost, smtpServerPort,
isSecure: isSmtpServerSecure);
await client.connectToServer(
smtpServerHost,
smtpServerPort,
isSecure: isSmtpServerSecure,
);
await client.ehlo();
if (client.serverInfo.supportsAuth(AuthMechanism.plain)) {
await client.authenticate('user.name', 'password', AuthMechanism.plain);
Expand All @@ -170,8 +181,11 @@ Future<void> smtpExample() async {
Future<void> popExample() async {
final client = PopClient(isLogEnabled: false);
try {
await client.connectToServer(popServerHost, popServerPort,
isSecure: isPopServerSecure);
await client.connectToServer(
popServerHost,
popServerPort,
isSecure: isPopServerSecure,
);
await client.login(userName, password);
// alternative login:
// await client.loginWithApop(userName, password);
Expand Down
19 changes: 15 additions & 4 deletions lib/src/codecs/base64_mail_codec.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,13 @@ class Base64MailCodec extends MailCodec {
/// [codec] the optional codec, defaults to utf8 [MailCodec.encodingUtf8].
/// Set [wrap] to `false` in case you do not want to wrap lines.
@override
String encodeText(String text,
{Codec codec = MailCodec.encodingUtf8, bool wrap = true}) {
String encodeText(
String text, {
Codec codec = MailCodec.encodingUtf8,
bool wrap = true,
}) {
final charCodes = codec.encode(text);

return encodeData(charCodes, wrap: wrap);
}

Expand All @@ -32,8 +36,11 @@ class Base64MailCodec extends MailCodec {
/// Set the [nameLength] for ensuring there is enough place for the
/// name of the encoding.
@override
String encodeHeader(String text,
{int nameLength = 0, bool fromStart = false}) {
String encodeHeader(
String text, {
int nameLength = 0,
bool fromStart = false,
}) {
final runes = List.from(text.runes, growable: false);
var numberOfRunesAbove7Bit = 0;
var startIndex = -1;
Expand Down Expand Up @@ -105,6 +112,7 @@ class Base64MailCodec extends MailCodec {
if (endIndex < text.length - 1) {
buffer.write(text.substring(endIndex + 1));
}

return buffer.toString();
}
}
Expand Down Expand Up @@ -136,6 +144,7 @@ class Base64MailCodec extends MailCodec {
@override
String decodeText(String part, Encoding codec, {bool isHeader = false}) {
final outputList = decodeData(part);

return codec.decode(outputList);
}

Expand All @@ -146,6 +155,7 @@ class Base64MailCodec extends MailCodec {
if (wrap) {
base64Text = _wrapText(base64Text);
}

return base64Text;
}

Expand All @@ -171,6 +181,7 @@ class Base64MailCodec extends MailCodec {
final startPos = chunkIndex * chunkLength;
buffer.write(text.substring(startPos));
}

return buffer.toString();
}
}
28 changes: 16 additions & 12 deletions lib/src/codecs/date_codec.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class DateCodec {
'Thu',
'Fri',
'Sat',
'Sun'
'Sun',
];
static const _months = <String>[
'Jan',
Expand All @@ -24,7 +24,7 @@ class DateCodec {
'Sep',
'Oct',
'Nov',
'Dec'
'Dec',
];
static const _monthsByName = <String, int>{
'jan': 1,
Expand Down Expand Up @@ -353,6 +353,7 @@ Date and time values occur in several header fields. This section
}
buffer.write(minutes);
}

return buffer.toString();
}

Expand All @@ -366,6 +367,7 @@ Date and time values occur in several header fields. This section
..write('-')
..write(dateTime.year)
..write('"');

return buffer.toString();
}

Expand Down Expand Up @@ -474,31 +476,32 @@ Date and time values occur in several header fields. This section
if (reminder.length > spaceIndex) {
reminder = reminder.substring(spaceIndex + 1).trim();
spaceIndex = reminder.indexOf(' ');
if (spaceIndex == -1) {
zoneText = reminder;
} else {
zoneText = reminder.substring(0, spaceIndex);
}
zoneText =
spaceIndex == -1 ? reminder : reminder.substring(0, spaceIndex);
}
}
final dayOfMonth = int.tryParse(dayText);
if (dayOfMonth == null || dayOfMonth < 1 || dayOfMonth > 31) {
print('Invalid day $dayText in date $dateText');

return null;
}
final month = _monthsByName[monthText.toLowerCase()];
if (month == null) {
print('Invalid month $monthText in date $dateText');

return null;
}
final year = int.tryParse(yearText.length == 2 ? '20$yearText' : yearText);
if (year == null) {
print('Invalid year $yearText in date $dateText');

return null;
}
final timeParts = timeText.split(':');
if (timeParts.length < 2) {
print('Invalid time $timeText in date $dateText');

return null;
}
int? second = 0;
Expand All @@ -509,6 +512,7 @@ Date and time values occur in several header fields. This section
}
if (hour == null || minute == null || second == null) {
print('Invalid time $timeText in date $dateText');

return null;
}
if (zoneText.length != 5) {
Expand All @@ -528,17 +532,17 @@ Date and time values occur in several header fields. This section
final timeZoneMinutes = int.tryParse(zoneText.substring(3));
if (timeZoneHours == null || timeZoneMinutes == null) {
print('invalid time zone $zoneText in $dateText');

return null;
}
var dateTime = DateTime.utc(year, month, dayOfMonth, hour, minute, second);
final isWesternTimeZone = zoneText.startsWith('+');
final timeZoneDuration =
Duration(hours: timeZoneHours, minutes: timeZoneMinutes);
if (isWesternTimeZone) {
dateTime = dateTime.subtract(timeZoneDuration);
} else {
dateTime = dateTime.add(timeZoneDuration);
}
dateTime = isWesternTimeZone
? dateTime.subtract(timeZoneDuration)
: dateTime.add(timeZoneDuration);

return dateTime.toLocal();
}
// cSpell:enable
Expand Down

0 comments on commit 301ddab

Please sign in to comment.