From 08d1d5ea35d52b90cf2447a14e8fe0c47c56815e Mon Sep 17 00:00:00 2001 From: Maksim Lin Date: Thu, 29 Jun 2023 14:33:24 +1000 Subject: [PATCH 1/2] fix deprecation, rm old logging --- lib/src/application.dart | 10 +++++----- lib/src/listings.dart | 8 +++----- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/lib/src/application.dart b/lib/src/application.dart index 66618f2..06b8937 100644 --- a/lib/src/application.dart +++ b/lib/src/application.dart @@ -130,8 +130,8 @@ class Application { connect = HttpServer.bind(ip, int.parse(port)); } - runZoned(() { - connect.then((final server) { + runZonedGuarded(() { + connect.then((final server) { log('Server running $ip on port: $port, $MY_HTTP_ROOT_PATH'); server.listen((final request) { log('${request.connectionInfo?.remoteAddress.address}:${request.connectionInfo?.localPort} - ${request.method} ${request.uri}'); @@ -139,9 +139,9 @@ class Application { virtDir.serveRequest(request); }); }); - }, - onError: (Object e, StackTrace stackTrace) => - Log.e('Error running http server: $e $stackTrace')); + }, (error, stack) { + Log.e('Error running http server: $error $stack'); + }); } void watch(final String folder, final Config config) { diff --git a/lib/src/listings.dart b/lib/src/listings.dart index 20e2787..2b9cf12 100644 --- a/lib/src/listings.dart +++ b/lib/src/listings.dart @@ -1,12 +1,10 @@ import 'dart:io'; +import 'package:bonsai/bonsai.dart'; import 'package:front_matter_ml/front_matter_ml.dart' as fm; -import 'package:logging/logging.dart'; import 'package:path/path.dart' as path; import 'package:yaml/yaml.dart' as yaml; -final Logger _logger = Logger('dsg.Generator'); - class ListingConfig { final Map _config; String get path => _config['path'] as String; @@ -43,7 +41,7 @@ Future?>> getListingsMap( final sortFunction = (sortDirection == 'DESC') ? desc : asc; - _logger.info('SORT listing: $key BY: $sortBy'); + Log.d('listings.dart', 'SORT listing: $key BY: $sortBy'); listings[key]?.sort(sortFunction); }); @@ -88,7 +86,7 @@ Future> _getFrontMatter( return (await fm.parseFile(filePath, delimiter: yamldelimiter)) .data.value.cast(); } catch (e) { - _logger.severe(e, 'failed parsing frontmatter in: $filePath'); + Log.e('failed parsing frontmatter in: $filePath', e); return {}; } } From 7e7b9cd86afb729adcb7c57a97ea2b184540512f Mon Sep 17 00:00:00 2001 From: Maksim Lin Date: Thu, 29 Jun 2023 14:40:02 +1000 Subject: [PATCH 2/2] fix analyzer lints --- analysis_options.yaml | 10 +++--- bin/dsg.dart | 2 +- lib/src/application.dart | 10 +++--- lib/src/config.dart | 31 +++++++++-------- lib/src/generator.dart | 73 +++++++++++++++++++++------------------- lib/src/init.dart | 4 +-- lib/src/listings.dart | 12 +++---- lib/src/options.dart | 2 ++ pubspec.lock | 8 +++++ pubspec.yaml | 3 +- 10 files changed, 87 insertions(+), 68 deletions(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index 30dfb95..4e68150 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -1,8 +1,10 @@ +include: package:lints/recommended.yaml + analyzer: - # language: - # strict-casts: true - # strict-inference: true - # strict-raw-types: true + language: + strict-casts: true + strict-inference: true + strict-raw-types: true exclude: - lib/**/*.g.dart - lib/**/*.freezed.dart diff --git a/bin/dsg.dart b/bin/dsg.dart index 122942c..d7f4ba5 100755 --- a/bin/dsg.dart +++ b/bin/dsg.dart @@ -4,7 +4,7 @@ import 'dart:io'; import 'package:bonsai/bonsai.dart'; import 'package:dsg/dsg.dart'; -Future main(List arguments) async { +Future main(List arguments) async { const debug = true; if (debug) { Log.init(true); diff --git a/lib/src/application.dart b/lib/src/application.dart index 06b8937..043115b 100644 --- a/lib/src/application.dart +++ b/lib/src/application.dart @@ -103,21 +103,21 @@ class Application { final ip = config.ip; final port = config.port; - final MY_HTTP_ROOT_PATH = + final myHttpRootPath = config.docroot; //Platform.script.resolve(folder).toFilePath(); late VirtualDirectory virtDir; - void _directoryHandler(final Directory dir, final HttpRequest request) { + void directoryHandler(final Directory dir, final HttpRequest request) { log('$dir'); final indexUri = Uri.file(dir.path).resolve('index.html'); virtDir.serveFile(File(indexUri.toFilePath()), request); } - virtDir = VirtualDirectory(MY_HTTP_ROOT_PATH) + virtDir = VirtualDirectory(myHttpRootPath) ..allowDirectoryListing = true ..followLinks = true ..jailRoot = false; - virtDir.directoryHandler = _directoryHandler; + virtDir.directoryHandler = directoryHandler; Future connect; if (config.usesecureconnection) { @@ -132,7 +132,7 @@ class Application { runZonedGuarded(() { connect.then((final server) { - log('Server running $ip on port: $port, $MY_HTTP_ROOT_PATH'); + log('Server running $ip on port: $port, $myHttpRootPath'); server.listen((final request) { log('${request.connectionInfo?.remoteAddress.address}:${request.connectionInfo?.localPort} - ${request.method} ${request.uri}'); diff --git a/lib/src/config.dart b/lib/src/config.dart index 276fd3f..b8d9400 100644 --- a/lib/src/config.dart +++ b/lib/src/config.dart @@ -1,3 +1,5 @@ +// ignore_for_file: constant_identifier_names + part of dsg; /// Defines default-configurations. @@ -36,12 +38,12 @@ class Config { Config(this._argResults) { _settings[Options._ARG_LOGLEVEL] = 'info'; - _settings[Config._CONF_CONTENT_DIR] = '${_CONFIG_FOLDER}/html/_content'; - _settings[Config._CONF_TEMPLATE_DIR] = '${_CONFIG_FOLDER}/html/_templates'; - _settings[Config._CONF_DATA_DIR] = '${_CONFIG_FOLDER}/html/_data'; - _settings[Config._CONF_LISTINGS_DIR] = '${_CONFIG_FOLDER}/html/_listings'; - _settings[Config._CONF_PARTIALS_DIR] = '${_CONFIG_FOLDER}/html/_partials'; - _settings[Config._CONF_ASSETS_DIR] = '${_CONFIG_FOLDER}/html/_assets'; + _settings[Config._CONF_CONTENT_DIR] = '$_CONFIG_FOLDER/html/_content'; + _settings[Config._CONF_TEMPLATE_DIR] = '$_CONFIG_FOLDER/html/_templates'; + _settings[Config._CONF_DATA_DIR] = '$_CONFIG_FOLDER/html/_data'; + _settings[Config._CONF_LISTINGS_DIR] = '$_CONFIG_FOLDER/html/_listings'; + _settings[Config._CONF_PARTIALS_DIR] = '$_CONFIG_FOLDER/html/_partials'; + _settings[Config._CONF_ASSETS_DIR] = '$_CONFIG_FOLDER/html/_assets'; _settings[Config._CONF_OUTPUT_DIR] = 'web'; _settings[Config._CONF_WORKSPACE_DIR] = '.'; @@ -182,8 +184,9 @@ class Config { void printSettings() { int getMaxKeyLength() { var length = 0; - settings.keys - .forEach((final String key) => length = math.max(length, key.length)); + for (var key in settings.keys) { + length = math.max(length, key.length); + } return length; } @@ -199,14 +202,14 @@ class Config { print('Settings:'); settings.forEach((final String key, final value) { - print(' ${prepareKey(key)} ${value}'); + print(' ${prepareKey(key)} $value'); }); } void printSiteKeys() { - print('Keys for ${configfile}:'); + print('Keys for $configfile:'); _settings.forEach((final String key, final dynamic value) { - print(' ${(key + ':').padRight(20)} $value'); + print(' ${('$key:').padRight(20)} $value'); }); } @@ -234,17 +237,17 @@ class Config { } void _overwriteSettingsWithConfigFile() { - final file = File('${configfolder}/${configfile}'); + final file = File('$configfolder/$configfile'); if (!file.existsSync()) { return; } final map = yaml.loadYaml(file.readAsStringSync()) as yaml.YamlMap; - _settings.keys.forEach((final String key) { + for (var key in _settings.keys) { if (map.containsKey(key)) { _settings[key] = map[key]; print('Found $key in $configfile: ${map[key]}'); } - }); + } } Map _toMap(final dynamic configOption) { diff --git a/lib/src/generator.dart b/lib/src/generator.dart index 109b1ef..3996967 100644 --- a/lib/src/generator.dart +++ b/lib/src/generator.dart @@ -3,7 +3,7 @@ part of dsg; /// Takes a template string (such as a Mustache template) and renders it out to an HTML string /// using the given input values/options. /// -typedef TemplateRenderer = String Function(String template, Map options, PartialsResolver resolver); +typedef TemplateRenderer = String Function(String template, Map options, PartialsResolver resolver); /// Resolved partial-names into mustache.Templates typedef PartialsResolver = mustache.Template Function(String name); @@ -15,12 +15,13 @@ String _outputFormat = 'MMMM dd yyyy'; /// /// Uses [Mustache templates](https://pub.dartlang.org/packages/mustache) by default. /// -TemplateRenderer renderTemplate = (final String? source, final Map options, final PartialsResolver resolver) { +TemplateRenderer renderTemplate = + (final String? source, final Map options, final PartialsResolver resolver) { final template = mustache.Template(source ?? '', htmlEscapeValues: false, partialResolver: resolver, lenient: true); final inFormat = 'yyyy-MM-dd'; - final formatDate = (mustache.LambdaContext ctx) => '${_parseDate(ctx.renderString(), inFormat, _outputFormat)}'; + formatDate(mustache.LambdaContext ctx) => _parseDate(ctx.renderString(), inFormat, _outputFormat); options['formatDate'] = formatDate; @@ -31,6 +32,7 @@ TemplateRenderer renderTemplate = (final String? source, final Map options, fina class Generator { /// Mustache-Renderer strips out newlines + // ignore: constant_identifier_names static const String _NEWLINE_PROTECTOR = '@@@#@@@'; /// Render and output your static site (WARNING: overwrites existing HTML files in output directory). @@ -69,11 +71,11 @@ class Generator { log('Generating .html files...'); for (final file in files) { - final relativeFileName = file.path.replaceAll('${contentDir.path}', '').replaceFirst('/', ''); + final relativeFileName = file.path.replaceAll(contentDir.path, '').replaceFirst('/', ''); final relativePath = path.dirname(relativeFileName).replaceFirst('.', ''); final extension = path.extension(relativeFileName).replaceFirst('.', '').toLowerCase(); - log('\nFile: ${relativeFileName}, Path: $relativePath'); + log('\nFile: $relativeFileName, Path: $relativePath'); final fileContents = file.readAsStringSync(); fm.FrontMatterDocument fmDocument; @@ -133,7 +135,7 @@ class Generator { templateContent, pageOptions, _partialsResolver(partialsDir, isMarkdownSupported: config.usemarkdown)), config); - final outputFilename = '${path.basenameWithoutExtension(relativeFileName)}.${outputExtension}'; + final outputFilename = '${path.basenameWithoutExtension(relativeFileName)}.$outputExtension'; final outputPath = _createOutputPath(outputDir, relativePath); final outputFile = File('${outputPath.path}/$outputFilename'); @@ -143,7 +145,7 @@ class Generator { } for (final image in images) { - final relativeFileName = image.path.replaceAll('${contentDir.path}', '').replaceFirst('/', ''); + final relativeFileName = image.path.replaceAll(contentDir.path, '').replaceFirst('/', ''); final relativePath = path.dirname(relativeFileName).startsWith('.') ? path.dirname(relativeFileName) : path.dirname(relativeFileName).replaceFirst('.', ''); @@ -157,7 +159,7 @@ class Generator { } for (final asset in assets) { - final relativeFileName = asset.path.replaceAll('${assetsDir.path}', '').replaceFirst('/', ''); + final relativeFileName = asset.path.replaceAll(assetsDir.path, '').replaceFirst('/', ''); final relativePath = path.dirname(relativeFileName).replaceFirst('.', ''); final outputPath = _createOutputPath(outputDir, relativePath); @@ -182,13 +184,13 @@ class Generator { /// void _resolvePartialsInYamlBlock( final Directory partialsDir, final Map pageOptions, bool useMarkdown) { - pageOptions.keys.forEach((final String key) { + for (var key in pageOptions.keys) { if (pageOptions[key] is String && (pageOptions[key] as String).contains('->')) { final partial = (pageOptions[key] as String).replaceAll(RegExp(r'[^>]*>'), ''); pageOptions[key] = renderTemplate( - '{{>${partial}}}', pageOptions, _partialsResolver(partialsDir, isMarkdownSupported: useMarkdown)); + '{{>$partial}}', pageOptions, _partialsResolver(partialsDir, isMarkdownSupported: useMarkdown)); } - }); + } } /// Returns a partials-Resolver. The partials-Resolver gets a dot separated name. This name is translated @@ -225,7 +227,7 @@ class Generator { Directory _createOutputPath(final Directory outputDir, final String relativePath) { final relPath = relativePath.isNotEmpty ? '/' : ''; - final outputPath = Directory('${outputDir.path}${relPath}${relativePath}'); + final outputPath = Directory('${outputDir.path}$relPath$relativePath'); if (!outputPath.existsSync()) { outputPath.createSync(recursive: true); } @@ -318,9 +320,9 @@ class Generator { .toList(); } - bool _isMarkdownSupported(final bool markdownForSite, final Map page_options) { + bool _isMarkdownSupported(final bool markdownForSite, final Map pageOptions) { return markdownForSite || - (page_options.containsKey('markdown_templating') && page_options['markdown_templating'] as bool); + (pageOptions.containsKey('markdown_templating') && pageOptions['markdown_templating'] as bool); } Map _fillInDefaultPageOptions(final String defaultDateFormat, final File file, @@ -331,22 +333,22 @@ class Generator { pageOptions['_site'] = siteOptions; /// See [DateFormat](https://api.dartlang.org/docs/channels/stable/latest/intl/DateFormat.html) for formatting options - final date_format = DateFormat(defaultDateFormat); + final dateFormat = DateFormat(defaultDateFormat); if (pageOptions.containsKey('date_format')) { - final page_date_format = DateFormat(pageOptions['date_format'] as String); - pageOptions['_date'] = page_date_format.format(file.lastModifiedSync()); + final pageDateFormat = DateFormat(pageOptions['date_format'] as String); + pageOptions['_date'] = pageDateFormat.format(file.lastModifiedSync()); } else { - pageOptions['_date'] = date_format.format(file.lastModifiedSync()); + pageOptions['_date'] = dateFormat.format(file.lastModifiedSync()); } return pageOptions; } - Map _getDataMap(final List dataFiles) { + Map _getDataMap(final List dataFiles) { final dataMap = {}; - dataFiles.forEach((final File file) { + for (var file in dataFiles) { if (file.existsSync()) { dynamic data; if (path.extension(file.path) == '.yaml') { @@ -358,7 +360,7 @@ class Generator { final filename = path.basenameWithoutExtension(file.path).toLowerCase(); dataMap[filename] = data; } - }); + } return dataMap; } @@ -380,13 +382,13 @@ class Generator { if (relativeFileName.contains('/')) { nestingLevel = relativeFileName.split('/').length - 1; for (var counter = 0; counter < nestingLevel; counter++) { - backPath = backPath + '../'; + backPath = '$backPath../'; } } final pathWithoutExtension = path.withoutExtension(relativeFileName); // final String portablePath = pathWithoutExtension.replaceAll( RegExp('(/|\\\\\)'),':'); - final pageIndicator = pathWithoutExtension.replaceAll(RegExp('(/|\\\\\)'), '_'); + final pageIndicator = pathWithoutExtension.replaceAll(RegExp('(/|\\\\)'), '_'); pageOptions['_page'] = { 'filename': pathWithoutExtension, 'pageindicator': pageIndicator, @@ -402,7 +404,8 @@ class Generator { } File _getTemplateFor( - final File file, final Map page_options, final List templates, final String defaultTemplate) { + final File file, final Map pageOptions, final List templates, + final String defaultTemplate) { final filenameWithoutExtension = path.basenameWithoutExtension(file.path); final filepath = path.normalize(file.path); @@ -410,9 +413,9 @@ class Generator { //_logger.info('Templates: ${templates}, Default: ${defaultTemplate}'); try { - if (page_options.containsKey('template')) { + if (pageOptions.containsKey('template')) { template = templates - .firstWhere((final File file) => path.basenameWithoutExtension(file.path) == page_options['template']); + .firstWhere((final File file) => path.basenameWithoutExtension(file.path) == pageOptions['template']); } else if (defaultTemplate.isNotEmpty) { template = templates.firstWhere((final File file) { return path.basenameWithoutExtension(file.path) == path.basenameWithoutExtension(defaultTemplate); @@ -432,12 +435,12 @@ class Generator { /// Currently only supports replacing Unix-style relative paths. /// String _fixPathRefs(String html, final Config config) { - var relative_output = path.relative(config.outputfolder, from: config.templatefolder); + var relativeOutput = path.relative(config.outputfolder, from: config.templatefolder); - relative_output = '$relative_output/'.replaceAll('\\', '/'); + relativeOutput = '$relativeOutput/'.replaceAll('\\', '/'); //_logger.info(relative_output); - html = html.replaceAll('src="$relative_output', 'src="').replaceAll('href="$relative_output', 'href="'); + html = html.replaceAll('src="$relativeOutput', 'src="').replaceAll('href="$relativeOutput', 'href="'); return html; } @@ -448,25 +451,25 @@ class Generator { final Map pageOptions, final Config config) { check(relativeFileName).isNotEmpty(); - log(' --- ${(relativeFileName + " ").padRight(76, "-")}'); + log(' --- ${("$relativeFileName ").padRight(76, "-")}'); - void _showMap(final Map values, final int nestingLevel) { + void showMap(final Map values, final int nestingLevel) { values.forEach((final String key, final dynamic value) { log(' ${"".padRight(nestingLevel * 2)} $key.'); if (value is Map) { - _showMap(value as Map, nestingLevel + 1); + showMap(value as Map, nestingLevel + 1); } else { var valueAsString = - value.toString().replaceAll(RegExp('(\n|\r|\\s{2,}|${_NEWLINE_PROTECTOR})', multiLine: true), ''); + value.toString().replaceAll(RegExp('(\n|\r|\\s{2,}|$_NEWLINE_PROTECTOR)', multiLine: true), ''); valueAsString = valueAsString.substring(0, math.min(50, math.max(valueAsString.length, 0))); - log(' ${"".padRight(nestingLevel * 2)} $key -> [${valueAsString}]'); + log(' ${"".padRight(nestingLevel * 2)} $key -> [$valueAsString]'); } }); } - _showMap(pageOptions, 0); + showMap(pageOptions, 0); log(' ${"".padRight(80, "-")}'); } } diff --git a/lib/src/init.dart b/lib/src/init.dart index 554af37..337219d 100644 --- a/lib/src/init.dart +++ b/lib/src/init.dart @@ -5,14 +5,14 @@ part of dsg; /// class Init { - static const String _STYLES_FOLDER = 'styles'; + static const String _stylesFolder = 'styles'; Future createDirs(final Config config) { return Future.wait([ _createDir(config.templatefolder), _createDir(config.contentfolder), - _createDir('${config.contentfolder}/$_STYLES_FOLDER'), + _createDir('${config.contentfolder}/$_stylesFolder'), _createDir(config.outputfolder), _createDir(config.configfolder) ]); diff --git a/lib/src/listings.dart b/lib/src/listings.dart index 2b9cf12..e4c2633 100644 --- a/lib/src/listings.dart +++ b/lib/src/listings.dart @@ -17,7 +17,7 @@ class ListingConfig { /// Returns a Map, wher each key is the name of "listing", /// the a listing is a List of Maps, where each Map represents the /// metadata for a MD file, including any YAMl Frontmatter that file has -Future?>> getListingsMap( +Future>?>> getListingsMap( Directory dir, String yamlDelimiter) async { final listingConfigs = _listingsFilesIn(dir); @@ -26,7 +26,7 @@ Future?>> getListingsMap( final listingsMap = configsMap .map((key, value) => MapEntry(key, _dirList(value, yamlDelimiter))); - final listings = ?>{}; + final listings = >?>{}; await Future.forEach(listingsMap.keys, (key) async { listings[key] = await listingsMap[key]; @@ -34,9 +34,9 @@ Future?>> getListingsMap( final sortBy = configsMap[key]?.sortby.split(' ')[0]; final sortDirection = configsMap[key]?.sortby.split(' ')[1]; - final asc = (dynamic a, dynamic b) => + asc(dynamic a, dynamic b) => a[sortBy].toString().compareTo(b[sortBy].toString()); - final desc = (dynamic a, dynamic b) => + desc(dynamic a, dynamic b) => b[sortBy].toString().compareTo(a[sortBy].toString()); final sortFunction = (sortDirection == 'DESC') ? desc : asc; @@ -95,7 +95,7 @@ Future> _getFrontMatter( Map _getListingConfigMap(final List listingFiles) { final listingMap = {}; - listingFiles.forEach((final File file) { + for (var file in listingFiles) { if (file.existsSync()) { dynamic data; if (path.extension(file.path) == '.yaml') { @@ -104,7 +104,7 @@ Map _getListingConfigMap(final List listingFiles) { final filename = path.basenameWithoutExtension(file.path).toLowerCase(); listingMap[filename] = ListingConfig((data as yaml.YamlMap).value); } - }); + } return listingMap; } diff --git a/lib/src/options.dart b/lib/src/options.dart index a3235b1..7e45915 100644 --- a/lib/src/options.dart +++ b/lib/src/options.dart @@ -1,3 +1,5 @@ +// ignore_for_file: constant_identifier_names + part of dsg; /// Commandline options diff --git a/pubspec.lock b/pubspec.lock index 83b2261..388fb5c 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -345,6 +345,14 @@ packages: url: "https://pub.dev" source: hosted version: "4.8.1" + lints: + dependency: "direct dev" + description: + name: lints + sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452" + url: "https://pub.dev" + source: hosted + version: "2.1.1" logging: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 433c64c..116ad3c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -32,4 +32,5 @@ dev_dependencies: test: any grinder: any build_runner: any - build_test: any \ No newline at end of file + build_test: any + lints: ^2.1.1 \ No newline at end of file