Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions docs/maintenance/crypto-square.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# crypto-square maintenance

This note maps every file of the `crypto-square` practice exercise to its role, and gives
a command that checks the metadata is consistent.

## File-role map

| Path | Role |
|---|---|
| `exercises/practice/crypto-square/crypto_square.cpp` | Learner stub (the `solution` file). Must stay unsolved. |
| `exercises/practice/crypto-square/crypto_square.h` | Learner stub header (the `solution` file). Must stay unsolved. |
| `exercises/practice/crypto-square/crypto_square_test.cpp` | The tests (the `test` file). |
| `exercises/practice/crypto-square/.meta/example.cpp` | Reference implementation (the `example` file). |
| `exercises/practice/crypto-square/.meta/example.h` | Reference header (the `example` file). |
| `exercises/practice/crypto-square/.meta/config.json` | Declares the files above in its `files` object. |
| `exercises/practice/crypto-square/.meta/tests.toml` | Which canonical test cases are enabled. Maintained with `configlet sync`. |
| `exercises/practice/crypto-square/.docs/instructions.md` | The problem description. |
| `exercises/practice/crypto-square/CMakeLists.txt` | Build definition. The test program is named after the exercise folder. |

The `files` object in `config.json` is the source of truth. Its paths are relative to the
exercise folder: `files.solution` lists the stub, `files.test` the tests, `files.example`
the reference, and `files.editor` (if present) extra files offered in the online editor.
Tools that need these files should read that object instead of guessing from file names.

## Generated artifacts

These are produced by running tools and are never edited by hand or committed to the exercise:

- the `build/` directory and the `crypto-square` test program created by CMake
- `work/R20-T058/` evidence files (`tool_versions.txt`, `evidence.json`, `reference_test_output.txt`), which are coursework evidence and stay out of any upstream PR
- `exercises/practice/crypto-square/.meta/tests.toml` is synced by `configlet`, so change it through that tool

## Reproducible validation

Check that every path declared in `config.json` exists inside the exercise and does not escape it:

```bash
python3 tools/course_checks/r20-t058.py
```

Exit code 0 means valid, 1 means invalid. The full course check, which also tests the
checker against broken fixtures and builds and runs the reference tests, is:

```bash
python3 work/R20-T058/check.py
```
66 changes: 66 additions & 0 deletions exercises/practice/pangram/.docs/hints.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Hints

## Passing the sentence: `const` reference

The reference solution's helper takes the sentence like this:

```cpp
bool found_letter(char a, const std::string &s)
```

`const std::string &s` is a reference to const: the function gets a read-only view of the caller's string instead of its own copy. A `char` is tiny, so it is passed by value. A whole sentence can be long, so it is passed by `const` reference.

This matters here because `is_pangram` asks `found_letter` about each of the 26 letters, so the sentence is passed 26 times.

The program below counts copies with a small wrapper type, so you can see them (it does not solve the exercise):

```cpp
#include <iostream>
#include <string>
#include <utility>

// A tiny wrapper that counts how many times it is copied.
struct Sentence {
std::string text;
static int copies;

explicit Sentence(std::string t) : text(std::move(t)) {}
Sentence(const Sentence &other) : text(other.text) { ++copies; }
};

int Sentence::copies = 0;

// Same shape as the reference helper: a char by value, the sentence by const reference.
bool found_letter(char a, const Sentence &s) {
for (char c : s.text) {
if (c == a) {
return true;
}
}
return false;
}

int main() {
Sentence sentence{"The quick brown fox jumps over the lazy dog"};
for (char letter = 'a'; letter <= 'z'; ++letter) {
found_letter(letter, sentence);
}
std::cout << "const reference: " << Sentence::copies << " copies\n";
}
```

Expected output:

```text
const reference: 0 copies
```

Now remove the `const` and the `&`, so the parameter becomes `Sentence s`, and change the output label to `by value: `. Every call now copies the whole sentence:

```text
by value: 26 copies
```

The answers from `found_letter` are identical, but there are 26 copies instead of none. As a rule of thumb, pass cheap types like `char` by value, and pass things you only read but that are expensive to copy, like strings, by `const` reference.

Further reading: [Reference declaration](https://en.cppreference.com/w/cpp/language/reference) on cppreference.
80 changes: 80 additions & 0 deletions tools/course_checks/r20-t058.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""Check that the files declared in an exercise's .meta/config.json really exist.

The paths in the "files" object (solution, test, example, editor, ...) are relative to
the exercise folder. This checker reads that object directly, resolves every path,
rejects paths that leave the exercise folder, and checks that every declared file exists.

Usage:
python3 tools/course_checks/r20-t058.py [EXERCISE_DIR]

EXERCISE_DIR defaults to exercises/practice/crypto-square.
Exit code 0 means valid, 1 means invalid.
"""
import json
import sys
from pathlib import Path, PurePosixPath

REPO = Path(__file__).resolve().parents[2]
DEFAULT_EXERCISE = REPO / "exercises" / "practice" / "crypto-square"
REQUIRED_KEYS = ("solution", "test", "example")


def validate(exercise_dir):
"""Return a list of problems. An empty list means the metadata is valid."""
exercise = Path(exercise_dir).resolve()
config_path = exercise / ".meta" / "config.json"
if not config_path.is_file():
return [f"missing config file: {config_path}"]

try:
config = json.loads(config_path.read_text())
except json.JSONDecodeError as err:
return [f"config.json is not valid JSON: {err}"]

files = config.get("files")
if not isinstance(files, dict):
return ["config.json has no 'files' object"]

problems = []
for key in REQUIRED_KEYS:
if not files.get(key):
problems.append(f"files.{key}: missing or empty")

for key, entries in files.items():
if not isinstance(entries, list):
problems.append(f"files.{key}: must be a list of paths")
continue
for entry in entries:
if not isinstance(entry, str) or not entry:
problems.append(f"files.{key}: '{entry}' is not a valid path")
continue
parts = PurePosixPath(entry)
if parts.is_absolute() or ".." in parts.parts:
problems.append(f"files.{key}: '{entry}' escapes the exercise folder")
continue
resolved = (exercise / entry).resolve()
try:
resolved.relative_to(exercise)
except ValueError:
problems.append(f"files.{key}: '{entry}' escapes the exercise folder")
continue
if not resolved.is_file():
problems.append(f"files.{key}: '{entry}' does not exist")
return problems


def main(argv):
exercise = Path(argv[1]) if len(argv) > 1 else DEFAULT_EXERCISE
problems = validate(exercise)
if problems:
print(f"INVALID: {exercise}")
for problem in problems:
print(f" - {problem}")
return 1
print(f"OK: every file declared in {exercise}/.meta/config.json exists inside the exercise")
return 0


if __name__ == "__main__":
sys.exit(main(sys.argv))
Loading