A2: alpha acceptance checklist and cargo xtask demo-project
docs/alpha-checklist.md turns the six alpha workflows into manual steps for Windows and macOS (action, expected result, a box per platform, about 40 minutes each) and says how to report a failure. cargo xtask demo-project DIR creates the offline demo the steps run against: a small PHP shop (classes, an interface, a function, one deliberate error), a history by three authors from 2024 to 2026 with a merged branch and a tag, the branch feature/discounts that conflicts with main, and a bare origin.git holding a remote-only branch and one commit the project has not fetched yet. Tested against real git. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
83aeec68c0
commit
13c42ccc40
6 changed files with 1071 additions and 2 deletions
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "xtask"
|
||||
description = "Project automation: ci, layers, assets, cleanroom, dev, fixtures, mac-report"
|
||||
description = "Project automation: ci, layers, assets, cleanroom, dev, fixtures, demo-project, mac-report"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
|
|
|||
875
xtask/src/demo.rs
Normal file
875
xtask/src/demo.rs
Normal file
|
|
@ -0,0 +1,875 @@
|
|||
//! `cargo xtask demo-project <dir>`: an offline demo for the alpha checklist
|
||||
//! (`docs/alpha-checklist.md`).
|
||||
//!
|
||||
//! It creates, inside `<dir>`:
|
||||
//! - `shop/`, a small PHP project (classes, an interface, a function, one
|
||||
//! deliberate error for diagnostics) with a Git history by three authors
|
||||
//! over three years, a merged branch, a tag, and the branch
|
||||
//! `feature/discounts`, which conflicts with `main` in
|
||||
//! `src/Service/PriceCalculator.php`;
|
||||
//! - `origin.git/`, a bare repository that is `shop`'s `origin`. It holds the
|
||||
//! branch `release/1.0` (only remote in `shop`) and one commit on `main`
|
||||
//! that `shop` does not know yet, so a fetch shows one incoming commit.
|
||||
//!
|
||||
//! Nothing touches the network or the user's Git configuration; the
|
||||
//! repository sets its own committer identity and turns commit signing off.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use crate::util::TaskResult;
|
||||
|
||||
/// A person in the demo history: name, e-mail address.
|
||||
type Author = (&'static str, &'static str);
|
||||
|
||||
/// Author of the skeleton, the customer branch and the entry point.
|
||||
const ADA: Author = ("Ada Lindqvist", "ada@example.com");
|
||||
/// Author of the repository and the rounding change.
|
||||
const BEN: Author = ("Ben Okafor", "ben@example.com");
|
||||
/// Author of the price calculator, the discounts branch and the remote commit.
|
||||
const CLEO: Author = ("Cleo Marchetti", "cleo@example.com");
|
||||
|
||||
/// The identity the demo repository commits with, so the checklist's commits
|
||||
/// work on a machine without a global Git identity.
|
||||
const TESTER: Author = ("Lutra Tester", "tester@example.com");
|
||||
|
||||
/// Variables that would point git at another repository.
|
||||
const GIT_REDIRECTS: &[&str] = &[
|
||||
"GIT_DIR",
|
||||
"GIT_WORK_TREE",
|
||||
"GIT_INDEX_FILE",
|
||||
"GIT_OBJECT_DIRECTORY",
|
||||
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
||||
"GIT_COMMON_DIR",
|
||||
"GIT_NAMESPACE",
|
||||
];
|
||||
|
||||
/// Folder length (bytes) above which a failure on Windows gets a hint about
|
||||
/// short paths: a push into the bare repository writes through a quarantine
|
||||
/// folder whose object paths pass 260 characters from about 150 on.
|
||||
const LONG_PATH_HINT: usize = 100;
|
||||
|
||||
/// Paths of the generated demo.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Demo {
|
||||
/// The PHP project and its work tree.
|
||||
pub shop: PathBuf,
|
||||
/// The bare repository configured as `origin`.
|
||||
pub origin: PathBuf,
|
||||
}
|
||||
|
||||
/// Runs `cargo xtask demo-project <dir>`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Fails without a directory argument, when the directory exists and is not
|
||||
/// empty, when git is missing, or when a git call fails.
|
||||
pub fn run(args: &[String]) -> TaskResult {
|
||||
let Some(dir) = args.first() else {
|
||||
return Err("usage: cargo xtask demo-project <dir>".into());
|
||||
};
|
||||
let dir = std::path::absolute(dir).map_err(|e| format!("cannot resolve `{dir}`: {e}"))?;
|
||||
let demo = create(&dir).map_err(|e| {
|
||||
if cfg!(windows) && dir.as_os_str().len() > LONG_PATH_HINT {
|
||||
format!(
|
||||
"{e}\n(git on Windows fails on paths near 260 characters; use a short folder such as C:\\lutra-demo)"
|
||||
)
|
||||
} else {
|
||||
e
|
||||
}
|
||||
})?;
|
||||
println!("demo-project: ready");
|
||||
println!(" project: {}", demo.shop.display());
|
||||
println!(" origin: {}", demo.origin.display());
|
||||
println!("open the project in Lutra and follow docs/alpha-checklist.md");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creates the demo in `dir`, which must be missing or empty.
|
||||
///
|
||||
/// # Errors
|
||||
/// Fails when `dir` is not empty, a file cannot be written, git is missing or
|
||||
/// a git call fails.
|
||||
pub fn create(dir: &Path) -> TaskResult<Demo> {
|
||||
if dir.exists() {
|
||||
let mut entries = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
if entries.next().is_some() {
|
||||
return Err(format!(
|
||||
"{} is not empty; pass a new or empty folder",
|
||||
dir.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
Command::new("git")
|
||||
.arg("--version")
|
||||
.output()
|
||||
.map_err(|e| format!("git is not on the PATH: {e}"))?;
|
||||
let shop = dir.join("shop");
|
||||
let origin = dir.join("origin.git");
|
||||
std::fs::create_dir_all(&shop).map_err(|e| format!("{}: {e}", shop.display()))?;
|
||||
|
||||
git(&shop, &["init", "-q", "-b", "main"], None)?;
|
||||
for (key, value) in [
|
||||
("user.name", TESTER.0),
|
||||
("user.email", TESTER.1),
|
||||
("commit.gpgsign", "false"),
|
||||
("tag.gpgsign", "false"),
|
||||
] {
|
||||
git(&shop, &["config", key, value], None)?;
|
||||
}
|
||||
|
||||
write_files(
|
||||
&shop,
|
||||
&[
|
||||
("composer.json", COMPOSER_JSON),
|
||||
(".gitignore", GITIGNORE),
|
||||
("README.md", README_V1),
|
||||
("src/Model/Product.php", PRODUCT),
|
||||
],
|
||||
)?;
|
||||
commit(
|
||||
&shop,
|
||||
"Initial project skeleton",
|
||||
ADA,
|
||||
Some("2024-03-12T09:14:00+01:00"),
|
||||
)?;
|
||||
write_files(
|
||||
&shop,
|
||||
&[
|
||||
("src/Repository/ProductRepository.php", PRODUCT_REPOSITORY),
|
||||
(
|
||||
"src/Repository/InMemoryProductRepository.php",
|
||||
IN_MEMORY_REPOSITORY,
|
||||
),
|
||||
],
|
||||
)?;
|
||||
commit(
|
||||
&shop,
|
||||
"Add product repository",
|
||||
BEN,
|
||||
Some("2024-09-30T16:40:00+02:00"),
|
||||
)?;
|
||||
write_files(
|
||||
&shop,
|
||||
&[
|
||||
("src/Service/PriceCalculator.php", PRICE_CALCULATOR_BASE),
|
||||
("src/functions.php", FUNCTIONS),
|
||||
],
|
||||
)?;
|
||||
commit(
|
||||
&shop,
|
||||
"Add price calculator and price formatting",
|
||||
CLEO,
|
||||
Some("2025-06-02T11:05:00+02:00"),
|
||||
)?;
|
||||
|
||||
git(&shop, &["switch", "-q", "-c", "feature/customer"], None)?;
|
||||
write_files(&shop, &[("src/Model/Customer.php", CUSTOMER)])?;
|
||||
commit(
|
||||
&shop,
|
||||
"Add customer model",
|
||||
ADA,
|
||||
Some("2025-10-01T10:00:00+02:00"),
|
||||
)?;
|
||||
write_files(&shop, &[("src/Service/Checkout.php", CHECKOUT)])?;
|
||||
commit(
|
||||
&shop,
|
||||
"Add checkout service",
|
||||
ADA,
|
||||
Some("2025-10-02T14:30:00+02:00"),
|
||||
)?;
|
||||
git(&shop, &["switch", "-q", "main"], None)?;
|
||||
write_files(&shop, &[("README.md", README_V2)])?;
|
||||
commit(
|
||||
&shop,
|
||||
"Document the project layout",
|
||||
BEN,
|
||||
Some("2025-10-05T08:45:00+02:00"),
|
||||
)?;
|
||||
git(
|
||||
&shop,
|
||||
&[
|
||||
"merge",
|
||||
"-q",
|
||||
"--no-ff",
|
||||
"-m",
|
||||
"Merge branch 'feature/customer'",
|
||||
"feature/customer",
|
||||
],
|
||||
Some((ADA, Some("2025-11-20T17:20:00+01:00"))),
|
||||
)?;
|
||||
git(&shop, &["tag", "v0.1.0"], None)?;
|
||||
git(&shop, &["branch", "release/1.0"], None)?;
|
||||
|
||||
git(&shop, &["switch", "-q", "-c", "feature/discounts"], None)?;
|
||||
write_files(
|
||||
&shop,
|
||||
&[("src/Service/DiscountPolicy.php", DISCOUNT_POLICY)],
|
||||
)?;
|
||||
commit(
|
||||
&shop,
|
||||
"Add discount policy",
|
||||
CLEO,
|
||||
Some("2026-09-03T09:30:00+02:00"),
|
||||
)?;
|
||||
write_files(
|
||||
&shop,
|
||||
&[(
|
||||
"src/Service/PriceCalculator.php",
|
||||
PRICE_CALCULATOR_DISCOUNTS,
|
||||
)],
|
||||
)?;
|
||||
commit(
|
||||
&shop,
|
||||
"Support discounts in gross prices",
|
||||
CLEO,
|
||||
Some("2026-09-05T15:10:00+02:00"),
|
||||
)?;
|
||||
|
||||
git(&shop, &["switch", "-q", "main"], None)?;
|
||||
write_files(
|
||||
&shop,
|
||||
&[("src/Service/PriceCalculator.php", PRICE_CALCULATOR_ROUNDED)],
|
||||
)?;
|
||||
commit(
|
||||
&shop,
|
||||
"Round gross prices to cents",
|
||||
BEN,
|
||||
Some("2026-08-14T13:00:00+02:00"),
|
||||
)?;
|
||||
write_files(&shop, &[("public/index.php", INDEX)])?;
|
||||
commit(&shop, "Add a command-line entry point", ADA, None)?;
|
||||
|
||||
let origin_url = origin.to_string_lossy().replace('\\', "/");
|
||||
git(
|
||||
dir,
|
||||
&["init", "-q", "--bare", "-b", "main", "origin.git"],
|
||||
None,
|
||||
)?;
|
||||
git(&shop, &["remote", "add", "origin", &origin_url], None)?;
|
||||
git(&shop, &["push", "-q", "-u", "origin", "main"], None)?;
|
||||
git(
|
||||
&shop,
|
||||
&["push", "-q", "origin", "v0.1.0", "release/1.0"],
|
||||
None,
|
||||
)?;
|
||||
git(&shop, &["branch", "-q", "-D", "release/1.0"], None)?;
|
||||
|
||||
git(&shop, &["switch", "-q", "-c", "teammate"], None)?;
|
||||
write_files(&shop, &[("CHANGELOG.md", CHANGELOG)])?;
|
||||
commit(&shop, "Start a changelog", CLEO, None)?;
|
||||
git(&shop, &["push", "-q", "origin", "teammate:main"], None)?;
|
||||
git(&shop, &["switch", "-q", "main"], None)?;
|
||||
git(&shop, &["branch", "-q", "-D", "teammate"], None)?;
|
||||
git(
|
||||
&shop,
|
||||
&["update-ref", "refs/remotes/origin/main", "refs/heads/main"],
|
||||
None,
|
||||
)?;
|
||||
|
||||
write_files(&shop, &[("var/log/app.log", APP_LOG)])?;
|
||||
Ok(Demo { shop, origin })
|
||||
}
|
||||
|
||||
/// Writes `files` (relative path, contents) below `root`, creating folders.
|
||||
///
|
||||
/// # Errors
|
||||
/// Fails when a folder or file cannot be written.
|
||||
fn write_files(root: &Path, files: &[(&str, &str)]) -> TaskResult {
|
||||
for (rel, text) in files {
|
||||
let path = root.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
|
||||
}
|
||||
std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stages everything and commits it as `author` at `date` (ISO 8601; `None`
|
||||
/// is now). The committer is the author, so log and blame show one person.
|
||||
///
|
||||
/// # Errors
|
||||
/// Fails when git fails.
|
||||
fn commit(repo: &Path, message: &str, author: Author, date: Option<&str>) -> TaskResult {
|
||||
git(repo, &["add", "-A"], None)?;
|
||||
git(
|
||||
repo,
|
||||
&["commit", "-q", "--no-verify", "-m", message],
|
||||
Some((author, date)),
|
||||
)
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
/// Runs git in `dir` with the redirecting variables removed and, with `who`,
|
||||
/// the author and committer set to that person and date.
|
||||
///
|
||||
/// # Errors
|
||||
/// Fails when git cannot start or exits unsuccessfully; the message holds
|
||||
/// git's error output.
|
||||
fn git(dir: &Path, args: &[&str], who: Option<(Author, Option<&str>)>) -> TaskResult<String> {
|
||||
let mut command = Command::new("git");
|
||||
command
|
||||
.args(["-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false"])
|
||||
.args(args)
|
||||
.current_dir(dir);
|
||||
for name in GIT_REDIRECTS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
if let Some(((name, email), date)) = who {
|
||||
command
|
||||
.env("GIT_AUTHOR_NAME", name)
|
||||
.env("GIT_AUTHOR_EMAIL", email)
|
||||
.env("GIT_COMMITTER_NAME", name)
|
||||
.env("GIT_COMMITTER_EMAIL", email);
|
||||
if let Some(date) = date {
|
||||
command
|
||||
.env("GIT_AUTHOR_DATE", date)
|
||||
.env("GIT_COMMITTER_DATE", date);
|
||||
}
|
||||
}
|
||||
let output = command
|
||||
.output()
|
||||
.map_err(|e| format!("cannot start git: {e}"))?;
|
||||
if !output.status.success() {
|
||||
return Err(format!(
|
||||
"`git {}` failed in {}: {}",
|
||||
args.join(" "),
|
||||
dir.display(),
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
));
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
|
||||
}
|
||||
|
||||
/// `composer.json` with a PSR-4 autoload, so the language server finds the
|
||||
/// classes by namespace.
|
||||
const COMPOSER_JSON: &str = r#"{
|
||||
"name": "lutra/demo-shop",
|
||||
"description": "A small shop for the Lutra alpha checklist",
|
||||
"type": "project",
|
||||
"license": "MIT",
|
||||
"require": {
|
||||
"php": ">=8.2"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Demo\\Shop\\": "src/"
|
||||
},
|
||||
"files": [
|
||||
"src/functions.php"
|
||||
]
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
/// Ignores `var/` (the log file shows the ignored colour) and `vendor/`.
|
||||
const GITIGNORE: &str = "/var/\n/vendor/\n";
|
||||
|
||||
/// The first README.
|
||||
const README_V1: &str = "# Demo shop\n\nA small PHP project for trying Lutra.\n";
|
||||
|
||||
/// The README after "Document the project layout".
|
||||
const README_V2: &str = "# Demo shop
|
||||
|
||||
A small PHP project for trying Lutra.
|
||||
|
||||
## Layout
|
||||
|
||||
- `src/Model`: products and customers
|
||||
- `src/Repository`: where products come from
|
||||
- `src/Service`: prices and the checkout
|
||||
- `public/index.php`: run it with `php public/index.php`
|
||||
";
|
||||
|
||||
/// The commit on `origin/main` that the local `main` does not have yet.
|
||||
const CHANGELOG: &str = "# Changelog
|
||||
|
||||
## Unreleased
|
||||
|
||||
- Prices are rounded to cents.
|
||||
- `php public/index.php` prints a sample total.
|
||||
";
|
||||
|
||||
/// An ignored file.
|
||||
const APP_LOG: &str = "[2026-10-30 09:00:00] demo.INFO: ignored by .gitignore\n";
|
||||
|
||||
/// The product model.
|
||||
const PRODUCT: &str = r#"<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Demo\Shop\Model;
|
||||
|
||||
/**
|
||||
* A product in the catalogue, priced net of VAT.
|
||||
*/
|
||||
final class Product
|
||||
{
|
||||
public function __construct(
|
||||
public readonly string $sku,
|
||||
public readonly string $name,
|
||||
public readonly float $netPrice,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a copy of the product with another net price.
|
||||
*/
|
||||
public function withNetPrice(float $netPrice): self
|
||||
{
|
||||
return new self($this->sku, $this->name, $netPrice);
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
/// The customer model.
|
||||
const CUSTOMER: &str = r#"<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Demo\Shop\Model;
|
||||
|
||||
/**
|
||||
* A customer; business customers pay net prices.
|
||||
*/
|
||||
final class Customer
|
||||
{
|
||||
public function __construct(
|
||||
public readonly string $email,
|
||||
public readonly string $name,
|
||||
public readonly bool $isBusiness = false,
|
||||
) {
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
/// The repository interface.
|
||||
const PRODUCT_REPOSITORY: &str = r#"<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Demo\Shop\Repository;
|
||||
|
||||
use Demo\Shop\Model\Product;
|
||||
|
||||
/**
|
||||
* Where products come from.
|
||||
*/
|
||||
interface ProductRepository
|
||||
{
|
||||
/**
|
||||
* Finds a product by its SKU, or null when there is none.
|
||||
*/
|
||||
public function findBySku(string $sku): ?Product;
|
||||
|
||||
/**
|
||||
* Returns every product.
|
||||
*
|
||||
* @return list<Product>
|
||||
*/
|
||||
public function all(): array;
|
||||
|
||||
/**
|
||||
* Adds a product or replaces the one with the same SKU.
|
||||
*/
|
||||
public function save(Product $product): void;
|
||||
}
|
||||
"#;
|
||||
|
||||
/// The in-memory implementation of the repository.
|
||||
const IN_MEMORY_REPOSITORY: &str = r#"<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Demo\Shop\Repository;
|
||||
|
||||
use Demo\Shop\Model\Product;
|
||||
|
||||
/**
|
||||
* Keeps products in an array, by SKU.
|
||||
*/
|
||||
final class InMemoryProductRepository implements ProductRepository
|
||||
{
|
||||
/** @var array<string, Product> */
|
||||
private array $items = [];
|
||||
|
||||
/**
|
||||
* @param list<Product> $products
|
||||
*/
|
||||
public function __construct(array $products = [])
|
||||
{
|
||||
foreach ($products as $product) {
|
||||
$this->save($product);
|
||||
}
|
||||
}
|
||||
|
||||
public function findBySku(string $sku): ?Product
|
||||
{
|
||||
return $this->items[$sku] ?? null;
|
||||
}
|
||||
|
||||
public function all(): array
|
||||
{
|
||||
return array_values($this->items);
|
||||
}
|
||||
|
||||
public function save(Product $product): void
|
||||
{
|
||||
$this->items[$product->sku] = $product;
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
/// The price calculator as first committed (the merge base of the conflict).
|
||||
const PRICE_CALCULATOR_BASE: &str = r#"<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Demo\Shop\Service;
|
||||
|
||||
use Demo\Shop\Model\Product;
|
||||
|
||||
/**
|
||||
* Turns net prices into gross prices.
|
||||
*/
|
||||
final class PriceCalculator
|
||||
{
|
||||
private const VAT_RATE = 0.19;
|
||||
|
||||
/**
|
||||
* Returns the gross price for a net price.
|
||||
*
|
||||
* @param float $net the net price in euros
|
||||
*/
|
||||
public function gross(float $net): float
|
||||
{
|
||||
return $net * (1 + self::VAT_RATE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the gross price of a product.
|
||||
*/
|
||||
public function grossFor(Product $product): float
|
||||
{
|
||||
return $this->gross($product->netPrice);
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
/// The price calculator on `main`: rounds to cents.
|
||||
const PRICE_CALCULATOR_ROUNDED: &str = r#"<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Demo\Shop\Service;
|
||||
|
||||
use Demo\Shop\Model\Product;
|
||||
|
||||
/**
|
||||
* Turns net prices into gross prices.
|
||||
*/
|
||||
final class PriceCalculator
|
||||
{
|
||||
private const VAT_RATE = 0.19;
|
||||
|
||||
/**
|
||||
* Returns the gross price for a net price, rounded to cents.
|
||||
*
|
||||
* @param float $net the net price in euros
|
||||
*/
|
||||
public function gross(float $net): float
|
||||
{
|
||||
return round($net * (1 + self::VAT_RATE), 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the gross price of a product.
|
||||
*/
|
||||
public function grossFor(Product $product): float
|
||||
{
|
||||
return $this->gross($product->netPrice);
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
/// The price calculator on `feature/discounts`: takes a discount. Changes the
|
||||
/// same lines as `main`, so merging the branch conflicts.
|
||||
const PRICE_CALCULATOR_DISCOUNTS: &str = r#"<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Demo\Shop\Service;
|
||||
|
||||
use Demo\Shop\Model\Product;
|
||||
|
||||
/**
|
||||
* Turns net prices into gross prices.
|
||||
*/
|
||||
final class PriceCalculator
|
||||
{
|
||||
private const VAT_RATE = 0.19;
|
||||
|
||||
/**
|
||||
* Returns the gross price for a net price after a discount.
|
||||
*
|
||||
* @param float $net the net price in euros
|
||||
* @param float $discount the net discount in euros
|
||||
*/
|
||||
public function gross(float $net, float $discount = 0.0): float
|
||||
{
|
||||
return max(0.0, $net - $discount) * (1 + self::VAT_RATE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the gross price of a product.
|
||||
*/
|
||||
public function grossFor(Product $product): float
|
||||
{
|
||||
return $this->gross($product->netPrice);
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
/// The discount policy, only on `feature/discounts`.
|
||||
const DISCOUNT_POLICY: &str = r#"<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Demo\Shop\Service;
|
||||
|
||||
use Demo\Shop\Model\Customer;
|
||||
|
||||
/**
|
||||
* Business customers get five percent off.
|
||||
*/
|
||||
final class DiscountPolicy
|
||||
{
|
||||
public function discountFor(Customer $customer, float $net): float
|
||||
{
|
||||
return $customer->isBusiness ? $net * 0.05 : 0.0;
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
/// The price formatting function, for signature help.
|
||||
const FUNCTIONS: &str = r#"<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Demo\Shop;
|
||||
|
||||
/**
|
||||
* Formats an amount of money for display, such as "12.50 EUR".
|
||||
*
|
||||
* @param float $amount the amount
|
||||
* @param string $currency the ISO 4217 currency code
|
||||
* @param int $decimals the number of decimals
|
||||
*/
|
||||
function format_price(float $amount, string $currency = 'EUR', int $decimals = 2): string
|
||||
{
|
||||
return number_format($amount, $decimals, '.', '') . ' ' . $currency;
|
||||
}
|
||||
"#;
|
||||
|
||||
/// The checkout service, with the deliberate error in `preview()`.
|
||||
const CHECKOUT: &str = r#"<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Demo\Shop\Service;
|
||||
|
||||
use Demo\Shop\Model\Customer;
|
||||
use Demo\Shop\Repository\ProductRepository;
|
||||
|
||||
use function Demo\Shop\format_price;
|
||||
|
||||
/**
|
||||
* Adds up a customer's basket.
|
||||
*/
|
||||
final class Checkout
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ProductRepository $products,
|
||||
private readonly PriceCalculator $calculator,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the formatted total for the given SKUs; unknown SKUs are
|
||||
* skipped.
|
||||
*
|
||||
* @param list<string> $skus
|
||||
*/
|
||||
public function total(Customer $customer, array $skus): string
|
||||
{
|
||||
$sum = 0.0;
|
||||
foreach ($skus as $sku) {
|
||||
$product = $this->products->findBySku($sku);
|
||||
if ($product === null) {
|
||||
continue;
|
||||
}
|
||||
$sum += $customer->isBusiness
|
||||
? $product->netPrice
|
||||
: $this->calculator->grossFor($product);
|
||||
}
|
||||
|
||||
return format_price($sum);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deliberate error for the alpha checklist: PriceCalculator has no
|
||||
* method grossPrice(), so the language server reports it.
|
||||
*/
|
||||
public function preview(float $net): string
|
||||
{
|
||||
return format_price($this->calculator->grossPrice($net));
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
/// The entry point for the terminal step; prints `19.88 EUR`.
|
||||
const INDEX: &str = r#"<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Demo\Shop\Model\Customer;
|
||||
use Demo\Shop\Model\Product;
|
||||
use Demo\Shop\Repository\InMemoryProductRepository;
|
||||
use Demo\Shop\Service\Checkout;
|
||||
use Demo\Shop\Service\PriceCalculator;
|
||||
|
||||
spl_autoload_register(static function (string $class): void {
|
||||
$prefix = 'Demo\\Shop\\';
|
||||
if (str_starts_with($class, $prefix)) {
|
||||
require __DIR__ . '/../src/' . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php';
|
||||
}
|
||||
});
|
||||
require __DIR__ . '/../src/functions.php';
|
||||
|
||||
$products = new InMemoryProductRepository([
|
||||
new Product('TEA-01', 'Green tea', 4.20),
|
||||
new Product('MUG-02', 'Otter mug', 12.50),
|
||||
]);
|
||||
$checkout = new Checkout($products, new PriceCalculator());
|
||||
|
||||
echo $checkout->total(new Customer('ada@example.com', 'Ada'), ['TEA-01', 'MUG-02']), PHP_EOL;
|
||||
"#;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A fresh, unique folder under the system temp directory.
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
let nanos = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0);
|
||||
std::env::temp_dir().join(format!("lutra-demo-{name}-{}-{nanos}", std::process::id()))
|
||||
}
|
||||
|
||||
/// Whether git can be started; the test skips without it.
|
||||
fn has_git() -> bool {
|
||||
Command::new("git").arg("--version").output().is_ok()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creates_history_branches_remote_and_a_conflict() {
|
||||
if !has_git() {
|
||||
eprintln!("skipped: git is not installed");
|
||||
return;
|
||||
}
|
||||
let dir = temp_dir("full");
|
||||
let demo = create(&dir).unwrap();
|
||||
let shop = &demo.shop;
|
||||
|
||||
assert!(shop.join("src/Service/Checkout.php").is_file());
|
||||
assert!(demo.origin.join("HEAD").is_file());
|
||||
assert_eq!(git(shop, &["status", "--porcelain"], None).unwrap(), "");
|
||||
assert_eq!(
|
||||
git(shop, &["branch", "--show-current"], None)
|
||||
.unwrap()
|
||||
.trim(),
|
||||
"main"
|
||||
);
|
||||
|
||||
let mut authors: Vec<String> = git(shop, &["log", "--all", "--format=%an"], None)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
authors.sort();
|
||||
authors.dedup();
|
||||
assert_eq!(authors, ["Ada Lindqvist", "Ben Okafor", "Cleo Marchetti"]);
|
||||
let years = git(shop, &["log", "--format=%ad", "--date=format:%Y"], None).unwrap();
|
||||
assert!(years.contains("2024") && years.contains("2025") && years.contains("2026"));
|
||||
|
||||
let refs = git(shop, &["for-each-ref", "--format=%(refname:short)"], None).unwrap();
|
||||
for name in [
|
||||
"main",
|
||||
"feature/customer",
|
||||
"feature/discounts",
|
||||
"origin/main",
|
||||
"origin/release/1.0",
|
||||
"v0.1.0",
|
||||
] {
|
||||
assert!(refs.lines().any(|r| r == name), "{name} missing in {refs}");
|
||||
}
|
||||
assert!(!refs.lines().any(|r| r == "release/1.0" || r == "teammate"));
|
||||
assert_eq!(
|
||||
git(
|
||||
shop,
|
||||
&["rev-parse", "--abbrev-ref", "main@{upstream}"],
|
||||
None
|
||||
)
|
||||
.unwrap()
|
||||
.trim(),
|
||||
"origin/main"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
git(shop, &["check-ignore", "var/log/app.log"], None)
|
||||
.unwrap()
|
||||
.trim(),
|
||||
"var/log/app.log"
|
||||
);
|
||||
|
||||
git(shop, &["fetch", "-q", "origin"], None).unwrap();
|
||||
assert_eq!(
|
||||
git(shop, &["rev-list", "--count", "main..origin/main"], None)
|
||||
.unwrap()
|
||||
.trim(),
|
||||
"1"
|
||||
);
|
||||
|
||||
assert!(git(shop, &["merge", "--no-edit", "feature/discounts"], None).is_err());
|
||||
assert_eq!(
|
||||
git(shop, &["diff", "--name-only", "--diff-filter=U"], None)
|
||||
.unwrap()
|
||||
.trim(),
|
||||
"src/Service/PriceCalculator.php"
|
||||
);
|
||||
assert!(shop.join("src/Service/DiscountPolicy.php").is_file());
|
||||
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_folder_that_is_not_empty() {
|
||||
let dir = temp_dir("busy");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("keep.txt"), "mine").unwrap();
|
||||
let err = create(&dir).unwrap_err();
|
||||
assert!(err.contains("not empty"), "{err}");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.join("keep.txt")).unwrap(),
|
||||
"mine"
|
||||
);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn needs_a_folder_argument() {
|
||||
assert!(run(&[]).unwrap_err().contains("usage"));
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@
|
|||
|
||||
mod assets;
|
||||
mod cleanroom;
|
||||
mod demo;
|
||||
mod layers;
|
||||
mod licences;
|
||||
mod lints;
|
||||
|
|
@ -27,6 +28,7 @@ commands:
|
|||
lints-selftest prove that shipped unwrap() fails clippy and test unwrap() passes
|
||||
dev [-- ARGS] run the desktop app in development mode, ARGS go to the app
|
||||
fixtures create Symfony and Laravel reference projects in target/fixtures/
|
||||
demo-project DIR create the offline demo for docs/alpha-checklist.md in DIR
|
||||
",
|
||||
"mac-report [--skip-gate] [--port PORT] [--out DIR]
|
||||
check this machine end to end and write one report file
|
||||
|
|
@ -57,6 +59,7 @@ fn main() -> ExitCode {
|
|||
tasks::dev(&app_args)
|
||||
}
|
||||
"fixtures" => tasks::fixtures(),
|
||||
"demo-project" => demo::run(rest),
|
||||
"mac-report" => macreport::parse(rest).and_then(|o| macreport::mac_report(&o)),
|
||||
"help" | "--help" | "-h" => {
|
||||
println!("{USAGE}");
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue