diff --git a/LICENSE b/LICENSE index 8cc2c1c..0a31d3e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,14 @@ -Copyright (c) 2015, . +Copyright (c) 2015, Michael Mitterer (office@mikemitterer.at), +IT-Consulting and Development Limited, Austrian Branch + All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright @@ -8,14 +16,16 @@ modification, are permitted provided that the following conditions are met: * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of the nor the + * Neither the name of the Michael Mitterer, IT-Consulting + and Development Limited, Austrian Branch, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DISCLAIMED. IN NO EVENT SHALL Michael Mitterer, +IT-Consulting and Development Limited, Austrian Branch, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND diff --git a/Prettify.iml b/Prettify.iml index a8c32d1..13e67a6 100644 --- a/Prettify.iml +++ b/Prettify.iml @@ -3,16 +3,15 @@ + + - - - - - - - - - + + + + + + diff --git a/README.md b/README.md index d106e53..9aee205 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -# prettify - -A library for Dart developers. It is awesome. +# prettify - Code prettifier for Dart +Beautify the code snippets in your web page +Based on Googles [google-code-prettify] ## Usage @@ -16,4 +16,26 @@ A simple usage example: Please file feature requests and bugs at the [issue tracker][tracker]. -[tracker]: http://example.com/issues/replaceme +###License### + + Copyright 2015 Michael Mitterer (office@mikemitterer.at), + IT-Consulting and Development Limited, Austrian Branch + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + either express or implied. See the License for the specific language + governing permissions and limitations under the License. + +If this plugin is helpful for you - please [(Circle)](http://gplus.mikemitterer.at/) me +or **star** this repo here on GitHub + +[tracker]: https://github.com/MikeMitterer/dart-prettify/issues +[google-code]: https://code.google.com/p/google-code-prettify/ +[usage]: \ No newline at end of file diff --git a/example/index.html b/example/index.html new file mode 100644 index 0000000..3f57dbc --- /dev/null +++ b/example/index.html @@ -0,0 +1,18 @@ + + + + + + + + Prettify - Beautify the code snippets in your web page + + + +The contents you are looking for have moved. You will be redirected to the new location automatically. +Please bookmark the correct page at http://prettify.mikemitterer.at/usage/ +

Last update: {{lastupdate}}

+ + + + diff --git a/example/theme/.gitignore b/example/usage/.gitignore similarity index 100% rename from example/theme/.gitignore rename to example/usage/.gitignore diff --git a/example/theme/CHANGELOG.md b/example/usage/CHANGELOG.md similarity index 100% rename from example/theme/CHANGELOG.md rename to example/usage/CHANGELOG.md diff --git a/example/theme/LICENSE b/example/usage/LICENSE similarity index 70% rename from example/theme/LICENSE rename to example/usage/LICENSE index 8cc2c1c..0a31d3e 100644 --- a/example/theme/LICENSE +++ b/example/usage/LICENSE @@ -1,6 +1,14 @@ -Copyright (c) 2015, . +Copyright (c) 2015, Michael Mitterer (office@mikemitterer.at), +IT-Consulting and Development Limited, Austrian Branch + All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright @@ -8,14 +16,16 @@ modification, are permitted provided that the following conditions are met: * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of the nor the + * Neither the name of the Michael Mitterer, IT-Consulting + and Development Limited, Austrian Branch, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DISCLAIMED. IN NO EVENT SHALL Michael Mitterer, +IT-Consulting and Development Limited, Austrian Branch, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND diff --git a/example/theme/README.md b/example/usage/README.md similarity index 100% rename from example/theme/README.md rename to example/usage/README.md diff --git a/example/theme/pubspec.yaml b/example/usage/pubspec.yaml similarity index 76% rename from example/theme/pubspec.yaml rename to example/usage/pubspec.yaml index 649589c..dc3b8e7 100644 --- a/example/theme/pubspec.yaml +++ b/example/usage/pubspec.yaml @@ -1,4 +1,4 @@ -name: 'theme' +name: usage version: 0.0.1 description: An absolute bare-bones web app. #author: @@ -14,3 +14,8 @@ dependencies: wsk_material: any + logging: any + logging_handlers: any + console_log_handler: any + + diff --git a/example/theme/web/images/app-icon.png b/example/usage/web/images/app-icon.png similarity index 100% rename from example/theme/web/images/app-icon.png rename to example/usage/web/images/app-icon.png diff --git a/example/theme/web/images/desktop-handsfree-hero.jpg b/example/usage/web/images/desktop-handsfree-hero.jpg similarity index 100% rename from example/theme/web/images/desktop-handsfree-hero.jpg rename to example/usage/web/images/desktop-handsfree-hero.jpg diff --git a/example/theme/web/index.html b/example/usage/web/index.html similarity index 99% rename from example/theme/web/index.html rename to example/usage/web/index.html index 1c2fb25..5671f83 100644 --- a/example/theme/web/index.html +++ b/example/usage/web/index.html @@ -57,10 +57,12 @@

sons-of-obsidian Theme - for Prettify - + for Prettify

Beautify the code snippets in your web page.

+

The code for this Dart-Package ist hosted on + GitHub +

diff --git a/example/theme/web/main.dart b/example/usage/web/main.dart similarity index 100% rename from example/theme/web/main.dart rename to example/usage/web/main.dart diff --git a/example/theme/web/styles/_colors.scss b/example/usage/web/styles/_colors.scss similarity index 100% rename from example/theme/web/styles/_colors.scss rename to example/usage/web/styles/_colors.scss diff --git a/example/theme/web/styles/main.css b/example/usage/web/styles/main.css similarity index 100% rename from example/theme/web/styles/main.css rename to example/usage/web/styles/main.css diff --git a/example/theme/web/styles/main.scss b/example/usage/web/styles/main.scss similarity index 100% rename from example/theme/web/styles/main.scss rename to example/usage/web/styles/main.scss diff --git a/gensamples b/gensamples new file mode 120000 index 0000000..748a977 --- /dev/null +++ b/gensamples @@ -0,0 +1 @@ +tools/gensamples.dart \ No newline at end of file diff --git a/pubspec.yaml b/pubspec.yaml index 11f54a4..11ae91f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -3,10 +3,20 @@ description: Beautify the code snippets in your web page version: 0.0.1 author: Mike Mitterer -homepage: https://github.com/MikeMitterer/dart-prettify +homepage: http://prettify.mikemitterer.at/ dependencies: # browser: any dev_dependencies: unittest: any + + # for the samples + wsk_material: any + + logging: any + logging_handlers: any + console_log_handler: any + + args: any + diff --git a/tools/buildinfolder.sh b/tools/buildinfolder.sh new file mode 100755 index 0000000..52b2057 --- /dev/null +++ b/tools/buildinfolder.sh @@ -0,0 +1,119 @@ +#!/bin/sh + +#------------------------------------------------------------------------------ +# Little script makes the dart-code more readable. +# Was +# final ProcessResult result = Process.runSync( "sh", [ '-c', '(cd ${folder} && pub build)' ]); +# + +FOLDER=$2 +if test "${FOLDER}" == "" +then + FOLDER=`pwd` +#elif [ -d ${FOLDER} ] +#then +# echo "$FOLDER does not exist!" +# exit 2 +fi + +cd ${FOLDER} + +#------------------------------------------------------------------------------ +# Functions +# + +buildCss() { + echo "Running sassc + autoprefixer in `pwd`" + + SCSSFOUND=0 + ERRORSTATE=1 + if [ -e "web/demo.scss" ] + then + echo "sassc demo.scss -> demo.css && autoprefixer demo.css" + sassc "web/demo.scss" "web/demo.css" && autoprefixer "web/demo.css" + ERRORSTATE=$? + SCCSFOUND=1 + fi + + if [ -e "web/assets/scss/styleguide.scss" ] + then + echo "sassc styleguide.scss -> styleguide.scss && autoprefixer styleguide.scss" + sassc "web/assets/scss/styleguide.scss" "web/assets/css/styleguide.css" && autoprefixer "web/assets/css/styleguide.css" + ERRORSTATE=$? + SCCSFOUND=1 + fi + + if [ ${SCCSFOUND} -ne 1 ]; then + echo "No SCSS-File found!" + exit 1 + fi + + if [ ${ERRORSTATE} -ne 0 ]; then + exit ${ERRORSTATE} + fi + +} + +buildJS() { + echo "Building sample in `pwd`" + # Now - run build + pub build + + ERRORSTATE=$? + if [ ${ERRORSTATE} -ne 0 ]; then + exit ${ERRORSTATE} + fi +} + +pubUpdate() { + echo "'pub update' in `pwd`" + pub update + + ERRORSTATE=$? + if [ ${ERRORSTATE} -ne 0 ]; then + exit ${ERRORSTATE} + fi +} + +#------------------------------------------------------------------------------ +# Options +# + +usage() { + echo + echo "Usage: `basename $0` [ options ] " + echo " --withcss Calls sassc + autoprefixer and makes a 'pub build'" + echo " --jsonly 'pub build' in `pwd`" + echo " --cssonly Calls sassc + autoprefixer" + echo " --update 'pub build' in `pwd`" + echo +} + +case "$1" in + help|-help|--help) + usage + ;; + + withcss|-withcss|--withcss) + buildCss + buildJS + ;; + + jsonly|-jsonly|--jsonly) + buildJS + ;; + + cssonly|-cssonly|--cssonly) + buildCss + ;; + + update|-update|--update) + pubUpdate + ;; + + *) + usage + ;; + +esac +exit 0 diff --git a/tools/gensamples.dart b/tools/gensamples.dart new file mode 100755 index 0000000..90c1372 --- /dev/null +++ b/tools/gensamples.dart @@ -0,0 +1,480 @@ +#!/usr/bin/env dart + +import 'dart:io'; +import 'dart:async'; +import 'dart:collection'; +import 'dart:convert'; +import 'dart:math'; + +import 'package:args/args.dart'; + +import 'package:logging/logging.dart'; +import 'package:logging_handlers/logging_handlers_shared.dart'; + +import 'package:validate/validate.dart'; + +class Application { + final Logger _logger = new Logger("buildsamples.Application"); + + final Options options; + + Application() : options = new Options(); + + void run(List args) { + + try { + final ArgResults argResults = options.parse(args); + final Config config = new Config(argResults); + + _configLogging(config.loglevel); + + if (argResults.wasParsed(Options._ARG_HELP) || (config.dirstoscan.length == 0 && args.length == 0)) { + options.showUsage(); + return; + } + + if(argResults.wasParsed(Options._ARG_SETTINGS)) { + config.printSettings(); + return; + } + + if(argResults.wasParsed(Options._ARG_SHOW_SAMPLES)) { + _iterateThroughDirSync(config.samplesfolder,new List(),_onlyDirs,(final File file) { + _logger.info(" - ${file.path}"); + }); + return; + } + + bool foundOptionToWorkWith = false; + + if(argResults.wasParsed(Options._ARG_UPDATE )) { + foundOptionToWorkWith = true; + _iterateThroughDirSync(config.samplesfolder,new List(),_onlyDirs,(final File file) { + pubUpdate(new File(file.path)); + }); + } + + if(argResults.wasParsed(Options._ARG_SASS )) { + foundOptionToWorkWith = true; + _iterateThroughDirSync(config.samplesfolder,new List(),_onlyDirs,(final File file) { + compileSassAndAutoPrefixCSS(new File(file.path)); + }); + } + + if(argResults.wasParsed(Options._ARG_BUILD )) { + foundOptionToWorkWith = true; + _iterateThroughDirSync(config.samplesfolder,new List(),_onlyDirs,(final File file) { + buildSampleInFolder(new File(file.path)); + }); + } + + if(argResults.wasParsed(Options._ARG_CPY_BUILD )) { + foundOptionToWorkWith = true; + _iterateThroughDirSync(config.samplesfolder,new List(),_onlyDirs,(final File file) { + copyExampleBuildToRootBuild(new File(file.path)); + }); + copyIndexHtmlToExample(); + } + + if(argResults.wasParsed(Options._ARG_RSYNC)) { + foundOptionToWorkWith = true; + rsyncBuildExample(); + } + + if(!foundOptionToWorkWith) { + options.showUsage(); + } + } + + on FormatException + catch (error) { + options.showUsage(); + } + } + + void pubUpdate(final File file) async { + Validate.notNull(file); + Validate.isTrue(FileSystemEntity.isDirectorySync(file.path)); + + final String folder = file.path; + _logger.info("'pub update' in ${folder}"); + + final ProcessResult result = Process.runSync("tools/buildinfolder.sh", [ '--update' ,folder ]); + if(result.exitCode != 0) { + _logger.severe("'pub update' faild with: ${(result.stderr as String).trim()}!"); + _vickiSay("error with pup update"); + } + + _logger.info(result.stdout); + _logger.info("Done!\n"); + } + + void buildSampleInFolder(final File file) async { + Validate.notNull(file); + Validate.isTrue(FileSystemEntity.isDirectorySync(file.path)); + + final String folder = file.path; + _logger.info("Building sample in ${folder}"); + + final ProcessResult result = Process.runSync("tools/buildinfolder.sh", [ '--jsonly' ,folder ]); + if(result.exitCode != 0) { + _logger.severe("run faild with: ${(result.stderr as String).trim()}!"); + _vickiSay("error in $folder"); + } + + _logger.info(result.stdout); + _logger.info("Done!\n"); + } + + void copyExampleBuildToRootBuild(final File file) { + Validate.notNull(file); + Validate.isTrue(FileSystemEntity.isDirectorySync(file.path)); + + final Directory webDir = new Directory("${file.path}/build/web"); + final Directory buildDir = new Directory("build/${file.path}"); + + if(!webDir.existsSync()) { + _logger.severe("${webDir.path} does not exist!"); + return; + } + + if(buildDir.existsSync()) { + buildDir.deleteSync(recursive: true); + } + + _logger.info("copy ${webDir.path} -> ${buildDir.path}"); + + final File src = new File(webDir.path); + final File target = new File(buildDir.path); + _copySubdirs(src,target); + + _logger.info(" - done!"); + } + + void copyIndexHtmlToExample() { + final File src = new File("example/index.html"); + final File target = new File("build/example/index.html"); + + final String content = src.readAsStringSync().replaceAll("{{lastupdate}}",new DateTime.now().toIso8601String()); + if(target.existsSync()) { + target.deleteSync(); + } + target.writeAsString(content); + _logger.info("index.html copied and 'last update date' updated!"); + } + + /// More infos about rsync without PW: + /// http://www.thegeekstuff.com/2011/07/rsync-over-ssh-without-password/ + /// http://www.thegeekstuff.com/2008/06/perform-ssh-and-scp-without-entering-password-on-openssh/ + void rsyncBuildExample() { + _logger.info("RSync build/web..."); + + // rsync -avz -e ssh build/example/ bcadmin@vhost2.mikemitterer.at:/home/wskan82301/www/ + Process.start("rsync", [ '-avz', '-e', 'ssh', 'build/example/', 'bcadmin@vhost2.mikemitterer.at:/home/prett26810/www/' ]) + .then((final Process process) { + + process.stdout.transform(UTF8.decoder).listen((final String data) { + _logger.info(data); + }); + + // Get the exit code from the new process. + process.exitCode.then((exitCode) { + _logger.info('Exit code: $exitCode'); // Prints 'exit code: 0'. + }); + + }); + } + + void compileSassAndAutoPrefixCSS(final File sampleFolder) { + Validate.notNull(sampleFolder); + + File sassFile = new File("${sampleFolder.path}/web/demo.scss"); + File cssFile = new File("${sampleFolder.path}/web/demo.css"); + if(!sassFile.existsSync()) { + sassFile = new File("${sampleFolder.path}/web/assets/scss/styleguide.scss"); + cssFile = new File("${sampleFolder.path}/web/assets/css/styleguide.css"); + if(!sassFile.existsSync()) { + _logger.warning("Could not find wether demo.scss nor styleguide.scss"); + return; + } + } + + _logger.info("Compiling ${sassFile.path} -> ${cssFile.path}"); + final ProcessResult result = Process.runSync("sassc", [ sassFile.path, cssFile.path ]); + if(result.exitCode != 0) { + _logger.info("sassc faild with: ${(result.stderr as String).trim()}!"); + _vickiSay("got a sassc error"); + return; + } + + _logger.info("Autoprefixing ${cssFile.path}"); + final ProcessResult prefixResult = Process.runSync("autoprefixer", [ cssFile.path ]); + if(prefixResult.exitCode != 0) { + _logger.info("autoprefixer faild with: ${(prefixResult.stderr as String).trim()}!"); + _vickiSay("autoprefixer faild"); + } + } + + + // -- private ------------------------------------------------------------- + + void _vickiSay(final String sentence) { + Validate.notBlank(sentence); + + final ProcessResult result = Process.runSync( "say", [ '-v', "Vicki",'-r', '200', sentence.replaceFirst("wsk_","") ]); + if(result.exitCode != 0) { + _logger.severe("run faild with: ${(result.stderr as String).trim()}!"); + } + } + + /// Goes through the files + void _iterateThroughDirSync(final String dir,final List foldersToExclude, + bool isEntityOK(final FileSystemEntity entity), void callback(final File file) ) { + + Validate.notNull(foldersToExclude); + Validate.notNull(isEntityOK); + Validate.notNull(callback); + + _logger.info("Scanning: $dir"); + + // its OK if the path starts with packages but not if the path contains packages (avoid recursion) + final RegExp regexp = new RegExp("^/*packages/*"); + + final Directory directory = new Directory(dir); + if (directory.existsSync()) { + + directory.listSync(recursive: false).where((final FileSystemEntity entity) { + _logger.fine("Entity: ${entity}"); + + for(final String folder in foldersToExclude) { + if(entity.path.contains(folder)) { + return false; + } + } + + if(entity.path.contains("packages") || entity.path.contains("/.") || entity.path.startsWith(".")) { + // return only true if the path starts!!!!! with packages + //return entity.path.contains(regexp); + return false; + } + + return isEntityOK(entity); + + }).any((final File file) { + //_logger.fine(" Found: ${file}"); + callback(file); + }); + } + } + + void _copySubdirs(final File sourceDir, final File targetDir, { int level: 0 } ) { + Validate.notNull(sourceDir); + Validate.notNull(targetDir); + + _logger.fine("Start!!!! ${sourceDir.path} -> ${targetDir.path} , Level: $level"); + final Directory directory = new Directory(sourceDir.path); + directory.listSync(recursive: false).where((final FileSystemEntity entity) { + // _logger.info("Check ${entity.path}"); + + if(entity.path.startsWith(".") || entity.path.contains("/.")) { + return false; + } + if(FileSystemEntity.isLinkSync(entity.path)) { + return false; + } + + return true; + + }).forEach((final FileSystemEntity entity) { + //_logger.info("D ${entity.path}"); + + if (FileSystemEntity.isDirectorySync(entity.path)) { + final File src = new File(entity.path); + final File target = new File(entity.path.replaceFirst(sourceDir.path,"")); + _copySubdirs(new File("${entity.path}"),new File("${targetDir.path}${target.path}"),level: ++level); + + } else { + if(level >= 0) { + final File src = new File(entity.path); + final File target = new File("${targetDir.path}${entity.path.replaceFirst(sourceDir.path,"")}"); + if(!target.existsSync()) { + target.createSync(recursive: true); + } + _logger.fine(" copy ${src.path} -> ${target.path} (Level $level)..."); + src.copySync(target.path); + } + } + }); + } + + bool _onlyDirs(final FileSystemEntity entity) { + return FileSystemEntity.isDirectorySync(entity.path); + } + + void _configLogging(final String loglevel) { + Validate.notBlank(loglevel); + + hierarchicalLoggingEnabled = false; // set this to true - its part of Logging SDK + + // now control the logging. + // Turn off all logging first + switch(loglevel) { + case "fine": + case "debug": + Logger.root.level = Level.FINE; + break; + + case "warning": + Logger.root.level = Level.SEVERE; + break; + + default: + Logger.root.level = Level.INFO; + } + + Logger.root.onRecord.listen(new LogPrintHandler(messageFormat: "%m")); + } +} + + +class Options { + static const APPNAME = 'gensamples'; + + static const _ARG_HELP = 'help'; + static const _ARG_LOGLEVEL = 'loglevel'; + static const _ARG_SETTINGS = 'settings'; + static const _ARG_SHOW_SAMPLES = 'showsamples'; + static const _ARG_BUILD = 'build'; + static const _ARG_SASS = 'sass'; + static const _ARG_UPDATE = 'update'; + static const _ARG_CPY_BUILD = 'copybuild'; + static const _ARG_RSYNC = 'rsync'; + + final ArgParser _parser; + + Options() : _parser = Options._createParser(); + + ArgResults parse(final List args) { + Validate.notNull(args); + return _parser.parse(args); + } + + void showUsage() { + print("Usage: $APPNAME [options]"); + _parser.getUsage().split("\n").forEach((final String line) { + print(" $line"); + }); + + print(""); + print("Sample: (usual workflow)"); + print(""); + print(" 'pub update' for every example: '$APPNAME -u'"); + print(" 'pub build' for every example: '$APPNAME -b'"); + print(" 'Copy example//build/web to build/example/: '$APPNAME -c'"); + print(" 'Rsyncs build/example to webserver: '$APPNAME -r'"); + print(""); + } + + // -- private ------------------------------------------------------------- + + static ArgParser _createParser() { + final ArgParser parser = new ArgParser() + + ..addFlag(_ARG_HELP, abbr: 'h', negatable: false, help: "Shows this message") + ..addFlag(_ARG_SETTINGS, abbr: 's', negatable: false, help: "Prints settings") + ..addFlag(_ARG_SHOW_SAMPLES, abbr: 'x', negatable: false, help: "Show samples") + ..addFlag(_ARG_BUILD, abbr: 'b', negatable: false, help: "Build your samples") + ..addFlag(_ARG_SASS, abbr: 'a', negatable: false, help: "sassc + autoprefixer") + ..addFlag(_ARG_UPDATE, abbr: 'u', negatable: false, help: "pub update for samples") + ..addFlag(_ARG_CPY_BUILD, abbr: 'c', negatable: false, help: "Copy example-build to root-build") + ..addFlag(_ARG_RSYNC, abbr: 'r', negatable: false, help: "RSync's build/example") + + ..addOption(_ARG_LOGLEVEL, abbr: 'v', help: "[ info | debug | warning ]") + ; + + return parser; + } +} + +/** + * Defines default-configurations. + * Most of these configs can be overwritten by commandline args. + */ +class Config { + final Logger _logger = new Logger("buildsamples.Config"); + + final ArgResults _argResults; + final Map _settings = new Map(); + + Config(this._argResults) { + + _settings[Options._ARG_LOGLEVEL] = 'info'; + _settings[Options._ARG_SHOW_SAMPLES] = 'example'; + + _overwriteSettingsWithArgResults(); + } + + List get dirstoscan => _argResults.rest; + + String get loglevel => _settings[Options._ARG_LOGLEVEL]; + + String get samplesfolder => _settings[Options._ARG_SHOW_SAMPLES]; + + Map get settings { + final Map settings = new Map(); + + settings["loglevel"] = loglevel; + settings["Samples folder"] = samplesfolder; + + if(dirstoscan.length > 0) { + settings["Dirs to scan"] = dirstoscan.join(", "); + } + + return settings; + } + + + void printSettings() { + + int getMaxKeyLength() { + int length = 0; + settings.keys.forEach((final String key) => length = max(length,key.length)); + return length; + } + + final int maxKeyLeght = getMaxKeyLength(); + + String prepareKey(final String key) { + return "${key[0].toUpperCase()}${key.substring(1)}:".padRight(maxKeyLeght + 1); + } + + print("Settings:"); + settings.forEach((final String key,final String value) { + print(" ${prepareKey(key)} $value"); + }); + } + + // -- private ------------------------------------------------------------- + + _overwriteSettingsWithArgResults() { + + /// Makes sure that path does not end with a / + String checkPath(final String arg) { + String path = arg; + if(path.endsWith("/")) { + path = path.replaceFirst(new RegExp("/\$"),""); + } + return path; + } + + if(_argResults.wasParsed(Options._ARG_LOGLEVEL)) { + _settings[Options._ARG_LOGLEVEL] = _argResults[Options._ARG_LOGLEVEL]; + } + } +} + +void main(List arguments) { + final Application application = new Application(); + application.run( arguments ); +} +