diff --git a/concepts/README.md b/concepts/README.md index 587f7445..d0c575db 100644 --- a/concepts/README.md +++ b/concepts/README.md @@ -9,7 +9,7 @@ erDiagram "Commands and Arguments" ||--|| Variables : "" Variables ||--|| "The Importance of Quoting" : "" "The Importance of Quoting" ||--|| Conditionals : "" -"The Importance of Quoting" ||--|| Arrays : "" +Looping ||--|| Arrays : "" "The Importance of Quoting" ||--|| "Pipelines and Command Lists" : "" Conditionals ||--|| Arithmetic : "" Conditionals ||--|| Looping : "" diff --git a/config.json b/config.json index 2d24bd67..a6f935e0 100644 --- a/config.json +++ b/config.json @@ -79,6 +79,18 @@ "quoting" ], "status": "wip" + }, + { + "slug": "bird-watcher", + "name": "Bird Watcher", + "uuid": "2493723d-786c-4361-a92f-f30837caea95", + "concepts": [ + "looping" + ], + "prerequisites": [ + "conditionals" + ], + "status": "wip" } ], "practice": [ diff --git a/docs/SYLLABUS.md b/docs/SYLLABUS.md index 3474ec1c..81fe10d9 100644 --- a/docs/SYLLABUS.md +++ b/docs/SYLLABUS.md @@ -11,8 +11,8 @@ While the learning exercises are still incomplete, most of the concept documenta * [Conditionals](https://exercism.org/tracks/bash/concepts/conditionals) * [Arithmetic](https://exercism.org/tracks/bash/concepts/arithmetic) * [Looping](https://exercism.org/tracks/bash/concepts/looping) - * [Arrays](https://exercism.org/tracks/bash/concepts/arrays) - * [More About Arrays](https://exercism.org/tracks/bash/concepts/more-arrays) + * [Arrays](https://exercism.org/tracks/bash/concepts/arrays) + * [More About Arrays](https://exercism.org/tracks/bash/concepts/more-arrays) * [Pipelines and Command Lists](https://exercism.org/tracks/bash/concepts/pipelines) * [Functions](https://exercism.org/tracks/bash/concepts/functions) * [Redirection](https://exercism.org/tracks/bash/concepts/redirection) diff --git a/exercises/concept/bird-watcher/.docs/hints.md b/exercises/concept/bird-watcher/.docs/hints.md new file mode 100644 index 00000000..69f621e4 --- /dev/null +++ b/exercises/concept/bird-watcher/.docs/hints.md @@ -0,0 +1,42 @@ +# Hints + +## General + +- Read about [looping constructs][looping-constructs] in the bash manual, or the track's looping concept page. +- Add to a number with [arithmetic expansion][arithmetic]: `total=$(( total + 1 ))`. +- Set your totals and counters to their starting values before a loop begins. +- Quote your parameter expansions: `"$@"`. + +## 1. Count all the birds + +- Use a [`for` loop][looping-constructs] to visit each of the `"$@"` arguments. +- Add each count to a total, then print the total after the loop. + +## 2. Find the first quiet day + +- Keep track of the day number while you loop over the counts. +- Compare numbers for equality with `==` inside `(( ... ))`. +- Use [`break`][builtins] to leave the loop early. +- Before the loop, store the answer to print if there is no quiet day. + +## 3. Draw a bar of a chart + +- An [arithmetic `for` loop][looping-constructs] can repeat commands a given number of times. +- Build up the stars in a variable: `bar="${bar}*"`. +- Print the variable after the loop, inside double quotes. + +## 4. Predict when you will reach your goal + +- You don't know in advance how many days you need, so use a [`while` loop][looping-constructs]. +- The condition can be an arithmetic comparison: `(( ... ))`. +- Each time around the loop, update the total, the number of birds, and the number of days. + +## 5. Summarize your log file + +- Read the file line by line with `while IFS= read -r line`, and redirect the file into the loop after `done`. +- Add `|| [[ -n $line ]]` to the condition to handle a last line without a newline. +- Use [`continue`][builtins] to skip a rainy day. + +[looping-constructs]: https://www.gnu.org/software/bash/manual/bash.html#Looping-Constructs +[builtins]: https://www.gnu.org/software/bash/manual/bash.html#Bourne-Shell-Builtins +[arithmetic]: https://www.gnu.org/software/bash/manual/bash.html#Arithmetic-Expansion diff --git a/exercises/concept/bird-watcher/.docs/instructions.md b/exercises/concept/bird-watcher/.docs/instructions.md new file mode 100644 index 00000000..3ba7a35c --- /dev/null +++ b/exercises/concept/bird-watcher/.docs/instructions.md @@ -0,0 +1,91 @@ +# Instructions + +You are an avid bird watcher. +Every day you count the birds that visit your garden, and now you want a script to help you work with those counts. + +You have five tasks, and they all belong to the same script. +The first argument names the task to perform, and the remaining arguments are the data for that task. +The script you are given already runs the right part of the code for each task, so you only need to fill in each part. +Do not print anything other than the requested output. + +## 1. Count all the birds + +The arguments are the number of birds you counted on each day. +There can be any number of days, including none at all. + +Print the total number of birds. + +```text +$ bash bird_watcher.sh total 2 5 0 7 4 +18 +``` + +## 2. Find the first quiet day + +The arguments are the daily counts. +A quiet day is a day when you saw no birds at all. + +Print the number of the first quiet day, where the first day is day 1. +If there was no quiet day, print `none`. +Stop looking as soon as you find a quiet day. + +```text +$ bash bird_watcher.sh quiet-day 2 5 0 7 0 +3 +``` + +## 3. Draw a bar of a chart + +The argument is the number of birds you counted on one day. + +Print one line containing one `*` for each bird. +If there were no birds, print an empty line. + +```text +$ bash bird_watcher.sh chart 3 +*** +``` + +## 4. Predict when you will reach your goal + +Spring is coming, and you expect to see one more bird each day than the day before. +The first argument is the total number of birds you want to see. +The second argument is the number of birds you expect to see on the first day. + +Print the number of days needed for the total to reach or pass the goal. + +For example, with 2 birds on the first day, you expect to see 2, 3, 4 and then 5 birds. +The totals after each day are 2, 5, 9 and 14, so a goal of 10 birds takes 4 days. + +```text +$ bash bird_watcher.sh goal 10 2 +4 +``` + +## 5. Summarize your log file + +You have also been keeping a log file, with one line for each day. +A line contains either the number of birds you saw, or the word `rain` for a day when you stayed indoors. +The last line of the file might not end with a newline. + +The argument is the name of the file. +Print the total number of birds, and the number of days that you were watching. +Rainy days are not days that you were watching. + +If the file `birds.txt` contains these lines: + +```text +2 +5 +rain +0 +7 +3 +``` + +then the output is: + +```text +$ bash bird_watcher.sh log birds.txt +17 birds in 5 days +``` diff --git a/exercises/concept/bird-watcher/.docs/introduction.md b/exercises/concept/bird-watcher/.docs/introduction.md new file mode 100644 index 00000000..6bb92b6b --- /dev/null +++ b/exercises/concept/bird-watcher/.docs/introduction.md @@ -0,0 +1,183 @@ +# Introduction + +## Looping + +Bash has two forms of looping: + +* Repeat some commands _for each item in a list of items_, +* Repeat some commands _while some condition is true (or false)_. + +### For Loops + +To iterate over a list of items, we use the `for` loop. + +```bash +for varname in words; do COMMANDS; done +``` + +`words` is expanded using word splitting and filename expansion (that we learned about in the [Quoting concept][quoting]). +Each word is assigned to the `varname` in turn, and the COMMANDS are executed. + +Here are some examples that show when the for loop can be useful + +* Perform some commands on a group of files. + + ```bash + # source all the bash library files in the current directory + for file in ./*.bash; do + source "$file" + done + ``` + +* Perform some command on each of the parameters to a script or function. + + ```bash + for arg in "$@"; do + echo "argument: ${arg}" + done + ``` + +* Perform some command for each whitespace-separated word in the output of a command. + + ```bash + for i in $(seq 10); do + echo "${i} squared is $((i * i))" + done + ``` + + We'll see some warnings about this style later on. + +#### Arithmetic For Loop + +Bash does have an arithmetic loop. +This will look somewhat familiar to other programming languages. + +```bash +for ((INITIALIZATION; CONDITION; INCREMENT)); do COMMANDS; done +``` + +The double-parentheses in bash represents an arithmetic context (we'll see more about bash arithmetic in a later concept). +The above example using `seq` can be written like this + +```bash +for ((i = 1; i <= 10; i++)); do + echo "${i} squared is $((i * i))" +done +``` + +#### When Not To Use For + +[Don't read lines with `for`][bashfaq1]. + +This is an anti-pattern you'll often see: iterating over the output of `cat`. + +```bash +for line in $(cat some.file); do + do_something_with "$line" +done +``` + +This is wrong on 2 counts. + +1. The command substitution is unquoted, so it is subject to word splitting. + Word splitting, by default, splits on _whitespace_ not just newlines. + This for loop is iterating over the **words** in the file, not the lines. +2. The command substitution is unquoted, so it is subject to filename expansion. + Every word in the file will be matched as a glob pattern. + +As we learned in the [Quoting concept][quoting], word splitting can be controlled with the `IFS` variable, and filename expansion can be turned off. +But this tends to be a fragile solution. +`for` is the wrong method to iterate over the lines of a file. +The idiomatic way to read a file is with a `while` loop. + +### While Loops + +Use `while` to repeat a sequence of commands _while_ some condition is true. + +```bash +while CONDITION_COMMANDS; do COMMANDS; done +``` + +As with `if` (as we learned in the [Conditionals concept][conditionals], there is no special syntax for CONDITION_COMMANDS. +The exit status of the command list will determine "true" or "false". + +### Controlling Loops + +The `break` command jumps out of the loop. +Control resumes with the command following the loop's `done` terminator. + +The `continue` command jumps to the next iteration of the loop. + +### Reading the Lines of a File + +As mentioned, a while loop is the idiomatic way to read a file. + +```bash +while IFS= read -r line; do + do_something_with "$line" +done < some.file +``` + +* The content of the file is provided as input to the loop with the `<` redirection. +* The `read` command returns "true" if it can read a full line from its input. + When the input is consumed, or if the last line ends without a trailing newline, then read returns "false". + * The _truly_ idiomatic way to read the lines of a file, even if the last line does not end with a newline, is + + ```bash + while IFS= read -r line || [[ -n "$line" ]]; do ... + ``` + +* The `-r` option tells `read` to not substitute backslash sequences: a backslash is just a plain character. +* `IFS=` assigns the empty string to IFS only for the duration of the read command. + This temporarily turns off word splitting so that any leading or trailing whitespace in the incoming line of text is preserved. + +### Until + +The `until` construct repeats a sequence of commands while some condition is **false**. +The loop repeats _until_ the condition becomes true. + +```bash +until CONDITION_COMMANDS; do COMMANDS; done +``` + +It is rare to use `until`. +It is more common to use a "while not" loop. + +```bash +while ! CONDITION_COMANDS; do ... +``` + +### Infinite Loops + +Sometimes you want to loop forever. +Here are two ways to do it. + +1. a while loop with a condition that always has a success exit status + + ```bash + while true; do ... + ``` + +2. an arithmetic for loop with empty expressions + + ```bash + for ((;;)); do ... + ``` + +### Do-While + +There is no explicit do-while construct, but you can achieve the same effect: + +```bash +while true; do + COMMANDS + + if END_CONDITION; then + break + fi +done +``` + +[bashfaq1]: https://mywiki.wooledge.org/DontReadLinesWithFor +[quoting]: https://exercism.org/tracks/bash/concepts/quoting +[conditionals]: https://exercism.org/tracks/bash/concepts/conditionals diff --git a/exercises/concept/bird-watcher/.docs/introduction.md.tpl b/exercises/concept/bird-watcher/.docs/introduction.md.tpl new file mode 100644 index 00000000..5aa08381 --- /dev/null +++ b/exercises/concept/bird-watcher/.docs/introduction.md.tpl @@ -0,0 +1,3 @@ +# Introduction + +%{concept:looping} diff --git a/exercises/concept/bird-watcher/.meta/config.json b/exercises/concept/bird-watcher/.meta/config.json new file mode 100644 index 00000000..4665b587 --- /dev/null +++ b/exercises/concept/bird-watcher/.meta/config.json @@ -0,0 +1,23 @@ +{ + "authors": [ + "glennj" + ], + "files": { + "solution": [ + "bird_watcher.sh" + ], + "test": [ + "bird_watcher.bats" + ], + "exemplar": [ + ".meta/exemplar.sh" + ], + "invalidator": [ + "bats-extra.bash" + ] + }, + "forked_from": [ + "javascript/bird-watcher" + ], + "blurb": "Learn about looping while counting the birds that visit your garden." +} diff --git a/exercises/concept/bird-watcher/.meta/design.md b/exercises/concept/bird-watcher/.meta/design.md new file mode 100644 index 00000000..bc8d928d --- /dev/null +++ b/exercises/concept/bird-watcher/.meta/design.md @@ -0,0 +1,37 @@ +# Design + +## Goal + +The goal of this exercise is to introduce looping in bash scripts. + +## Learning objectives + +- Use a `for` loop to iterate over the arguments in `"$@"`. +- Use `continue` to skip to the next iteration of a loop. +- Use `break` to leave a loop early. +- Use an arithmetic `for` loop to repeat commands a given number of times. +- Use a `while` loop to repeat commands while a condition is true. +- Read the lines of a file with `while IFS= read -r`. +- Process the last line of a file that does not end with a newline. + +## Out of scope + +- The `until` loop. +- Infinite loops, and the do-while pattern. +- Nested loops. +- Looping over the results of filename expansion or command substitution. +- Arrays. +- Functions. +- The `case` and `shift` commands: the stub provides them to select the task. +- Redirection, other than providing a file as the input of a `while` loop. +- Validating the input. + +## Concepts + +The Concepts this exercise unlocks are: + +- `looping` + +## Prerequisites + +- `conditionals` diff --git a/exercises/concept/bird-watcher/.meta/exemplar.sh b/exercises/concept/bird-watcher/.meta/exemplar.sh new file mode 100644 index 00000000..b4aaa882 --- /dev/null +++ b/exercises/concept/bird-watcher/.meta/exemplar.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash + +task=$1 +shift + +case $task in + total) + total=0 + for count in "$@"; do + total=$(( total + count )) + done + echo "$total" + ;; + + quiet-day) + day=0 + quiet_day="none" + for count in "$@"; do + day=$(( day + 1 )) + if (( count == 0 )); then + quiet_day=$day + break + fi + done + echo "$quiet_day" + ;; + + chart) + count=$1 + bar="" + for (( i = 0; i < count; i++ )); do + bar="${bar}*" + done + echo "$bar" + ;; + + goal) + goal=$1 + birds=$2 + total=0 + days=0 + while (( total < goal )); do + total=$(( total + birds )) + birds=$(( birds + 1 )) + days=$(( days + 1 )) + done + echo "$days" + ;; + + log) + logfile=$1 + total=0 + days=0 + while IFS= read -r line || [[ -n $line ]]; do + if [[ $line == "rain" ]]; then + continue + fi + total=$(( total + line )) + days=$(( days + 1 )) + done < "$logfile" + echo "${total} birds in ${days} days" + ;; +esac diff --git a/exercises/concept/bird-watcher/bats-extra.bash b/exercises/concept/bird-watcher/bats-extra.bash new file mode 100644 index 00000000..7cef63ea --- /dev/null +++ b/exercises/concept/bird-watcher/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/bird-watcher/bird_watcher.bats b/exercises/concept/bird-watcher/bird_watcher.bats new file mode 100644 index 00000000..58b93e40 --- /dev/null +++ b/exercises/concept/bird-watcher/bird_watcher.bats @@ -0,0 +1,193 @@ +#!/usr/bin/env bats +load bats-extra + +# bats test_tags=task:1 +test_total_of_several_days() { # @test + run bash bird_watcher.sh total 2 5 0 7 4 + + assert_success + assert_output '18' +} + +# bats test_tags=task:1 +test_total_of_two_weeks() { # @test + run bash bird_watcher.sh total 2 5 0 7 4 1 3 0 2 5 0 1 3 1 + + assert_success + assert_output '34' +} + +# bats test_tags=task:1 +test_total_of_one_day() { # @test + run bash bird_watcher.sh total 12 + + assert_success + assert_output '12' +} + +# bats test_tags=task:1 +test_total_of_no_days() { # @test + run bash bird_watcher.sh total + + assert_success + assert_output '0' +} + +# bats test_tags=task:2 +test_quiet_day_in_the_middle() { # @test + run bash bird_watcher.sh quiet-day 2 5 0 7 4 + + assert_success + assert_output '3' +} + +# bats test_tags=task:2 +test_only_the_first_quiet_day_is_reported() { # @test + run bash bird_watcher.sh quiet-day 4 0 3 0 0 + + assert_success + assert_output '2' +} + +# bats test_tags=task:2 +test_quiet_first_day() { # @test + run bash bird_watcher.sh quiet-day 0 1 2 + + assert_success + assert_output '1' +} + +# bats test_tags=task:2 +test_no_quiet_day() { # @test + run bash bird_watcher.sh quiet-day 10 20 3 + + assert_success + assert_output 'none' +} + +# bats test_tags=task:3 +test_chart_of_a_few_birds() { # @test + run bash bird_watcher.sh chart 3 + + assert_success + assert_output '***' +} + +# bats test_tags=task:3 +test_chart_of_many_birds() { # @test + run bash bird_watcher.sh chart 12 + + assert_success + assert_output '************' +} + +# bats test_tags=task:3 +test_chart_of_no_birds() { # @test + run bash bird_watcher.sh chart 0 + + assert_success + assert_output '' +} + +# bats test_tags=task:4 +test_goal_passed_on_the_fourth_day() { # @test + run bash bird_watcher.sh goal 10 2 + + assert_success + assert_output '4' +} + +# bats test_tags=task:4 +test_goal_reached_exactly() { # @test + run bash bird_watcher.sh goal 15 1 + + assert_success + assert_output '5' +} + +# bats test_tags=task:4 +test_goal_reached_on_the_first_day() { # @test + run bash bird_watcher.sh goal 3 8 + + assert_success + assert_output '1' +} + +# bats test_tags=task:4 +test_goal_of_zero_birds() { # @test + run bash bird_watcher.sh goal 0 5 + + assert_success + assert_output '0' +} + +# bats test_tags=task:4 +test_goal_with_no_birds_on_the_first_day() { # @test + run bash bird_watcher.sh goal 3 0 + + assert_success + assert_output '3' +} + +# bats test_tags=task:4 +test_large_goal() { # @test + run bash bird_watcher.sh goal 100 1 + + assert_success + assert_output '14' +} + +# bats test_tags=task:5 +test_log_of_counts() { # @test + local log="${BATS_TEST_TMPDIR}/birds.txt" + printf '%s\n' 2 5 0 7 3 > "$log" + + run bash bird_watcher.sh log "$log" + + assert_success + assert_output '17 birds in 5 days' +} + +# bats test_tags=task:5 +test_log_skips_rainy_days() { # @test + local log="${BATS_TEST_TMPDIR}/birds.txt" + printf '%s\n' rain 4 rain rain 6 rain > "$log" + + run bash bird_watcher.sh log "$log" + + assert_success + assert_output '10 birds in 2 days' +} + +# bats test_tags=task:5 +test_log_without_a_final_newline() { # @test + local log="${BATS_TEST_TMPDIR}/birds.txt" + printf '3\nrain\n8' > "$log" + + run bash bird_watcher.sh log "$log" + + assert_success + assert_output '11 birds in 2 days' +} + +# bats test_tags=task:5 +test_log_file_name_with_spaces() { # @test + local log="${BATS_TEST_TMPDIR}/my bird log.txt" + printf '%s\n' 1 2 > "$log" + + run bash bird_watcher.sh log "$log" + + assert_success + assert_output '3 birds in 2 days' +} + +# bats test_tags=task:5 +test_empty_log() { # @test + local log="${BATS_TEST_TMPDIR}/birds.txt" + : > "$log" + + run bash bird_watcher.sh log "$log" + + assert_success + assert_output '0 birds in 0 days' +} diff --git a/exercises/concept/bird-watcher/bird_watcher.sh b/exercises/concept/bird-watcher/bird_watcher.sh new file mode 100644 index 00000000..fd59737f --- /dev/null +++ b/exercises/concept/bird-watcher/bird_watcher.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash + +# This script helps you keep track of the birds that visit your garden. +# +# The first argument names the task to perform. +# The remaining arguments are the data for that task. +# +# The `case` command below runs the code for the requested task. +# The `shift` command removes the first argument, so that "$@" holds the +# arguments that are left, and "$1" is the first of them. +# +# Add your code below each task comment. +# Keep the other lines as they are. + +task=$1 +shift + +case $task in + total) + # Task 1: print the total number of birds. + # "$@" holds the daily counts. + + ;; + + quiet-day) + # Task 2: print the number of the first day without any birds. + # "$@" holds the daily counts. + + ;; + + chart) + # Task 3: print one bar of the chart. + # "$1" is the number of birds. + + ;; + + goal) + # Task 4: print the number of days needed to reach the goal. + # "$1" is the goal, and "$2" is the number of birds on the first day. + + ;; + + log) + # Task 5: print a summary of a log file. + # "$1" is the name of the file. + + ;; +esac diff --git a/exercises/concept/road-map.md b/exercises/concept/road-map.md index 615addfc..38350379 100644 --- a/exercises/concept/road-map.md +++ b/exercises/concept/road-map.md @@ -9,8 +9,8 @@ Ref: [Syllabus][syllabus] | [quoting][quoting] | messy-downloads (OC) | [987][987] | variables | | [conditionals][conditionals] | [vehicle-purchase][vehicle-purchase] | | quoting | | [arithmetic][arithmetic] | | | conditionals | -| [looping][looping] | | | conditionals | -| [arrays][arrays] | | | quoting | +| [looping][looping] | bird-watcher | | conditionals | +| [arrays][arrays] | | | looping | | [more-arrays][more-arrays] | | | arrays | | [pipelines][pipelines] | | | quoting | | [functions][functions] | | | pipelines |