diff --git a/concepts/strings/about.md b/concepts/strings/about.md index 734cf5d9..874f8bbe 100644 --- a/concepts/strings/about.md +++ b/concepts/strings/about.md @@ -16,18 +16,54 @@ val s = "Escape backslash \\." // Escape backslash \. ``` -Raw strings use 3 double-quotes, and can contain arbitrary text (no need for escaping). -Multiline strings are also supported, including flexible handling of indents. +Multi-line strings are surrounded by 3 double-quotes, and can contain arbitrary text (no need for escaping). ```kotlin val multi = """I'm a - |multi-line - |string with special characters \ \t """ + multi-line + string with special characters \ \t """ +//I'm a +// multi-line +// string with special characters \ \t +``` + +Use [trimIndent][trimIndent-doc] to remove the common indenting from the lines. +This is useful for formatting the string: + +```kotlin +val multi = """ + I'm a + multi-line + string""".trimIndent() -multi.trimMargin() // delimiter defaults to | but can be specified //I'm a -//multi-line -//string with special characters \ \t +// multi-line +//string +``` + +Alternatively, [trimMargin][trimMargin-doc] lets you specify a delimiter. +Each line in the `String` then begins after the delimiter. +The delimiter defaults to `|`, but you can specify a different delimiter as a parameter. +For example: + +```kotlin +val multi = """ + |I'm a + | multi-line + |string""".trimMargin() + +//I'm a +// multi-line +//string + +val multi2 = """ + start>I'm a + start> multi-line + start>string""".trimMargin("start>") + +//I'm a +// multi-line +//string ``` Strings can be concatenated with `+`, but this is best limited to short and simple cases. @@ -70,7 +106,7 @@ Mostly, these are [`extensions functions`][ref-extensions] rather than members o ~~~~exercism/note Kotlin's rather complex [documentation][ref-string-functions] pages hide extension functions in the default view. -At moment of writing this, the most valuable content is hidden in a tab named `Members and Extensions`. +At moment of writing this, the most valuable content is hidden in a tab named `Members & Extensions`. Click it to expand this section and see all the members and extensions available on the `String` class. [ref-string-functions]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-string/ @@ -85,15 +121,19 @@ str.length // => 12 (a property, not a function) str.elementAt(6) // => W str.elementAtOrNull(20) // => null (index out of range) str.substring(6, 11) // => "World" +str.substringAfter(" ") // => "World!" + +str.lowercase() // => "hello world!" +str.uppercase() // => "HELLO WORLD!" -str.lowercase() // => "hello world!" -str.uppercase() // => "HELLO WORLD!" +str.startsWith("Hel") // => true +str.endsWith("xyz") // => false +str.indexOf("0") // => 4 -str.startsWith("Hel") // => true -str.endsWith("xyz") // => false +str.toCharArray() // => [H, e, l, l, o, , W, o, r, l, d, !] +"42".toInt() + 1 // => 43 (parsing; see also toFloat) -str.toCharArray() // => [H, e, l, l, o, , W, o, r, l, d, !] -"42".toInt() + 1 // => 43 (parsing; see also toFloat) +"Howdy! ".trim() // => "Howdy" ``` ## Building a string @@ -157,3 +197,5 @@ val countDown = buildString { [ref-sb-deleterange]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/-string-builder/#-1622040372%2FFunctions%2F-956074838 [ref-buildstring]: https://kotlinlang.org/docs/java-to-kotlin-idioms-strings.html#build-a-string [ref-jointostring]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.collections/join-to-string.html +[trimIndent-doc]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/trim-indent.html +[trimMargin-doc]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/trim-margin.html diff --git a/concepts/strings/introduction.md b/concepts/strings/introduction.md index 88d55e1c..465b38b3 100644 --- a/concepts/strings/introduction.md +++ b/concepts/strings/introduction.md @@ -6,27 +6,63 @@ A [`string`][ref-string] in Kotlin is an immutable sequence of Unicode character [`Unicode`][wiki-unicode] means that most of the world's writing systems can be represented, but (in contrast to older languages such as C) there is no 1:1 mapping between characters and bytes. -A string is usually surrounded by double-quotes `" "`. +A string is surrounded by double-quotes `" "`. -Some characters need escaping: `\'`, `\\`, plus the usual non-printing characters such as `\t` (tab) and `\n` (newline). +Some characters need escaping: `\\`, plus the usual non-printing characters such as `\t` (tab) and `\n` (newline). ```kotlin -val s = "Escape apostrophe \' and backslash \\." -// Escape apostrophe ' and backslash \. +val s = "Escape backslash \\." +// Escape backslash \. ``` -Raw strings use 3 double-quotes, and can contain arbitrary text (no need for escaping). -Multiline strings are also supported, including flexible handling of indents. +Multi-line strings are surrounded by 3 double-quotes, and can contain arbitrary text (no need for escaping). ```kotlin val multi = """I'm a - |multi-line - |string with special characters \ \t """ + multi-line + string with special characters \ \t """ +//I'm a +// multi-line +// string with special characters \ \t +``` + +Use [trimIndent][trimIndent-doc] to remove the common indenting from the lines. +This is useful for formatting the string: + +```kotlin +val multi = """ + I'm a + multi-line + string""".trimIndent() -multi.trimMargin() // delimiter defaults to | but can be specified //I'm a -//multi-line -//string with special characters \ \t +// multi-line +//string +``` + +Alternatively, [trimMargin][trimMargin-doc] lets you specify a delimiter. +Each line in the `String` then begins after the delimiter. +The delimiter defaults to `|`, but you can specify a different delimiter as a parameter. +For example: + +```kotlin +val multi = """ + |I'm a + | multi-line + |string""".trimMargin() + +//I'm a +// multi-line +//string + +val multi2 = """ + start>I'm a + start> multi-line + start>string""".trimMargin("start>") + +//I'm a +// multi-line +//string ``` Strings can be concatenated with `+`, but this is best limited to short and simple cases. @@ -56,12 +92,12 @@ Mostly, these are [`extensions functions`][ref-extensions] rather than members o ~~~~exercism/note Kotlin's rather complex [documentation][ref-string-functions] pages hide extension functions in the default view. -Be sure to click `Members and Extensions` to expand this section. +Be sure to click `Members & Extensions` to expand this section. [ref-string-functions]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-string/ ~~~~ -The following example shows just a small selection of what is available: +The following examples show just a small selection of what is available: ```kotlin val str = "Hello World!" @@ -70,15 +106,19 @@ str.length // => 12 (a property, not a function) str.elementAt(6) // => W str.elementAtOrNull(20) // => null (index out of range) str.substring(6, 11) // => "World" +str.substringAfter(" ") // => "World!" + +str.lowercase() // => "hello world!" +str.uppercase() // => "HELLO WORLD!" -str.lowercase() // => "hello world!" -str.uppercase() // => "HELLO WORLD!" +str.startsWith("Hel") // => true +str.endsWith("xyz") // => false +str.indexOf("0") // => 4 -str.startsWith("Hel") // => true -str.endsWith("xyz") // => false +str.toCharArray() // => [H, e, l, l, o, , W, o, r, l, d, !] +"42".toInt() + 1 // => 43 (parsing; see also toFloat) -str.toCharArray() // => [H, e, l, l, o, , W, o, r, l, d, !] -"42".toInt() + 1 // => 43 (parsing; see also toFloat) +"Howdy! ".trim() // => "Howdy" ``` @@ -88,3 +128,5 @@ str.toCharArray() // => [H, e, l, l, o, , W, o, r, l, d, !] [ref-stringbuilder]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/-string-builder/ [ref-extensions]: https://kotlinlang.org/docs/extensions.html#extensions.md [ref-string-functions]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-string/ +[trimIndent-doc]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/trim-indent.html +[trimMargin-doc]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/trim-margin.html diff --git a/config.json b/config.json index 0f44a742..53a0c9b5 100644 --- a/config.json +++ b/config.json @@ -55,6 +55,18 @@ "basics" ], "status": "wip" + }, + { + "slug": "log-levels", + "name": "log-levels", + "uuid": "ef54c5e6-7d31-42d1-a300-e405169dbd7f", + "concepts": [ + "strings" + ], + "prerequisites": [ + "basics" + ], + "status": "wip" } ], "practice": [ diff --git a/exercises/concept/log-levels/.docs/hints.md b/exercises/concept/log-levels/.docs/hints.md new file mode 100644 index 00000000..c6b26b8e --- /dev/null +++ b/exercises/concept/log-levels/.docs/hints.md @@ -0,0 +1,28 @@ +# Hints + +## General + +- Kotlin provides many [functions][ref-strings] for working with Strings. Be sure to check out the `Members & Extensions` tab! + +## 1. Get message from a log line + +- There is a [function][ref-string-substringAfter] to extract the part of a `String` after a given delimiter. +- Removing whitespace from a `String` is explored in [Remove All Whitespaces from a String in Kotlin][tutorial-trim-white-space]. + +## 2. Get log level from a log line + +- There is also a [function][ref-string-substringBefore] to extract part of a `String` _before_ a given delimiter. +- There is a [way][ref-string-lowercase] to change a `String` to lowercase. + +## 3. Reformat a log line + +- [String templates][docs-string-template] can be done with a [multiline string][docs-string-multiline]. + +[docs-string-multiline]: https://kotlinlang.org/docs/strings.html#multiline-strings +[docs-string-template]: https://kotlinlang.org/docs/strings.html#string-templates +[ref-strings]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-string/ +[ref-string-indexOf]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-string/#-537588047%2FFunctions%2F-1430298843 +[ref-string-lowercase]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-string/#-648004414%2FFunctions%2F-956074838 +[ref-string-substringAfter]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-string/#1564391517%2FFunctions%2F-1430298843 +[tutorial-search-text-in-string]: https://javarevisited.blogspot.com/2016/10/how-to-check-if-string-contains-another-substring-in-java-indexof-example.html +[tutorial-trim-white-space]: https://www.baeldung.com/kotlin/string-remove-whitespace diff --git a/exercises/concept/log-levels/.docs/instructions.md b/exercises/concept/log-levels/.docs/instructions.md new file mode 100644 index 00000000..f320564d --- /dev/null +++ b/exercises/concept/log-levels/.docs/instructions.md @@ -0,0 +1,29 @@ +# Instructions + +In this exercise you'll be processing log-liners. + +Each log line is a string formatted as follows: "[]: *". + +## 1. Get the message from a log line + +Implement the `LogLevels.message()` function to return the message from a log line, with the leading and trailing whitespaces removed. + +## 2. Get the log level from a log line + +Implement the `LogLevels.logLevel()` function to return the log level from a log line in lower case. + +## 3. Reformat a log line + +Implement the `LogLevels.reformat()` method that takes a log line and a location string and reformats into a message containing two lines. +The first line is formatted as `@:`, where: + +* `` is the log level in lower case (as from 2. Get the log level from a log line). +* `` is the location given as the second parameter. + +The second line contains exactly two spaces, followed by the log message (as from 1. Get the message from a log line): + +```kotlin +reformat("[TRACE]: Start of function", 2, 8) +// => "trace@208: + Start of function" +``` \ No newline at end of file diff --git a/exercises/concept/log-levels/.docs/introduction.md b/exercises/concept/log-levels/.docs/introduction.md new file mode 100644 index 00000000..c2c4dfcd --- /dev/null +++ b/exercises/concept/log-levels/.docs/introduction.md @@ -0,0 +1,132 @@ +# Introduction + +A [`string`][ref-string] in Kotlin is an immutable sequence of Unicode characters. + +[`Immutable`][wiki-immutable] means that any operation on a string must return a new string: the original string can never change. + +[`Unicode`][wiki-unicode] means that most of the world's writing systems can be represented, but (in contrast to older languages such as C) there is no 1:1 mapping between characters and bytes. + +A string is usually surrounded by double-quotes `" "`. + +Some characters need escaping: `\'`, `\\`, plus the usual non-printing characters such as `\t` (tab) and `\n` (newline). + +```kotlin +val s = "Escape apostrophe \' and backslash \\." +// Escape apostrophe ' and backslash \. +``` + +Multi-line strings are surrounded by 3 double-quotes, and can contain arbitrary text (no need for escaping). + +```kotlin +val multi = """I'm a + multi-line + string with special characters \ \t """ +//I'm a +// multi-line +// string with special characters \ \t +``` + +Use [trimIndent][trimIndent-doc] to remove the common indenting from the lines. +This is useful for formatting the string: + +```kotlin +val multi = """ + I'm a + multi-line + string""".trimIndent() + +//I'm a +// multi-line +//string +``` + +Alternatively, [trimMargin][trimMargin-doc] lets you specify a delimiter. +Each line in the `String` then begins after the delimiter. +The delimiter defaults to `|`, but you can specify a different delimiter as a parameter. +For example: + +```kotlin +val multi = """ + |I'm a + | multi-line + |string""".trimMargin() + +//I'm a +// multi-line +//string + +val multi2 = """ + start>I'm a + start> multi-line + start>string""".trimMargin("start>") + +//I'm a +// multi-line +//string +``` + +Strings can be concatenated with `+`, but this is best limited to short and simple cases. +There are other and often better options. + +## String templates + +This refers to what some other languages call "interpolation". + +If a string contains a dollar sign `$`, followed by an identifier, or contains braces (`{expression}`) surrounding an expression, those are substituted by respectively the value or the result of the expression. + +```kotlin +val x = 42 +val st = "x is $x, x squared is {x * x}" +// x is 42, x squared is 1764 +``` + +The braces `{ }` are needed around expressions when parsing would otherwise be ambiguous. + +In general, use of string templates is a more efficient and idiomatic way to combine strings than using `+`. + +## String functions + +Kotlin provides _many_ [`functions`][ref-string-functions] to manipulate strings. + +Mostly, these are [`extensions functions`][ref-extensions] rather than members of the `String` class, though this has little effect on how we use them. + +~~~~exercism/note +Kotlin's rather complex [documentation][ref-string-functions] pages hide extension functions in the default view. +Be sure to click `Members & Extensions` to expand this section. + +[ref-string-functions]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-string/ +~~~~ + +The following examples show just a small selection of what is available: + +```kotlin +val str = "Hello World!" + +str.length // => 12 (a property, not a function) +str.elementAt(6) // => W +str.elementAtOrNull(20) // => null (index out of range) +str.substring(6, 11) // => "World" +str.substringAfter(" ") // => "World!" + +str.lowercase() // => "hello world!" +str.uppercase() // => "HELLO WORLD!" + +str.startsWith("Hel") // => true +str.endsWith("xyz") // => false +str.indexOf("0") // => 4 + +str.toCharArray() // => [H, e, l, l, o, , W, o, r, l, d, !] +"42".toInt() + 1 // => 43 (parsing; see also toFloat) + +"Howdy! ".trim() // => "Howdy" +``` + + +[ref-string]: https://kotlinlang.org/docs/strings.html +[wiki-immutable]: https://en.wikipedia.org/wiki/Immutable_object +[wiki-unicode]: https://en.wikipedia.org/wiki/Unicode +[ref-stringbuilder]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/-string-builder/ +[ref-extensions]: https://kotlinlang.org/docs/extensions.html#extensions.md +[ref-string-functions]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-string/ +[trimIndent-doc]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/trim-indent.html +[trimMargin-doc]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/trim-margin.html diff --git a/exercises/concept/log-levels/.meta/config.json b/exercises/concept/log-levels/.meta/config.json new file mode 100644 index 00000000..355bcab9 --- /dev/null +++ b/exercises/concept/log-levels/.meta/config.json @@ -0,0 +1,17 @@ +{ + "authors": [ + "kahgoh" + ], + "files": { + "solution": [ + "src/main/kotlin/LogLevels.kt" + ], + "test": [ + "src/test/kotlin/LogLevelsTest.kt" + ], + "exemplar": [ + ".meta/src/reference/kotlin/LogLevels.kt" + ] + }, + "blurb": "Learn about strings by processing logs." +} diff --git a/exercises/concept/log-levels/.meta/src/reference/kotlin/LogLevels.kt b/exercises/concept/log-levels/.meta/src/reference/kotlin/LogLevels.kt new file mode 100644 index 00000000..2eef5d66 --- /dev/null +++ b/exercises/concept/log-levels/.meta/src/reference/kotlin/LogLevels.kt @@ -0,0 +1,14 @@ +fun message(logLine : String) : String { + return logLine.substringAfter(":").trim() +} + +fun logLevel(logLine : String) : String { + return logLine.substringBefore(":").removeSurrounding("[", "]").lowercase() +} + +fun reformat(logLine : String, location : String) : String { + return """ + |${logLevel(logLine)}@$location: + | ${message(logLine)} + """.trimMargin() +} \ No newline at end of file diff --git a/exercises/concept/log-levels/build.gradle.kts b/exercises/concept/log-levels/build.gradle.kts new file mode 100644 index 00000000..b1d5054b --- /dev/null +++ b/exercises/concept/log-levels/build.gradle.kts @@ -0,0 +1,23 @@ +import org.gradle.api.tasks.testing.logging.TestExceptionFormat + +plugins { + kotlin("jvm") +} + +repositories { + mavenCentral() +} + +dependencies { + implementation(kotlin("stdlib-jdk8")) + + testImplementation("junit:junit:4.13.2") + testImplementation(kotlin("test-junit")) +} + +tasks.withType { + testLogging { + exceptionFormat = TestExceptionFormat.FULL + events("passed", "failed", "skipped") + } +} diff --git a/exercises/concept/log-levels/gradle/wrapper/gradle-wrapper.jar b/exercises/concept/log-levels/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..7f93135c Binary files /dev/null and b/exercises/concept/log-levels/gradle/wrapper/gradle-wrapper.jar differ diff --git a/exercises/concept/log-levels/gradle/wrapper/gradle-wrapper.properties b/exercises/concept/log-levels/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..3fa8f862 --- /dev/null +++ b/exercises/concept/log-levels/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/exercises/concept/log-levels/gradlew b/exercises/concept/log-levels/gradlew new file mode 100755 index 00000000..1aa94a42 --- /dev/null +++ b/exercises/concept/log-levels/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/exercises/concept/log-levels/gradlew.bat b/exercises/concept/log-levels/gradlew.bat new file mode 100755 index 00000000..93e3f59f --- /dev/null +++ b/exercises/concept/log-levels/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/exercises/concept/log-levels/settings.gradle.kts b/exercises/concept/log-levels/settings.gradle.kts new file mode 100644 index 00000000..054e2f7e --- /dev/null +++ b/exercises/concept/log-levels/settings.gradle.kts @@ -0,0 +1,13 @@ +pluginManagement { + repositories { + mavenCentral() + gradlePluginPortal() + } + resolutionStrategy { + eachPlugin { + when (requested.id.id) { + "org.jetbrains.kotlin.jvm" -> useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.0") + } + } + } +} diff --git a/exercises/concept/log-levels/src/main/kotlin/LogLevels.kt b/exercises/concept/log-levels/src/main/kotlin/LogLevels.kt new file mode 100644 index 00000000..93c867be --- /dev/null +++ b/exercises/concept/log-levels/src/main/kotlin/LogLevels.kt @@ -0,0 +1,11 @@ +fun message(logLine : String) : String { + TODO("Please implement the message() function") +} + +fun logLevel(logLine : String) : String { + TODO("Please implement the logLevel() function") +} + +fun reformat(logLine : String, location : String) : String { + TODO("Please implement the reformat() method") +} \ No newline at end of file diff --git a/exercises/concept/log-levels/src/test/kotlin/LogLevelsTest.kt b/exercises/concept/log-levels/src/test/kotlin/LogLevelsTest.kt new file mode 100644 index 00000000..c5707d8f --- /dev/null +++ b/exercises/concept/log-levels/src/test/kotlin/LogLevelsTest.kt @@ -0,0 +1,92 @@ +import kotlin.test.Test +import kotlin.test.assertEquals + +class LogLevelsTest { + @Test + fun `error message`() { + assertEquals("Stack overflow", message("[ERROR]: Stack overflow")) + } + + @Test + fun `warning message`() { + assertEquals("Disk almost full", message("[WARNING]: Disk almost full")) + } + + @Test + fun `info message`() { + assertEquals("File info", message("[INFO]: File info")) + } + + @Test + fun `warning message with leading and trailing whitespace`() { + val logLine = """[WARNING]: Timezone not set + """ + assertEquals("Timezone not set", message(logLine)) + } + + @Test + fun `error log level`() { + assertEquals("error", logLevel("[ERROR]: Stack overflow")) + } + + @Test + fun `warning log level`() { + assertEquals("warning", logLevel("[WARNING]: Disk almost full")) + } + + @Test + fun `info log level`() { + assertEquals("info", logLevel("[INFO]: File info")) + } + + @Test + fun `warning log level with leading and trailing whitespace`() { + val logLine = """[WARNING]: Timezone not set + """ + assertEquals("warning", logLevel(logLine)) + } + + @Test + fun `reformat error log line`() { + val expected = """ + |error@code: + | Segmentation fault + """.trimMargin() + assertEquals(expected, reformat("[ERROR]: Segmentation fault", "code")) + } + + @Test + fun `reformat warn log line`() { + val expected = """ + |warn@CPU: + | High temperature + """.trimMargin() + assertEquals(expected, reformat("[WARN]: High temperature", "CPU")) + } + + @Test + fun `reformat info log line`() { + val expected = """ + |info@disk: + | Disk defragmented + """.trimMargin() + assertEquals(expected, reformat("[INFO]: Disk defragmented", "disk")) + } + + @Test + fun `reformat a log line with multiple whitespace`() { + val expected = """ + |notice@shell: + | Entered bad input too many times! + | + | This incident will be reported! + """.trimMargin() + val logLine = """ + |[NOTICE]: Entered bad input too many times! + | + | This incident will be reported! + + """.trimMargin() + assertEquals(expected, reformat(logLine, "shell")) + } +} \ No newline at end of file diff --git a/exercises/settings.gradle.kts b/exercises/settings.gradle.kts index bc770812..65e3dbc3 100644 --- a/exercises/settings.gradle.kts +++ b/exercises/settings.gradle.kts @@ -1,4 +1,8 @@ include( + "concept:annalyns-infiltration", + "concept:cars-assemble", + "concept:log-levels", + "concept:lucians-luscious-lasagna", "practice:accumulate", "practice:acronym", "practice:all-your-base",