diff --git a/POLICIES.md b/POLICIES.md index 18c66747..7fad6cb4 100644 --- a/POLICIES.md +++ b/POLICIES.md @@ -32,6 +32,12 @@ Markdown documents in this repository should use "ventilated prose": one sentenc This keeps diffs focused on the sentences that actually changed, which makes code review easier. Additionally, ensure that both headers and lists have a blank line before and after them. +### Markdown style + +Markdown documents in this repository should use "ventilated prose": one sentence per line. +This keeps diffs focused on the sentences that actually changed, which makes code review easier. +Additionally, ensure that both headers and lists have a blank line before and after them. + ### Prefer standard bash over POSIX compliance When submitting or updating exercises, POSIX compliance is not required. diff --git a/concepts/arithmetic/about.md b/concepts/arithmetic/about.md index 9aee746b..6872fdcd 100644 --- a/concepts/arithmetic/about.md +++ b/concepts/arithmetic/about.md @@ -9,31 +9,12 @@ Additionally, Bash only performs arithmetic in certain places (known as arithmet ## Arithmetic Expansion -Arithmetic expansion looks like [command substitution][cmd-sub], but with double parentheses. - -```bash -$(( expression )) -``` - -This syntax expands to the result of evaluating the expression. -It is commonly used to capture the result in a variable: - -```bash -x=$(( 3 + 4 )) -``` - -~~~~exercism/note -The amount of whitespace inside the parentheses is up to you. -It is a matter of style and readability. +As we saw in the [Variables][variables] lesson, math can be performed in an arithmetic expansion. ```bash x=$(( 3 + 4 )) -y=$((5+6)) ``` -Your friendly author likes to add spaces so that the arithmetic expression is more visible within the parentheses. -~~~~ - ## Arithmetic Conditional The arithmetic conditional is performed within double parentheses _without_ the leading `$`: @@ -183,4 +164,4 @@ area=$(( $1 * $2 )) [let]: https://www.gnu.org/software/bash/manual/bash.html#index-let [awk]: https://www.gnu.org/software/gawk/manual/html_node/index.html [bc]: https://www.gnu.org/software/bc/manual/html_mono/bc.html -[cmd-sub]: https://exercism.org/tracks/bash/concepts/variables#h-command-substitution +[variables]: https://exercism.org/tracks/bash/concepts/variables#h-arithmetic-expansion diff --git a/concepts/arithmetic/introduction.md b/concepts/arithmetic/introduction.md index 54a63018..58de104a 100644 --- a/concepts/arithmetic/introduction.md +++ b/concepts/arithmetic/introduction.md @@ -9,31 +9,12 @@ Additionally, Bash only performs arithmetic in certain places (known as arithmet ## Arithmetic Expansion -Arithmetic expansion looks like [command substitution][cmd-sub], but with double parentheses. - -```bash -$(( expression )) -``` - -This syntax expands to the result of evaluating the expression. -It is commonly used to capture the result in a variable: - -```bash -x=$(( 3 + 4 )) -``` - -~~~~exercism/note -The amount of whitespace inside the parentheses is up to you. -It is a matter of style and readability. +As we saw in the [Variables][variables] lesson, math can be performed in an arithmetic expansion. ```bash x=$(( 3 + 4 )) -y=$((5+6)) ``` -Your friendly author likes to add spaces so that the arithmetic expression is more visible within the parentheses. -~~~~ - ## Arithmetic Conditional The arithmetic conditional is performed within double parentheses _without_ the leading `$`: @@ -183,4 +164,4 @@ area=$(( $1 * $2 )) [let]: https://www.gnu.org/software/bash/manual/bash.html#index-let [awk]: https://www.gnu.org/software/gawk/manual/html_node/index.html [bc]: https://www.gnu.org/software/bc/manual/html_mono/bc.html -[cmd-sub]: https://exercism.org/tracks/bash/concepts/variables#h-command-substitution +[variables]: https://exercism.org/tracks/bash/concepts/variables#h-arithmetic-expansion diff --git a/concepts/variables/about.md b/concepts/variables/about.md index ed1d8962..79796784 100644 --- a/concepts/variables/about.md +++ b/concepts/variables/about.md @@ -124,6 +124,58 @@ echo "$uppercase" # => HELLO WORLD! ``` +## Arithmetic Expansion + +Arithmetic expansion looks like command substitution, but with double parentheses. + +```bash +$(( expression )) +``` + +This syntax expands to the result of evaluating the expression. +It is commonly used to capture the result in a variable: + +```bash +x=$(( 3 + 4 )) +``` + +Inside the parentheses, you can use a variable's name without the `$`: + +```bash +height=10 +width=20 +area=$(( height * width )) +``` + +Bash can do arithmetic but _only with integers_. + +~~~~exercism/note +The amount of whitespace inside the parentheses is up to you. +It is a matter of style and readability. + +```bash +x=$(( 3 + 4 )) +y=$((5+6)) +``` + +Your friendly author likes to add spaces so that the arithmetic expression is more visible within the parentheses. +~~~~ + +## Magic Numbers + +A "magic number" is a number written directly in your code with no explanation of what it means. +Store it in a variable with a descriptive name instead. +Your code will be easier to read, and you'll only need to change the value in one place. + +```bash +# what does 12 mean? +eggs=$(( cartons * 12 )) + +# much clearer +eggs_per_carton=12 +eggs=$(( cartons * eggs_per_carton )) +``` + ## More on Parameter Expansion Bash has many builtin facilities to manipulate variables and strings so that you don't need to call out to external commands. diff --git a/concepts/variables/introduction.md b/concepts/variables/introduction.md index 13534020..cbee49f8 100644 --- a/concepts/variables/introduction.md +++ b/concepts/variables/introduction.md @@ -124,6 +124,58 @@ echo "$uppercase" # => HELLO WORLD! ``` +## Arithmetic Expansion + +Arithmetic expansion looks like command substitution, but with double parentheses. + +```bash +$(( expression )) +``` + +This syntax expands to the result of evaluating the expression. +It is commonly used to capture the result in a variable: + +```bash +x=$(( 3 + 4 )) +``` + +Inside the parentheses, you can use a variable's name without the `$`: + +```bash +height=10 +width=20 +area=$(( height * width )) +``` + +Bash can do arithmetic but _only with integers_. + +~~~~exercism/note +The amount of whitespace inside the parentheses is up to you. +It is a matter of style and readability. + +```bash +x=$(( 3 + 4 )) +y=$((5+6)) +``` + +Your friendly author likes to add spaces so that the arithmetic expression is more visible within the parentheses. +~~~~ + +## Magic Numbers + +A "magic number" is a number written directly in your code with no explanation of what it means. +Store it in a variable with a descriptive name instead. +Your code will be easier to read, and you'll only need to change the value in one place. + +```bash +# what does 12 mean? +eggs=$(( cartons * 12 )) + +# much clearer +eggs_per_carton=12 +eggs=$(( cartons * eggs_per_carton )) +``` + ## More on Parameter Expansion Bash has many builtin facilities to manipulate variables and strings so that you don't need to call out to external commands. diff --git a/config.json b/config.json index 84af5f21..3cee2be2 100644 --- a/config.json +++ b/config.json @@ -43,6 +43,18 @@ ], "prerequisites": [], "status": "wip" + }, + { + "slug": "lasagna", + "name": "Lucian's Luscious Lasagna", + "uuid": "0a182883-a62b-49b5-aa02-accc682b6d9a", + "concepts": [ + "variables" + ], + "prerequisites": [ + "commands-and-arguments" + ], + "status": "wip" } ], "practice": [ @@ -674,10 +686,10 @@ "practices": [], "prerequisites": [], "difficulty": 4, + "status": "wip", "topics": [ "dates" - ], - "status": "wip" + ] }, { "slug": "binary-search", diff --git a/exercises/concept/lasagna/.docs/hints.md b/exercises/concept/lasagna/.docs/hints.md new file mode 100644 index 00000000..5a17a15d --- /dev/null +++ b/exercises/concept/lasagna/.docs/hints.md @@ -0,0 +1,37 @@ +# Hints + +## General + +- There must be _no spaces_ around the `=` in a variable assignment. +- Use `$name` or `${name}` to get the value of a variable. +- Quote parameter expansions: `"$name"`. +- Use `${name:-default}` to provide a default value when a variable is empty or unset. +- Use good variable names: lowercase, and descriptive. + +## 1. Define the expected oven time in minutes + +- Assign the value to a variable, then use [`echo`][echo] with the variable inside a double-quoted string. +- Braces can separate the variable name from surrounding text: `"${name}text"`. + +## 2. Calculate the remaining oven time in minutes + +- The first command-line argument is the [positional parameter][positional] `$1`. +- Use a default value to handle a missing argument: `${1:-0}`. +- [Arithmetic expansion][arithmetic] expands to the result of a calculation: `result=$(( 7 - 2 ))`. +- Inside `$(( ))`, you can use variable names without the `$`. + +## 3. Calculate the preparation time in minutes + +- The second command-line argument is `$2`. +- Remember to provide a default for a missing argument. +- Use `*` to multiply: `$(( a * b ))`. +- Store the minutes per layer in a variable, so the number 2 has a name. + +## 4. Calculate the total working time in minutes + +- `$(( a + b ))` adds two numbers. +- You can reuse the variables you have already assigned. + +[echo]: https://www.gnu.org/software/bash/manual/bash.html#Bash-Builtins +[positional]: https://www.gnu.org/software/bash/manual/bash.html#Positional-Parameters +[arithmetic]: https://www.gnu.org/software/bash/manual/bash.html#Arithmetic-Expansion diff --git a/exercises/concept/lasagna/.docs/instructions.md b/exercises/concept/lasagna/.docs/instructions.md new file mode 100644 index 00000000..fb6a9e0b --- /dev/null +++ b/exercises/concept/lasagna/.docs/instructions.md @@ -0,0 +1,73 @@ +# Instructions + +In this exercise you're going to write some code to help you cook a brilliant lasagna from your favorite cookbook. + +You have four tasks, all related to the time spent cooking the lasagna. +Each task adds to the same script, so preserve the output from the previous tasks. +Do not print anything other than the requested output. + +The script accepts two optional command-line arguments: + +1. the number of minutes the lasagna has _actually_ been in the oven. + If it is missing, use `0`. +2. the number of layers in the lasagna. + If it is missing, use `1`. + +Run the script with: + +```bash +bash lasagna.sh 18 3 +``` + +Use arithmetic expansion to do the math. +For example, `$(( 7 - 2 ))` expands to `5`. + +## 1. Define the expected oven time in minutes + +According to the cookbook, the expected oven time is 40 minutes. +Store this value in a variable, and print it: + +```text +Expected minutes in oven: 40 +``` + +## 2. Calculate the remaining oven time in minutes + +Store the actual minutes in the oven (the first argument) in a variable. +Then calculate how many minutes the lasagna still has to remain in the oven, based on the expected oven time from the previous task. +Print it on the next line: + +```bash +bash lasagna.sh 18 3 +``` + +```text +Expected minutes in oven: 40 +Remaining minutes in oven: 22 +``` + +## 3. Calculate the preparation time in minutes + +The preparation time is how long it takes to get the lasagna ready before it is put in the oven. +It takes 2 minutes to prepare each layer. +Store the number of layers (the second argument) in a variable, and store the minutes per layer in another variable instead of using a "magic number". +Print the preparation time on the next line: + +```text +Expected minutes in oven: 40 +Remaining minutes in oven: 22 +Preparation time in minutes: 6 +``` + +## 4. Calculate the total working time in minutes + +Calculate how many minutes in total you've worked on cooking the lasagna. +This is the sum of the preparation time and the time the lasagna has spent in the oven so far. +Print it on the last line: + +```text +Expected minutes in oven: 40 +Remaining minutes in oven: 22 +Preparation time in minutes: 6 +Total time in minutes: 24 +``` diff --git a/exercises/concept/lasagna/.docs/introduction.md b/exercises/concept/lasagna/.docs/introduction.md new file mode 100644 index 00000000..784ef8a2 --- /dev/null +++ b/exercises/concept/lasagna/.docs/introduction.md @@ -0,0 +1,217 @@ +# Introduction + +## Variables + +### Variables + +_Variables_ are a place to hold data. +Bash has two kinds of data: strings and arrays. +We'll talk about arrays later. + +You assign a variable like this +```bash +name="value" +``` + +~~~~exercism/note +**Important** -- there must be _no spaces_ around the equal sign! + +When there are spaces, like in this example, + +```bash +x = 10 +``` + +bash is going to call the **command** `x` with the **two arguments** `=` and `10`! +~~~~ + +Variables can also be called _parameters_. +The two terms will be used interchangably in this document. + +Some important parameters used by or set by bash include: + +* `PATH` -- a colon-separated list of directories used to find external commands. +* `IFS` -- the "internal field separator". + We'll see how it's used below. +* `PWD` -- your current working directory. + It will be the same value as the output of the `pwd` command. +* `RANDOM` -- a pseudo-random integer between 0 and 32767. +* `BASH_VERSION` -- the version string of the running instance of bash. + +### Variable Names + +A variable name consists of _uppercase letters, lowercase letters, numbers and underscore_. +It cannot start with a number. + +~~~~exercism/caution +It is best practice to **avoid using ALLCAPS variable names**. +The shell uses this convention for its parameters, and you don't want to accidentally overwrite shell parameters that have special meaning. +For example: [1][1], [2][2], [3][3] + +[1]: https://stackoverflow.com/q/27555060/7552 +[2]: https://stackoverflow.com/q/28310594/7552 +[3]: https://unix.stackexchange.com/q/114596/4667 +~~~~ + +### Parameter Expansion + +You get the value of a parameter with the `$varname` syntax. + +```bash +x=10 +echo "The value of x is $x" +``` + +To prevent the variable name from being confused with surrounding text, you can enclose the variable name in braces. +For example to print the string `10x10` + +```bash +echo "${x}x$x" +# or +echo "${x}x${x}" +``` + +Some [style guides][google-style-guide] recommend using braces in most cases for readability and/or consistency. + +### Positional Parameters + +As we discussed in the [Commands and Arguments][cmds-args] lesson, commands can take arguments. +Bash scripts are no exception. +The arguments to the current instance of bash are called _positional parameters_. +They can be retrieved with these special parameters: + +* `$1` -- the first positional parameter +* `$2` ... `$9` -- subsequent parameters +* `${10}` ... -- double digits require braces. +* `$0` -- the name of the current script. + +Arguments to a shell function are also positional parameters, handled just like this. +We'll see more about functions in a later lesson. + +#### Special Positional Parameters + +There are some _special parameters_ that help you work with the positional parameters. + +* `$#` expands to the _number_ of positional parameters. +* `"$@"` expands to the list of all of the positional parameters, each as a separate word. +* `"$*"` expands to a single string of all the positional parameters joined together by a character. + * The join character is _the first character_ of the `$IFS` variable, which is a space by default. + +The `"$@"` is the safest way to pass positional parameters to another command while keeping them safely quoted. +It is also what you will use to loop over the positional parameters: + +```bash +for arg in "$@"; do + do_something_with "$arg" +done +``` + +In practice, `"$@"` is used more often than `"$*"`. + +### Command Substitution + +A very frequent operation you will do in bash scripts is to capture the output of a command and store it in a variable. +To do this, you will use _command substitution_. + +```bash +var=$(command) +``` + +For example, to upper-case a string, you can do this: + +```bash +text="Hello world!" +uppercase=$(echo "$text" | tr '[:lower:]' '[:upper:]') +echo "$uppercase" +# => HELLO WORLD! +``` + +### Arithmetic Expansion + +Arithmetic expansion looks like command substitution, but with double parentheses. + +```bash +$(( expression )) +``` + +This syntax expands to the result of evaluating the expression. +It is commonly used to capture the result in a variable: + +```bash +x=$(( 3 + 4 )) +``` + +Inside the parentheses, you can use a variable's name without the `$`: + +```bash +height=10 +width=20 +area=$(( height * width )) +``` + +Bash can do arithmetic but _only with integers_. + +~~~~exercism/note +The amount of whitespace inside the parentheses is up to you. +It is a matter of style and readability. + +```bash +x=$(( 3 + 4 )) +y=$((5+6)) +``` + +Your friendly author likes to add spaces so that the arithmetic expression is more visible within the parentheses. +~~~~ + +### Magic Numbers + +A "magic number" is a number written directly in your code with no explanation of what it means. +Store it in a variable with a descriptive name instead. +Your code will be easier to read, and you'll only need to change the value in one place. + +```bash +# what does 12 mean? +eggs=$(( cartons * 12 )) + +# much clearer +eggs_per_carton=12 +eggs=$(( cartons * eggs_per_carton )) +``` + +### More on Parameter Expansion + +Bash has many builtin facilities to manipulate variables and strings so that you don't need to call out to external commands. + +* Uppercasing text. + In the previous section I showed how to use `tr` to upper case some text. + To do it in bash: + + ```bash + echo "${text^^}" + ``` + + Similarly, `${text,,}` lowercases the value. + +* Provide a default value if the variable is empty. + + ```bash + default="nothing here" + result="" + echo "${result:-$default}" + # => nothing here + ``` + +* Search and replace. + + ```bash + text="Hello world!" + echo "${text//[aeiou]/X}" + # => HXllX wXrld!" + ``` + +There are many other interesting parameter expansions: extract a substring, get the string length, _assign_ a default value, remove text from the start or end of the value, and more. +Read about them [in the manual][param-exp]. + +[google-style-guide]: https://google.github.io/styleguide/shellguide.html +[cmds-args]: https://exercism.org/tracks/bash/concepts/commands-and-arguments +[param-exp]: https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion diff --git a/exercises/concept/lasagna/.docs/introduction.md.tpl b/exercises/concept/lasagna/.docs/introduction.md.tpl new file mode 100644 index 00000000..fd7059b7 --- /dev/null +++ b/exercises/concept/lasagna/.docs/introduction.md.tpl @@ -0,0 +1,3 @@ +# Introduction + +%{concept:variables} diff --git a/exercises/concept/lasagna/.meta/config.json b/exercises/concept/lasagna/.meta/config.json new file mode 100644 index 00000000..c867315b --- /dev/null +++ b/exercises/concept/lasagna/.meta/config.json @@ -0,0 +1,20 @@ +{ + "authors": [ + "glennj" + ], + "files": { + "solution": [ + "lasagna.sh" + ], + "test": [ + "lasagna.bats" + ], + "exemplar": [ + ".meta/exemplar.sh" + ], + "invalidator": [ + "bats-extra.bash" + ] + }, + "blurb": "Learn about variables by keeping track of the time spent cooking a lasagna." +} diff --git a/exercises/concept/lasagna/.meta/design.md b/exercises/concept/lasagna/.meta/design.md new file mode 100644 index 00000000..e78fd7bc --- /dev/null +++ b/exercises/concept/lasagna/.meta/design.md @@ -0,0 +1,34 @@ +# Design + +## Goal + +The goal of this exercise is to introduce variables in bash scripts. + +## Learning objectives + +- Assign a value to a variable, with no spaces around the equal sign. +- Expand a variable's value with `$name` and `${name}`. +- Use descriptive, non-ALLCAPS variable names. +- Read command-line arguments through positional parameters. +- Provide a default value with `${name:-default}`. +- Capture the output of a command in a variable with command substitution. +- Do integer arithmetic with arithmetic expansion. + +## Out of scope + +- Other arithmetic contexts, such as the `(( ))` conditional. +- Arrays. +- Functions and `local` variables. +- Exported variables and the environment. +- Parameter expansions beyond default values. +- Conditionals and loops. + +## Concepts + +The Concepts this exercise unlocks are: + +- `variables` + +## Prerequisites + +- `commands-and-arguments` diff --git a/exercises/concept/lasagna/.meta/exemplar.sh b/exercises/concept/lasagna/.meta/exemplar.sh new file mode 100644 index 00000000..ac4958ad --- /dev/null +++ b/exercises/concept/lasagna/.meta/exemplar.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +expected_minutes_in_oven=40 +minutes_per_layer=2 + +actual_minutes_in_oven=${1:-0} +number_of_layers=${2:-1} + +# Task 1 +echo "Expected minutes in oven: ${expected_minutes_in_oven}" + +# Task 2 +remaining_minutes_in_oven=$(( expected_minutes_in_oven - actual_minutes_in_oven )) +echo "Remaining minutes in oven: ${remaining_minutes_in_oven}" + +# Task 3 +preparation_time=$(( number_of_layers * minutes_per_layer )) +echo "Preparation time in minutes: ${preparation_time}" + +# Task 4 +total_time=$(( preparation_time + actual_minutes_in_oven )) +echo "Total time in minutes: ${total_time}" diff --git a/exercises/concept/lasagna/bats-extra.bash b/exercises/concept/lasagna/bats-extra.bash new file mode 100644 index 00000000..7cef63ea --- /dev/null +++ b/exercises/concept/lasagna/bats-extra.bash @@ -0,0 +1,642 @@ +# This is the source code for bats-support and bats-assert, concatenated +# * https://github.com/bats-core/bats-support +# * https://github.com/bats-core/bats-assert +# +# Comments have been removed to save space. See the git repos for full source code. + +############################################################ +# +# bats-support - Supporting library for Bats test helpers +# +# Written in 2016 by Zoltan Tombol +# +# To the extent possible under law, the author(s) have dedicated all +# copyright and related and neighboring rights to this software to the +# public domain worldwide. This software is distributed without any +# warranty. +# +# You should have received a copy of the CC0 Public Domain Dedication +# along with this software. If not, see +# . +# + +# shellcheck disable=SC2120 # (warning): fail references arguments, but none are ever passed. +fail() { + # shellcheck disable=2015 # (info): Note that A && B || C is not if-then-else. C may run when A is true. + (( $# == 0 )) && batslib_err || batslib_err "$@" + return 1 +} + +batslib_is_caller() { + local -i is_mode_direct=1 + + # Handle options. + while (( $# > 0 )); do + case "$1" in + -i|--indirect) is_mode_direct=0; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + # Arguments. + local -r func="$1" + + # Check call stack. + if (( is_mode_direct )); then + [[ $func == "${FUNCNAME[2]}" ]] && return 0 + else + local -i depth + for (( depth=2; depth<${#FUNCNAME[@]}; ++depth )); do + [[ $func == "${FUNCNAME[$depth]}" ]] && return 0 + done + fi + + return 1 +} + +batslib_err() { + { if (( $# > 0 )); then + echo "$@" + else + cat - + fi + } >&2 +} + +batslib_count_lines() { + local -i n_lines=0 + local line + while IFS='' read -r line || [[ -n $line ]]; do + (( ++n_lines )) + done < <(printf '%s' "$1") + echo "$n_lines" +} + +batslib_is_single_line() { + for string in "$@"; do + (( $(batslib_count_lines "$string") > 1 )) && return 1 + done + return 0 +} + +batslib_get_max_single_line_key_width() { + local -i max_len=-1 + while (( $# != 0 )); do + local -i key_len="${#1}" + batslib_is_single_line "$2" && (( key_len > max_len )) && max_len="$key_len" + shift 2 + done + echo "$max_len" +} + +batslib_print_kv_single() { + local -ir col_width="$1"; shift + while (( $# != 0 )); do + printf '%-*s : %s\n' "$col_width" "$1" "$2" + shift 2 + done +} + +batslib_print_kv_multi() { + while (( $# != 0 )); do + printf '%s (%d lines):\n' "$1" "$( batslib_count_lines "$2" )" + printf '%s\n' "$2" + shift 2 + done +} + +batslib_print_kv_single_or_multi() { + local -ir width="$1"; shift + local -a pairs=( "$@" ) + + local -a values=() + local -i i + for (( i=1; i < ${#pairs[@]}; i+=2 )); do + values+=( "${pairs[$i]}" ) + done + + if batslib_is_single_line "${values[@]}"; then + batslib_print_kv_single "$width" "${pairs[@]}" + else + local -i i + for (( i=1; i < ${#pairs[@]}; i+=2 )); do + pairs[i]="$( batslib_prefix < <(printf '%s' "${pairs[$i]}") )" + done + batslib_print_kv_multi "${pairs[@]}" + fi +} + +batslib_prefix() { + local -r prefix="${1:- }" + local line + while IFS='' read -r line || [[ -n $line ]]; do + printf '%s%s\n' "$prefix" "$line" + done +} + +batslib_mark() { + local -r symbol="$1"; shift + # Sort line numbers. + # shellcheck disable=SC2046 # (warning): Quote this to prevent word splitting. + set -- $( sort -nu <<< "$( printf '%d\n' "$@" )" ) + + local line + local -i idx=0 + while IFS='' read -r line || [[ -n $line ]]; do + if (( ${1:--1} == idx )); then + printf '%s\n' "${symbol}${line:${#symbol}}" + shift + else + printf '%s\n' "$line" + fi + (( ++idx )) + done +} + +batslib_decorate() { + echo + echo "-- $1 --" + cat - + echo '--' + echo +} + +############################################################ + +assert() { + if ! "$@"; then + batslib_print_kv_single 10 'expression' "$*" \ + | batslib_decorate 'assertion failed' \ + | fail + fi +} + +assert_equal() { + if [[ $1 != "$2" ]]; then + batslib_print_kv_single_or_multi 8 \ + 'expected' "$2" \ + 'actual' "$1" \ + | batslib_decorate 'values do not equal' \ + | fail + fi +} + +assert_failure() { + : "${output?}" + : "${status?}" + + (( $# > 0 )) && local -r expected="$1" + if (( status == 0 )); then + batslib_print_kv_single_or_multi 6 'output' "$output" \ + | batslib_decorate 'command succeeded, but it was expected to fail' \ + | fail + elif (( $# > 0 )) && (( status != expected )); then + { local -ir width=8 + batslib_print_kv_single "$width" \ + 'expected' "$expected" \ + 'actual' "$status" + batslib_print_kv_single_or_multi "$width" \ + 'output' "$output" + } \ + | batslib_decorate 'command failed as expected, but status differs' \ + | fail + fi +} + +assert_line() { + local -i is_match_line=0 + local -i is_mode_partial=0 + local -i is_mode_regexp=0 + : "${lines?}" + + # Handle options. + while (( $# > 0 )); do + case "$1" in + -n|--index) + if (( $# < 2 )) || ! [[ $2 =~ ^([0-9]|[1-9][0-9]+)$ ]]; then + echo "\`--index' requires an integer argument: \`$2'" \ + | batslib_decorate 'ERROR: assert_line' \ + | fail + return $? + fi + is_match_line=1 + local -ri idx="$2" + shift 2 + ;; + -p|--partial) is_mode_partial=1; shift ;; + -e|--regexp) is_mode_regexp=1; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + if (( is_mode_partial )) && (( is_mode_regexp )); then + echo "\`--partial' and \`--regexp' are mutually exclusive" \ + | batslib_decorate 'ERROR: assert_line' \ + | fail + return $? + fi + + # Arguments. + local -r expected="$1" + + if (( is_mode_regexp == 1 )) && [[ '' =~ $expected ]] || (( $? == 2 )); then + echo "Invalid extended regular expression: \`$expected'" \ + | batslib_decorate 'ERROR: assert_line' \ + | fail + return $? + fi + + # Matching. + if (( is_match_line )); then + # Specific line. + if (( is_mode_regexp )); then + if ! [[ ${lines[$idx]} =~ $expected ]]; then + batslib_print_kv_single 6 \ + 'index' "$idx" \ + 'regexp' "$expected" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'regular expression does not match line' \ + | fail + fi + elif (( is_mode_partial )); then + if [[ ${lines[$idx]} != *"$expected"* ]]; then + batslib_print_kv_single 9 \ + 'index' "$idx" \ + 'substring' "$expected" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'line does not contain substring' \ + | fail + fi + else + if [[ ${lines[$idx]} != "$expected" ]]; then + batslib_print_kv_single 8 \ + 'index' "$idx" \ + 'expected' "$expected" \ + 'actual' "${lines[$idx]}" \ + | batslib_decorate 'line differs' \ + | fail + fi + fi + else + # Contained in output. + if (( is_mode_regexp )); then + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + [[ ${lines[$idx]} =~ $expected ]] && return 0 + done + { local -ar single=( 'regexp' "$expected" ) + local -ar may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + batslib_print_kv_single_or_multi "$width" "${may_be_multi[@]}" + } \ + | batslib_decorate 'no output line matches regular expression' \ + | fail + elif (( is_mode_partial )); then + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + [[ ${lines[$idx]} == *"$expected"* ]] && return 0 + done + { local -ar single=( 'substring' "$expected" ) + local -ar may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + batslib_print_kv_single_or_multi "$width" "${may_be_multi[@]}" + } \ + | batslib_decorate 'no output line contains substring' \ + | fail + else + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + [[ ${lines[$idx]} == "$expected" ]] && return 0 + done + { local -ar single=( 'line' "$expected" ) + local -ar may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + batslib_print_kv_single_or_multi "$width" "${may_be_multi[@]}" + } \ + | batslib_decorate 'output does not contain line' \ + | fail + fi + fi +} + +assert_output() { + local -i is_mode_partial=0 + local -i is_mode_regexp=0 + local -i is_mode_nonempty=0 + local -i use_stdin=0 + : "${output?}" + + # Handle options. + if (( $# == 0 )); then + is_mode_nonempty=1 + fi + + while (( $# > 0 )); do + case "$1" in + -p|--partial) is_mode_partial=1; shift ;; + -e|--regexp) is_mode_regexp=1; shift ;; + -|--stdin) use_stdin=1; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + if (( is_mode_partial )) && (( is_mode_regexp )); then + echo "\`--partial' and \`--regexp' are mutually exclusive" \ + | batslib_decorate 'ERROR: assert_output' \ + | fail + return $? + fi + + # Arguments. + local expected + if (( use_stdin )); then + expected="$(cat -)" + else + expected="${1-}" + fi + + # Matching. + if (( is_mode_nonempty )); then + if [ -z "$output" ]; then + echo 'expected non-empty output, but output was empty' \ + | batslib_decorate 'no output' \ + | fail + fi + elif (( is_mode_regexp )); then + # shellcheck disable=SC2319 # (warning) `$?` in a conditional expression: https://github.com/koalaman/shellcheck/wiki/SC2319 + if [[ '' =~ $expected ]] || (( $? == 2 )); then + # the regex matches an empty string or it is syntactically incorrect. + echo "Invalid extended regular expression: \`$expected'" \ + | batslib_decorate 'ERROR: assert_output' \ + | fail + elif ! [[ $output =~ $expected ]]; then + batslib_print_kv_single_or_multi 6 \ + 'regexp' "$expected" \ + 'output' "$output" \ + | batslib_decorate 'regular expression does not match output' \ + | fail + fi + elif (( is_mode_partial )); then + if [[ $output != *"$expected"* ]]; then + batslib_print_kv_single_or_multi 9 \ + 'substring' "$expected" \ + 'output' "$output" \ + | batslib_decorate 'output does not contain substring' \ + | fail + fi + else + if [[ $output != "$expected" ]]; then + batslib_print_kv_single_or_multi 8 \ + 'expected' "$expected" \ + 'actual' "$output" \ + | batslib_decorate 'output differs' \ + | fail + fi + fi +} + +assert_success() { + : "${output?}" + : "${status?}" + + if (( status != 0 )); then + { local -ir width=6 + batslib_print_kv_single "$width" 'status' "$status" + batslib_print_kv_single_or_multi "$width" 'output' "$output" + } \ + | batslib_decorate 'command failed' \ + | fail + fi +} + +refute() { + if "$@"; then + batslib_print_kv_single 10 'expression' "$*" \ + | batslib_decorate 'assertion succeeded, but it was expected to fail' \ + | fail + fi +} + +refute_line() { + local -i is_match_line=0 + local -i is_mode_partial=0 + local -i is_mode_regexp=0 + : "${lines?}" + + # Handle options. + while (( $# > 0 )); do + case "$1" in + -n|--index) + if (( $# < 2 )) || ! [[ $2 =~ ^([0-9]|[1-9][0-9]+)$ ]]; then + echo "\`--index' requires an integer argument: \`$2'" \ + | batslib_decorate 'ERROR: refute_line' \ + | fail + return $? + fi + is_match_line=1 + local -ri idx="$2" + shift 2 + ;; + -p|--partial) is_mode_partial=1; shift ;; + -e|--regexp) is_mode_regexp=1; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + if (( is_mode_partial )) && (( is_mode_regexp )); then + echo "\`--partial' and \`--regexp' are mutually exclusive" \ + | batslib_decorate 'ERROR: refute_line' \ + | fail + return $? + fi + + # Arguments. + local -r unexpected="$1" + + if (( is_mode_regexp == 1 )) && [[ '' =~ $unexpected ]] || (( $? == 2 )); then + echo "Invalid extended regular expression: \`$unexpected'" \ + | batslib_decorate 'ERROR: refute_line' \ + | fail + return $? + fi + + # Matching. + if (( is_match_line )); then + # Specific line. + if (( is_mode_regexp )); then + if [[ ${lines[$idx]} =~ $unexpected ]]; then + batslib_print_kv_single 6 \ + 'index' "$idx" \ + 'regexp' "$unexpected" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'regular expression should not match line' \ + | fail + fi + elif (( is_mode_partial )); then + if [[ ${lines[$idx]} == *"$unexpected"* ]]; then + batslib_print_kv_single 9 \ + 'index' "$idx" \ + 'substring' "$unexpected" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'line should not contain substring' \ + | fail + fi + else + if [[ ${lines[$idx]} == "$unexpected" ]]; then + batslib_print_kv_single 5 \ + 'index' "$idx" \ + 'line' "${lines[$idx]}" \ + | batslib_decorate 'line should differ' \ + | fail + fi + fi + else + # Line contained in output. + if (( is_mode_regexp )); then + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + if [[ ${lines[$idx]} =~ $unexpected ]]; then + { local -ar single=( 'regexp' "$unexpected" 'index' "$idx" ) + local -a may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + if batslib_is_single_line "${may_be_multi[1]}"; then + batslib_print_kv_single "$width" "${may_be_multi[@]}" + else + may_be_multi[1]="$( printf '%s' "${may_be_multi[1]}" | batslib_prefix | batslib_mark '>' "$idx" )" + batslib_print_kv_multi "${may_be_multi[@]}" + fi + } \ + | batslib_decorate 'no line should match the regular expression' \ + | fail + return $? + fi + done + elif (( is_mode_partial )); then + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + if [[ ${lines[$idx]} == *"$unexpected"* ]]; then + { local -ar single=( 'substring' "$unexpected" 'index' "$idx" ) + local -a may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + if batslib_is_single_line "${may_be_multi[1]}"; then + batslib_print_kv_single "$width" "${may_be_multi[@]}" + else + may_be_multi[1]="$( printf '%s' "${may_be_multi[1]}" | batslib_prefix | batslib_mark '>' "$idx" )" + batslib_print_kv_multi "${may_be_multi[@]}" + fi + } \ + | batslib_decorate 'no line should contain substring' \ + | fail + return $? + fi + done + else + local -i idx + for (( idx = 0; idx < ${#lines[@]}; ++idx )); do + if [[ ${lines[$idx]} == "$unexpected" ]]; then + { local -ar single=( 'line' "$unexpected" 'index' "$idx" ) + local -a may_be_multi=( 'output' "$output" ) + local -ir width="$( batslib_get_max_single_line_key_width "${single[@]}" "${may_be_multi[@]}" )" + batslib_print_kv_single "$width" "${single[@]}" + if batslib_is_single_line "${may_be_multi[1]}"; then + batslib_print_kv_single "$width" "${may_be_multi[@]}" + else + may_be_multi[1]="$( printf '%s' "${may_be_multi[1]}" | batslib_prefix | batslib_mark '>' "$idx" )" + batslib_print_kv_multi "${may_be_multi[@]}" + fi + } \ + | batslib_decorate 'line should not be in output' \ + | fail + return $? + fi + done + fi + fi +} + +refute_output() { + local -i is_mode_partial=0 + local -i is_mode_regexp=0 + local -i is_mode_empty=0 + local -i use_stdin=0 + : "${output?}" + + # Handle options. + if (( $# == 0 )); then + is_mode_empty=1 + fi + + while (( $# > 0 )); do + case "$1" in + -p|--partial) is_mode_partial=1; shift ;; + -e|--regexp) is_mode_regexp=1; shift ;; + -|--stdin) use_stdin=1; shift ;; + --) shift; break ;; + *) break ;; + esac + done + + if (( is_mode_partial )) && (( is_mode_regexp )); then + echo "\`--partial' and \`--regexp' are mutually exclusive" \ + | batslib_decorate 'ERROR: refute_output' \ + | fail + return $? + fi + + # Arguments. + local unexpected + if (( use_stdin )); then + unexpected="$(cat -)" + else + unexpected="${1-}" + fi + + if (( is_mode_regexp == 1 )) && [[ '' =~ $unexpected ]] || (( $? == 2 )); then + echo "Invalid extended regular expression: \`$unexpected'" \ + | batslib_decorate 'ERROR: refute_output' \ + | fail + return $? + fi + + # Matching. + if (( is_mode_empty )); then + if [ -n "$output" ]; then + batslib_print_kv_single_or_multi 6 \ + 'output' "$output" \ + | batslib_decorate 'output non-empty, but expected no output' \ + | fail + fi + elif (( is_mode_regexp )); then + if [[ $output =~ $unexpected ]]; then + batslib_print_kv_single_or_multi 6 \ + 'regexp' "$unexpected" \ + 'output' "$output" \ + | batslib_decorate 'regular expression should not match output' \ + | fail + fi + elif (( is_mode_partial )); then + if [[ $output == *"$unexpected"* ]]; then + batslib_print_kv_single_or_multi 9 \ + 'substring' "$unexpected" \ + 'output' "$output" \ + | batslib_decorate 'output should not contain substring' \ + | fail + fi + else + if [[ $output == "$unexpected" ]]; then + batslib_print_kv_single_or_multi 6 \ + 'output' "$output" \ + | batslib_decorate 'output equals, but it was expected to differ' \ + | fail + fi + fi +} diff --git a/exercises/concept/lasagna/lasagna.bats b/exercises/concept/lasagna/lasagna.bats new file mode 100644 index 00000000..5dbe2474 --- /dev/null +++ b/exercises/concept/lasagna/lasagna.bats @@ -0,0 +1,87 @@ +#!/usr/bin/env bats +load bats-extra + +# bats test_tags=task:1 +test_expected_minutes_in_oven() { # @test + run bash lasagna.sh 18 3 + + assert_success + assert_line --index 0 "Expected minutes in oven: 40" +} + +# bats test_tags=task:2 +test_remaining_minutes_in_oven() { # @test + run bash lasagna.sh 18 3 + + assert_success + assert_line --index 1 "Remaining minutes in oven: 22" +} + +# bats test_tags=task:2 +test_remaining_minutes_in_oven_other_value() { # @test + run bash lasagna.sh 30 3 + + assert_success + assert_line --index 1 "Remaining minutes in oven: 10" +} + +# bats test_tags=task:2 +test_remaining_minutes_defaults_to_zero_minutes_in_oven() { # @test + run bash lasagna.sh + + assert_success + assert_line --index 1 "Remaining minutes in oven: 40" +} + +# bats test_tags=task:3 +test_preparation_time() { # @test + run bash lasagna.sh 18 3 + + assert_success + assert_line --index 2 "Preparation time in minutes: 6" +} + +# bats test_tags=task:3 +test_preparation_time_other_value() { # @test + run bash lasagna.sh 18 5 + + assert_success + assert_line --index 2 "Preparation time in minutes: 10" +} + +# bats test_tags=task:3 +test_preparation_time_defaults_to_one_layer() { # @test + run bash lasagna.sh 18 + + assert_success + assert_line --index 2 "Preparation time in minutes: 2" +} + +# bats test_tags=task:4 +test_total_time() { # @test + run bash lasagna.sh 18 3 + + assert_success + assert_line --index 3 "Total time in minutes: 24" +} + +# bats test_tags=task:4 +test_total_time_with_defaults() { # @test + run bash lasagna.sh + + assert_success + assert_line --index 3 "Total time in minutes: 2" +} + +# bats test_tags=task:4 +test_exact_output() { # @test + run bash lasagna.sh 10 2 + + assert_success + assert_output - <<'END' +Expected minutes in oven: 40 +Remaining minutes in oven: 30 +Preparation time in minutes: 4 +Total time in minutes: 14 +END +} diff --git a/exercises/concept/lasagna/lasagna.sh b/exercises/concept/lasagna/lasagna.sh new file mode 100644 index 00000000..4f1bef45 --- /dev/null +++ b/exercises/concept/lasagna/lasagna.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash + +# This script helps you keep track of the time spent making a lasagna. +# +# Arguments (both optional): +# $1 the actual number of minutes the lasagna has been in the oven. +# Default: 0 +# $2 the number of layers in the lasagna. +# Default: 1 +# +# Add your code below each task comment. +# Each task builds on the previous tasks, so keep the earlier output unchanged. +# Use variables to give names to the values you work with. + +# Task 1: define a variable for the expected oven time (in minutes) +# and print it. + +# Task 2: store the actual oven time from the first argument in a variable +# (using a default value if it is missing), +# then print the remaining oven time. + +# Task 3: store the number of layers from the second argument in a variable +# (using a default value if it is missing), +# then print the preparation time. + +# Task 4: print the total working time. diff --git a/exercises/concept/road-map.md b/exercises/concept/road-map.md new file mode 100644 index 00000000..5f5f74c5 --- /dev/null +++ b/exercises/concept/road-map.md @@ -0,0 +1,37 @@ +# Road map to implement bash concept exercises + +Ref: [Syllabus][syllabus] + +| Concept | Exercise | branch or PR | Prereq | +| ------- | -------- | ------------ | ------ | +| [commands-and-arguments][commands-and-arguments] | shopping | [980][980] | - | +| [variables][variables] | [lasagna][lasagna] | [985][985] | cmds-args | +| [quoting][quoting] | messy-downloads (OC) | [branch][concept-expercise-quoting] | variables | +| [conditionals][conditionals] | [vehicle-purchase][vehicle-purchase] | | quoting | +| [arithmetic][arithmetic] | [vehicle-purchase][vehicle-purchase] | | quoting | +| [looping][looping] | | | conditionals | +| [arrays][arrays] | | | quoting | +| [more-arrays][more-arrays] | | | arrays | +| [pipelines][pipelines] | | | quoting | +| [functions][functions] | | | pipelines | +| [redirection][redirection] | | | pipelines | +| [heredocs][heredocs] | | | redirection | + +[syllabus]: https://exercism.org/docs/tracks/bash/syllabus +[commands-and-arguments]: https://github.com/exercism/bash/tree/main/concepts/commands-and-arguments +[980]: https://github.com/exercism/bash/pull/980 +[variables]: https://exercism.org/docs/building/tracks/stories/basics-lasagna +[lasagna]: https://github.com/glennj/exercism-bash/tree/concept-exercise-lasagna +[985]: https://github.com/exercism/bash/pull/985 +[quoting]: https://github.com/exercism/bash/tree/main/concepts/quoting +[concept-expercise-quoting]: https://github.com/glennj/exercism-bash/tree/concept-expercise-quoting +[conditionals]: https://github.com/exercism/bash/tree/main/concepts/conditionals +[vehicle-purchase]: https://exercism.org/docs/building/tracks/stories/conditionals-vehicle-purchase +[arithmetic]: https://github.com/exercism/bash/tree/main/concepts/arithmetic +[looping]: https://github.com/exercism/bash/tree/main/concepts/looping +[arrays]: https://github.com/exercism/bash/tree/main/concepts/arrays +[more-arrays]: https://github.com/exercism/bash/tree/main/concepts/more-arrays +[pipelines]: https://github.com/exercism/bash/tree/main/concepts/pipelines +[functions]: https://github.com/exercism/bash/tree/main/concepts/functions +[redirection]: https://github.com/exercism/bash/tree/main/concepts/redirection +[heredocs]: https://github.com/exercism/bash/tree/main/concepts/heredocs