diff --git a/ROADMAP.md b/ROADMAP.md index 120b92c6..263a655c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -46,7 +46,7 @@ Changes to `.github/workflows/deploy.yml`, release tags, Pages deployment, or ve - [ ] **Formatting Expectations**: Document a supported Prettier command and intentionally add any further linting or pre-commit tooling only when it fits the repository. - [x] **AI Contextualization**: Create a `.github/copilot-instructions.md` to help GitHub Copilot understand the conference data schema and project goals. - [ ] **Prompt Imports**: Build a library of standardized prompts to assist contributors in formatting and validating new conference submissions. -- [ ] **Maintenance Script Documentation**: Document the scripts in `tools/`, especially `tools/identify_updates.rb`, `tools/monthly_data.rb`, and `tools/status_find.rb`, or remove/replace scripts that are no longer part of the workflow. +- [ ] **Maintenance Script Documentation**: Document the scripts in `tools/`, especially `tools/identify_updates.rb` and `tools/status_find.rb`, or remove/replace scripts that are no longer part of the workflow. - [ ] **Local Verification Docs**: Make the local build and validation paths reliable and clear for both Docker and non-Docker setups. ### WebMCP experiment @@ -80,14 +80,14 @@ References: ### Platform-neutral draft generator -- [ ] **Define the Newsletter Format**: Document the recurring sections, selection rules, tone, subject-line pattern, and optional editorial or sponsor content using representative past issues. -- [ ] **Replace the Monthly Data Prototype**: Upgrade or replace `tools/monthly_data.rb` with a non-interactive command that accepts a target month such as `--month 2026-09`. -- [ ] **Generate Markdown**: Read `_data/current.yml`, select the relevant conferences, and render a polished Markdown draft rather than raw YAML. -- [ ] **Highlight Timely Information**: Group supported CFP, registration, and early-bird information without inventing details that are absent from the conference data. -- [ ] **Support Editorial Review**: Include clearly marked areas for an introduction, sponsor copy, announcements, and final notes. -- [ ] **Keep Drafts Reviewable**: Store generated drafts in a predictable, version-controlled location and make repeated generation deterministic. -- [ ] **Add Focused Tests**: Cover month selection, chronological order, missing or ambiguous dates, escaping, links, and empty-month behavior. -- [ ] **Document the Workflow**: Add the local command, expected output, review checklist, and troubleshooting guidance. +- [x] **Define the Newsletter Format**: Document the recurring sections, selection rules, tone, subject-line pattern, and optional editorial or sponsor content using representative past issues. +- [x] **Replace the Monthly Data Prototype**: Upgrade or replace `tools/monthly_data.rb` with a non-interactive command that accepts a target month such as `--month 2026-09`. +- [x] **Generate Markdown**: Read `_data/current.yml`, select the relevant conferences, and render a polished Markdown draft rather than raw YAML. +- [x] **Highlight Timely Information**: Group supported CFP, registration, and early-bird information without inventing details that are absent from the conference data. +- [x] **Support Editorial Review**: Include clearly marked areas for an introduction, sponsor copy, announcements, and final notes. +- [x] **Keep Drafts Reviewable**: Store generated drafts in a predictable, version-controlled location and make repeated generation deterministic. +- [x] **Add Focused Tests**: Cover month selection, chronological order, missing or ambiguous dates, escaping, links, and empty-month behavior. +- [x] **Document the Workflow**: Add the local command, expected output, review checklist, and troubleshooting guidance. ### Buttondown trial diff --git a/SPEC-newsletter-generator.md b/SPEC-newsletter-generator.md new file mode 100644 index 00000000..ed4868a4 --- /dev/null +++ b/SPEC-newsletter-generator.md @@ -0,0 +1,231 @@ +--- +published: false +--- + +# Spec: Newsletter Draft Generator — V1 + +Status: approved 2026-11-14 + +## Objective + +Provide maintainers with a non-interactive Ruby command that turns conference data +from `_data/current.yml` into a deterministic, reviewable monthly newsletter draft. +The command reduces repetitive formatting work while keeping all editorial decisions, +provider uploads, scheduling, and sending under human control. + +The generated draft is a starting point, not a finished campaign. It must preserve +source wording and links, identify data that needs review, and never infer facts that +are absent from the conference data. + +## Newsletter Format + +Each generated `_drafts/YYYY-MM-newsletter.md` file contains, in this order: + +1. A title naming the target month and year. +2. A deterministic suggested subject and preheader based on the selected event count. +3. A clearly marked introduction placeholder. +4. A clearly marked sponsor-copy placeholder. +5. Three monthly conference sections beginning with the requested month. Each entry + includes the linked name, source date text, location, and source status when present. +6. An `Upcoming discounts` section containing every upcoming event whose source status + identifies an active early-bird, super-early-bird, blind-bird, discount, or similar + reduced-price offer. +7. An `Open CFPs` section containing every upcoming event whose source status explicitly + identifies an open call for proposals, papers, or speakers. +8. A clearly marked announcements placeholder. +9. A clearly marked final-notes placeholder. +10. A deterministic link to the live conference list and contribution instructions. +11. A `Review before sending` checklist identifying ambiguous or unparseable source + dates and reminding the editor to verify generated copy and links. + +Editorial placeholders use visible bracketed text and adjacent HTML comments so they +are easy to find and hard to mistake for finished copy. Existing `` elements in a +status are converted to Markdown links. Other HTML is reduced to readable plain text; +the generator does not pass arbitrary source HTML into the Markdown draft. + +## Selection Rules + +- `--month` is required and must use the exact `YYYY-MM` form. +- The requested month is the first month in a rolling three-calendar-month conference + window. For example, `--month 2026-10` produces October, November, and December 2026 + conference sections. +- An event appears in the three-month conference window when its parsed start date is + inside that window. A cross-month event is grouped under its start month. +- Events within each month are ordered by parsed start date, then by name for a + deterministic tie break. Source YAML order does not determine newsletter order. +- Unparseable or ambiguous dates are not guessed. Those events are excluded from the + conference window, discount list, and CFP list and are named in the review checklist. +- A month with no selected events still receives its own heading and an explicit + no-events message. +- `Upcoming discounts` and `Open CFPs` are not limited to the three-month conference + window. They inspect all parseable upcoming events whose end date is on or after the + first day of the requested month. +- Discount matching is case-insensitive and includes supported active terms such as + early bird, super early bird, blind bird, discount, savings, and reduced pricing. + A status explicitly marked closed, ended, expired, or sold out is excluded. +- CFP matching is case-insensitive and requires both a supported CFP/call-for-proposals, + papers, or speakers term and an explicit open state. A closed CFP is excluded. +- Ordinary registration status is retained on conference entries in the three-month + window. It does not create a separate all-registration section. +- Status wording, links, and deadlines are copied only from `_data/current.yml`. A + listed deadline does not control whether an otherwise active discount or CFP is + included; the editor must verify that source statuses remain current before sending. + +## Commands + +Generate or deterministically replace a draft: + +```bash +ruby tools/newsletter.rb --month 2026-11 +``` + +Generate to an explicit path for review or testing: + +```bash +ruby tools/newsletter.rb --month 2026-11 --output /tmp/2026-11-newsletter.md +``` + +Run focused tests: + +```bash +ruby test/newsletter_test.rb +``` + +Run existing data validation and its regression suite: + +```bash +ruby tools/validate_data.rb +ruby test/validate_data_test.rb +``` + +Run the relevant site gates when the local Ruby environment supports them: + +```bash +bundle exec jekyll build --verbose +bundle exec htmlproofer ./_site --disable-external --no-enforce-https --allow-missing-href --ignore-urls '/^\/\//' +``` + +## Project Structure + +```text +tools/newsletter.rb CLI entry point and newsletter implementation +test/newsletter_test.rb focused unit and command-level tests +test/fixtures/newsletter/ isolated conference-data fixtures +_drafts/YYYY-MM-newsletter.md generated, version-controlled editorial drafts +docs/newsletter-workflow.md command, review checklist, and troubleshooting +``` + +The implementation remains a small Ruby script using the standard library and the +repository's existing Minitest convention. V1 does not introduce a provider adapter +or a generalized plugin architecture. + +## Code Style + +Follow existing Ruby conventions: frozen string literals, two-space indentation, +small named methods, standard-library dependencies, and explicit error messages. +Parsing and rendering are separated so behavior can be tested without invoking a +subprocess or writing into the real `_drafts` directory. + +Example public boundary: + +```ruby +month = Newsletter::TargetMonth.parse(options.fetch(:month)) +events = Newsletter::DataFile.load(options.fetch(:data_file)) +draft = Newsletter::Draft.render(month:, events:) +Newsletter::Writer.write(options.fetch(:output), draft) +``` + +This is illustrative rather than a requirement to create one class per operation; +the implementation should use the smallest structure that keeps parsing and rendering +testable. + +## Testing Strategy + +Use Minitest and real temporary files; do not mock filesystem or YAML behavior. +Tests must be deterministic and must not read or alter the repository's production +conference data unless explicitly exercising the default CLI path. + +Focused coverage includes: + +- required and valid `--month YYYY-MM` handling; +- single-day, same-month range, and cross-month range selection; +- rolling three-month selection and month grouping across a year boundary; +- chronological ordering independent of YAML order; +- ambiguous and unparseable dates surfaced for review without guessing; +- HTML-link conversion, Markdown escaping, and safe plain-text fallback; +- all-upcoming discount selection outside the three-month event window; +- all-upcoming open-CFP selection outside the three-month event window; +- exclusion of closed discounts and CFPs; +- ordinary registration status retained only on conference entries; +- missing optional fields; +- empty-month output; +- deterministic regeneration and explicit-output behavior; +- nonzero exit status and useful messages for invalid input or unreadable data. + +Every behavior change follows RED → GREEN → REFACTOR. The focused suite runs after +each slice; the validator suite and Jekyll/htmlproofer gates run before completion. + +## Boundaries + +### Always + +- Read conference facts only from `_data/current.yml` or an explicit test data file. +- Preserve source URLs and wording unless converting supported HTML to Markdown/plain + text. +- Write drafts deterministically and replace only the exact target output file. +- Keep final editorial review and sending manual. +- Keep generated drafts version-controlled and readable without Mailchimp, Buttondown, + or any other provider. + +### Ask first + +- Change the newsletter section order or selection rules after this spec is approved. +- Change the output location from `_drafts/YYYY-MM-newsletter.md`. +- Add a gem or another dependency. +- Modify conference data, navigation, CI, deployment, versioning, or ownership files. + +### Never + +- Upload, schedule, or send a newsletter. +- Access or store provider credentials or subscriber information. +- Invent dates, locations, deadlines, registration states, sponsor copy, or editorial + prose. +- Edit generated `_site` output. +- Modify unrelated conference records while implementing the generator. + +## Success Criteria + +- `ruby tools/newsletter.rb --month YYYY-MM` succeeds without prompts and writes the + documented draft path. +- The generated Markdown follows the approved format and selection rules. +- Re-running the same command against unchanged input produces byte-identical output. +- The focused suite proves rolling three-month selection, chronological order, range + handling, ambiguous dates, escaping, links, all-upcoming discounts, all-upcoming open + CFPs, closed-status exclusion, registration display, and empty-month output. +- Invalid arguments and invalid data fail safely without partially overwriting an + existing draft. +- `ruby test/newsletter_test.rb`, `ruby tools/validate_data.rb`, and + `ruby test/validate_data_test.rb` pass. +- Jekyll builds and htmlproofer passes when the local environment supports the + repository's documented commands. +- `docs/newsletter-workflow.md` documents generation, editorial review, deterministic + regeneration, expected output, and troubleshooting. +- The final diff contains no `_site` files, conference-data edits, credentials, + provider configuration, CI/deployment changes, or dependency changes. + +## Out of Scope (Deferred) + +- Mailchimp campaign replication or draft upload; evaluate after one generated issue + has completed editorial review. +- Buttondown integration or Mailchimp migration. +- Sending, scheduling, subscriber management, analytics, or unsubscribe feedback. +- Automated factual research or enrichment beyond `_data/current.yml`. +- Git-history analysis for newly added or materially changed conferences. +- CI-triggered generation. + +## Editorial Reference + +The selection and section rules above follow the demonstrated structure of newsletter +issue 101: three event months beginning with the issue month, followed by every upcoming +discount and every open CFP. The archived issue is available at +. diff --git a/_drafts/2026-11-newsletter.md b/_drafts/2026-11-newsletter.md new file mode 100644 index 00000000..9e042dcd --- /dev/null +++ b/_drafts/2026-11-newsletter.md @@ -0,0 +1,175 @@ +# Software Testing Conferences Newsletter — November 2026–January 2027 + +**Suggested subject:** 10 software testing conferences from November 2026 through January 2027 +**Suggested preheader:** 9 upcoming discounts and 2 open CFPs, plus a three-month conference calendar. + + +## Introduction + +[Write the introduction before sending.] + + +## Sponsor + +[Add sponsor copy or remove this section before sending.] + +## November 2026 + +### [Agile Testing Days 2026]() + +**Location:** Potsdam, Germany and Online +**Dates:** November 16-19, 2026 +**Status:** [Registration is Open]() + +### [QA Leadership Summit - Winter 2026 Edition]() + +**Location:** Online +**Dates:** November 18, 2026 +**Status:** Registration is Open + +### [Software Quality Summit Columbus 2026]() + +**Location:** Columbus, OH, USA +**Dates:** November 19, 2026 +**Status:** [Registration is Open]() + +### [StackConnect World Tour: Hyderabad 2026]() + +**Location:** Hyderabad, India +**Dates:** November 19, 2026 +**Status:** Registration is Open and Free + +### [Software Quality Summit Manila 2026]() + +**Location:** Manila, Philippines +**Dates:** November 20, 2026 +**Status:** [Registration is Open]() + +### [QA Insurance Forum 2026]() + +**Location:** London, UK +**Dates:** November 25, 2026 +**Status:** [Registration is Open]() | Free for employees of insurance firms + +### [Testing United 2026]() + +**Location:** Copenhagen, Denmark +**Dates:** November 25-26, 2026 +**Status:** [Registration is Open]() + +## December 2026 + +### [StackConnect World Tour: Mumbai]() + +**Location:** Mumbai, India +**Dates:** December 2, 2026 +**Status:** Registration is Open and Free + +### [QonfX Hyderabad 2026]() + +**Location:** Hyderabad, India +**Dates:** December 3, 2026 +**Status:** [Request Your Free Invite]() + +### [TestGuild IRL Santa Clara County 2026]() + +**Location:** Santa Clara County, CA, USA +**Dates:** December 10, 2026 +**Status:** [Registration is Open and Free]() + +## January 2027 + +No conferences or workshops are currently listed for January 2027. + +## Upcoming discounts + +### [Software Quality Summit Austin 2027]() + +**Location:** Austin, TX, USA +**Dates:** March 3, 2027 +**Status:** [Super Early Bird Registration is Open]() until January 3, 2027 + +### [The Living Documentation Event 2027]() + +**Location:** Hilversum, Netherlands +**Dates:** March 5, 2027 +**Status:** [Early Bird Registration is Open]() until December 1, 2026 + +### [RoboCon 2027 Helsinki]() + +**Location:** Helsinki, Finland +**Dates:** March 8-12, 2027 +**Status:** [Blind Bird Registration is Open]() + +### [Testing Peers Conference 2027]() + +**Location:** Nottingham, UK +**Dates:** March 11, 2027 +**Status:** [Early Bird Registration is Open]() + +### [RoboCon 2027 Online]() + +**Location:** Online +**Dates:** April 7-9, 2027 +**Status:** [Blind Bird Registration is Open]() + +### [EuroSTAR 2027 Software Testing Conference]() + +**Location:** Copenhagen, Denmark +**Dates:** May 11-14, 2027 +**Status:** [Super Early Bird Registration is Open]() + +### [Test Coast 2027]() + +**Location:** Gothenburg, Sweden +**Dates:** May 19-20, 2027 +**Status:** [CFP is Open]() | [Early Bird Registration]() until December 31, 2026 + +### [expo:QA 27]() + +**Location:** Madrid, Spain +**Dates:** May 25-27, 2027 +**Status:** [Early Bird Pricing is Open]() + +### [TACON 2027]() + +**Location:** Leipzig, Germany +**Dates:** September 15-16, 2027 +**Status:** [Blind Registration is Open]() + +## Open CFPs + +### [Test Coast 2027]() + +**Location:** Gothenburg, Sweden +**Dates:** May 19-20, 2027 +**Status:** [CFP is Open]() | [Early Bird Registration]() until December 31, 2026 + +### [WeTest.Athens 2027]() + +**Location:** Athens, Greece, Europe +**Dates:** May 25, 2027 +**Status:** [CFP is Open]() until December 15, 2026 + + +## Announcements + +[Add announcements or remove this section before sending.] + + +## Final notes + +[Add final notes before sending.] + +View the latest conference information at [TestingConferences.org](https://testingconferences.org/). + +Know of an event we missed? [Contribute to the community-maintained list](https://github.com/TestingConferences/testingconferences.github.io). + +## Review before sending + +- [ ] Replace or remove every editorial placeholder. +- [ ] Verify conference details, discount availability, CFP status, and deadlines against official sources. +- [ ] Check every link and review the final email on desktop, mobile, and plain text. +- [ ] Resolve or intentionally omit these ambiguous or unparseable conference dates: + - TestGuild IRL Boston 2027 — `2027 TBA` + - TestGuild IRL New York 2027 — `2027 TBA` diff --git a/docs/newsletter-workflow.md b/docs/newsletter-workflow.md new file mode 100644 index 00000000..a94dbde1 --- /dev/null +++ b/docs/newsletter-workflow.md @@ -0,0 +1,117 @@ +--- +published: false +--- + +# Newsletter draft workflow + +The newsletter generator turns `_data/current.yml` into a reviewable Markdown draft. +It does not connect to an email provider, upload a campaign, schedule a message, or +send email. + +## Generate a draft + +Pass the first month of the issue in `YYYY-MM` form: + +```bash +ruby tools/newsletter.rb --month 2026-11 +``` + +The command writes `_drafts/2026-11-newsletter.md`. It does not prompt for input, so +the same command can be repeated during editorial review. + +To inspect output without replacing the default draft, provide another path: + +```bash +ruby tools/newsletter.rb --month 2026-11 --output /tmp/2026-11-newsletter.md +``` + +Explicit output paths are limited to the repository's `_drafts` directory and the +operating system's temporary directories. The destination directory must already +exist. The command rejects an existing symbolic link or a file owned by another user +before replacing anything. + +Generation is deterministic: unchanged conference data and the same target month +produce byte-identical Markdown. Re-running the command replaces the exact output +file, including any manual edits in that file. Make conference-data corrections before +regenerating, or write to a temporary path and merge the changes into an edited draft. + +## What the generator selects + +The issue format follows newsletter #101: + +1. Three conference months beginning with `--month`. Events are selected and grouped + by their start date, then ordered chronologically within each month. +2. Every parseable upcoming event whose status identifies an active discount, including + early-bird, super-early-bird, blind-bird, blind-registration, and similar offers. +3. Every parseable upcoming event whose status explicitly identifies an open CFP, call + for proposals, call for papers, or call for speakers. + +Ordinary registration status appears with an event in the three-month conference +calendar. It does not create a separate all-registration list. + +The generator copies facts and status wording from `_data/current.yml`. It does not +decide whether a listed deadline has passed or whether an organizer's page has changed. +An ambiguous or missing event date is not guessed; the event is named in the draft's +review checklist instead. + +## Review before using the draft + +The generated Markdown is an editorial starting point. Before importing it into an +email provider: + +1. Replace the introduction and final-notes placeholders. +2. Add approved sponsor copy or remove the sponsor section. +3. Add announcements or remove that section. +4. Review the suggested subject and preheader. +5. Resolve or intentionally omit every event named for an ambiguous or missing date. +6. Verify conference dates, locations, registration states, discounts, CFPs, and + deadlines against official event sources. +7. Open every link. +8. Review the final campaign on desktop and mobile and check its plain-text version. +9. Send a provider test message before scheduling or sending the production issue. + +Provider actions remain manual and outside this command. + +## Troubleshooting + +### `Missing required option: --month YYYY-MM` + +Include a target month: + +```bash +ruby tools/newsletter.rb --month 2026-11 +``` + +The month must contain a four-digit year and a two-digit calendar month. Values such +as `2026-1`, `2026-13`, and `November 2026` are rejected. + +### Conference data cannot be read + +Run the repository validator first: + +```bash +ruby tools/validate_data.rb +``` + +Correct YAML syntax and required-field errors in `_data/current.yml`, then generate +the draft again. The generator completes parsing and rendering before replacing the +output file, so invalid input does not partially overwrite an existing draft. + +### A conference is missing from the three-month calendar + +Confirm that its `dates` value has a supported date and that its start month is inside +the three-month window. A cross-month event appears under its start month. Ambiguous +values such as `2027 TBA` appear in the review checklist instead of the calendar. + +### A discount or CFP is missing + +Check the event's `status` in `_data/current.yml`. Discounts need recognizable active +discount language. CFPs need both a CFP/call-for-proposals term and an explicit open +state. Statuses marked closed, ended, expired, or sold out are excluded unless the same +status also describes another supported active offer. + +### A month has no conferences + +This is valid. The generator keeps all three month headings and writes an explicit +no-events message so the editor can decide whether to retain that month in the final +campaign. diff --git a/tasks/plan.md b/tasks/plan.md new file mode 100644 index 00000000..109072fb --- /dev/null +++ b/tasks/plan.md @@ -0,0 +1,121 @@ +--- +published: false +--- + +# Implementation Plan: Newsletter Draft Generator + +Source spec: `SPEC-newsletter-generator.md` + +## Overview + +Build a standard-library Ruby CLI that reads `_data/current.yml` and generates a +deterministic Markdown newsletter draft. The draft follows newsletter issue 101: +three event months beginning with `--month`, then all upcoming active discounts, +then all upcoming open CFPs. The implementation remains provider-neutral and never +uploads, schedules, or sends email. + +## Architecture Decisions + +- Keep V1 in `tools/newsletter.rb`, guarded by + `if $PROGRAM_NAME == __FILE__`, so tests can require its parsing and rendering + functions without executing the CLI. +- Use only Ruby standard-library components already available to the project: + `Date`, `YAML`, `OptionParser`, `CGI`, `FileUtils`, and `Tempfile`. +- Keep newsletter date parsing local rather than refactoring the existing validator. + The formats must match the validator, but changing the validator would expand the + risk and scope of this feature. +- Treat the requested month as the deterministic reference point. Do not use + `Date.today`; this makes historic regeneration byte-identical. +- Represent a parsed event as a small immutable value carrying its source mapping, + start date, and end date. Rendering operates on those values, while unparseable + mappings remain available for the review checklist. +- Convert supported `text` source status fragments to Markdown, + strip other markup, decode HTML entities, and escape Markdown-significant source + text. Never pass arbitrary source HTML into the draft. +- Write through a temporary file in the destination directory and rename it only + after rendering succeeds, so invalid arguments or data cannot partially overwrite + an existing draft. +- Keep the generated current issue (`_drafts/2026-11-newsletter.md`) as an example and + editorial starting point. It remains generated content and must not be mistaken for + a sent campaign. + +## Dependency Graph + +```text +month/date parsing + │ + ├── rolling event-window selection + │ + └── upcoming-event eligibility + │ +status conversion and classification + │ + Markdown rendering + │ + CLI validation and safe write + │ + documentation and real draft + │ + full verification +``` + +## Task List + +Tasks are tracked in `tasks/todo.md`. + +### Phase 1: Selection foundation + +- Task 1: Parse target months and conference date ranges, then select and group the + rolling three-month event window. + +### Phase 2: Newsletter semantics + +- Task 2: Convert source text safely and classify every upcoming active discount and + open CFP while excluding explicitly closed states. +- Task 3: Render the complete deterministic Markdown draft and expose the safe CLI + write path. + +### Checkpoint: Complete generator + +- Focused tests pass after all three behavior slices. +- A temporary-directory CLI run proves deterministic regeneration and safe failures. + +### Phase 3: Editorial workflow + +- Task 4: Document generation and review, then generate the November 2026 draft from + current conference data. + +### Phase 4: Completion audit + +- Task 5: Run repository validation/build gates and audit every spec requirement and + final changed file. + +## Risks and Mitigations + +| Risk | Impact | Mitigation | +|---|---|---| +| Free-form date strings are misinterpreted | High | Accept only formats already supported by the validator; surface every other value for review instead of guessing. | +| Stale status text produces a stale discount or CFP | Medium | Preserve source wording and add an explicit editor verification checklist; never infer deadline state. | +| HTML status fragments break Markdown | Medium | Convert only anchors, strip other tags, decode entities, and test special characters and multiple links. | +| A failed run damages an edited draft | High | Complete parsing/rendering before an atomic same-directory replacement; test that invalid input preserves the prior file. | +| Empty or year-crossing windows produce surprising structure | Medium | Test all three headings, empty-month messages, and November/December/January rollover. | +| The generated draft is treated as send-ready | Medium | Include visible editorial placeholders and a review checklist; documentation states that generation never sends or uploads. | + +## Verification Checkpoints + +1. After Task 1: date and rolling-window tests pass; no rendering or file writing exists. +2. After Tasks 2–3: the entire focused suite passes and an explicit-output CLI run is + byte-identical on regeneration. +3. After Task 4: the documented default command produces the current draft and the + draft visibly follows issue 101's section order. +4. After Task 5: focused tests, validator tests, data validation, Jekyll, htmlproofer, + diff checks, and scope/secret audits all pass. + +## Parallelization + +None. The slices share one small CLI contract and are intentionally sequential. This +avoids merging competing parsers or renderers and keeps every RED/GREEN cycle focused. + +## Open Questions + +None. Newsletter issue 101 resolved the selection and section-order questions. diff --git a/tasks/todo.md b/tasks/todo.md new file mode 100644 index 00000000..05861425 --- /dev/null +++ b/tasks/todo.md @@ -0,0 +1,175 @@ +--- +published: false +--- + +# Newsletter Draft Generator Tasks + +Source spec: `SPEC-newsletter-generator.md` + +Implementation plan: `tasks/plan.md` + +## Task 1: Select the rolling three-month conference window + +**Description:** Add focused tests first, then implement strict target-month parsing, +supported conference date-range parsing, chronological ordering, year rollover, and +month grouping without reading the system clock. + +**Acceptance criteria:** + +- [x] `YYYY-MM` input is required and invalid values fail with useful messages. +- [x] Single-day, same-month, cross-month, abbreviated-month, and reversed day/month + source formats produce correct start and end dates. +- [x] Events whose start dates fall within the rolling three-month window are grouped + by start month and ordered by start date then name. +- [x] Ambiguous or unparseable dates are never guessed and remain available for review. + +**Verification:** + +- [x] RED: `ruby test/newsletter_test.rb` fails for the missing selection behavior. +- [x] GREEN: `ruby test/newsletter_test.rb` passes for selection tests. +- [x] `ruby test/validate_data_test.rb` still passes. + +**Dependencies:** None + +**Files likely touched:** + +- `tools/newsletter.rb` +- `test/newsletter_test.rb` +- `test/fixtures/newsletter/current.yml` + +**Estimated scope:** Medium (3 files) + +## Task 2: Classify discounts and CFPs safely + +**Description:** Add tests first, then convert supported source status HTML to safe +Markdown and select all upcoming active discounts and open CFPs outside the three-month +event window while retaining ordinary registration status only on event entries. + +**Acceptance criteria:** + +- [x] Anchor tags become Markdown links; unsupported HTML becomes readable plain text. +- [x] Markdown-significant source text is escaped without changing URLs. +- [x] Every parseable upcoming event with an active discount status is selected. +- [x] Every parseable upcoming event with an explicitly open CFP is selected. +- [x] Closed, ended, expired, or sold-out discounts and closed CFPs are excluded. +- [x] Ordinary registration alone does not place an event in either global list. + +**Verification:** + +- [x] RED: focused status tests fail before implementation. +- [x] GREEN: `ruby test/newsletter_test.rb` passes after implementation. + +**Dependencies:** Task 1 + +**Files likely touched:** + +- `tools/newsletter.rb` +- `test/newsletter_test.rb` +- `test/fixtures/newsletter/current.yml` + +**Estimated scope:** Medium (3 files) + +## Task 3: Render and write the deterministic draft + +**Description:** Add rendering and command-level tests first, then produce the complete +Markdown format, visible editorial placeholders, review checklist, empty-month output, +CLI options, and atomic destination replacement. + +**Acceptance criteria:** + +- [x] Output follows the approved section order and contains all four editorial areas. +- [x] Three monthly sections always appear, including explicit empty-month messages. +- [x] Suggested subject/preheader and all generated copy are deterministic. +- [x] Unparseable event names appear in the review checklist. +- [x] Default output is `_drafts/YYYY-MM-newsletter.md`; `--output` is supported. +- [x] Repeated generation from unchanged data is byte-identical. +- [x] Invalid input/data exits nonzero without partially overwriting an existing file. + +**Verification:** + +- [x] RED: rendering/CLI tests fail before implementation. +- [x] GREEN: `ruby test/newsletter_test.rb` passes. +- [x] Two explicit-output runs have identical checksums. + +**Dependencies:** Tasks 1–2 + +**Files likely touched:** + +- `tools/newsletter.rb` +- `test/newsletter_test.rb` + +**Estimated scope:** Small (2 files) + +## Checkpoint: Complete generator + +- [x] `ruby test/newsletter_test.rb` passes with no skipped tests. +- [x] `ruby test/validate_data_test.rb` passes. +- [x] Manual CLI checks confirm success and safe failure behavior. +- [x] Tasks 1–3 are committed as reviewable save points. + +## Task 4: Document and generate the editorial draft + +**Description:** Document the local command, expected structure, editor checklist, +regeneration behavior, and troubleshooting, then run the default command for November +2026 and inspect the resulting Markdown against newsletter issue 101. + +**Acceptance criteria:** + +- [x] `docs/newsletter-workflow.md` explains generation, review, regeneration, and + troubleshooting without promising upload or send behavior. +- [x] `_drafts/2026-11-newsletter.md` is generated solely from current repository data. +- [x] The draft contains November 2026, December 2026, and January 2027 sections, + followed by all upcoming discounts and all open CFPs. +- [x] The draft visibly retains placeholders for introduction, sponsor copy, + announcements, and final notes. + +**Verification:** + +- [x] Run `ruby tools/newsletter.rb --month 2026-11`. +- [x] Re-run it and confirm no diff in the generated draft. +- [x] Review the generated section order and checklist manually. + +**Dependencies:** Task 3 + +**Files likely touched:** + +- `docs/newsletter-workflow.md` +- `_drafts/2026-11-newsletter.md` + +**Estimated scope:** Small (2 files) + +## Task 5: Run the completion audit + +**Description:** Run every focused and repository gate, then audit the final diff +against the approved spec and repository safety rules. + +**Acceptance criteria:** + +- [x] Focused tests and existing validator regression tests pass. +- [x] Production conference data validation passes. +- [x] Jekyll and htmlproofer pass when the local environment supports them. +- [x] No `_site`, conference data, credential, provider, navigation, CI, deployment, + versioning, dependency, or unrelated files are included. +- [x] Every success criterion in `SPEC-newsletter-generator.md` has direct evidence. + +**Verification:** + +- [x] `ruby test/newsletter_test.rb` +- [x] `ruby tools/validate_data.rb` +- [x] `ruby test/validate_data_test.rb` +- [x] `bundle exec jekyll build --verbose` +- [x] `bundle exec htmlproofer ./_site --disable-external --no-enforce-https --allow-missing-href --ignore-urls '/^\/\//'` +- [x] `git diff --check` +- [x] Final status/diff and sensitive-filename/content review + +**Dependencies:** Tasks 1–4 + +**Files likely touched:** None beyond task/checklist completion marks + +**Estimated scope:** Extra small (verification only) + +## Checkpoint: Complete + +- [x] All task acceptance criteria and verification items are checked. +- [x] All approved spec success criteria are proven. +- [x] Final changes are ready for maintainer review. diff --git a/test/fixtures/newsletter/current.yml b/test/fixtures/newsletter/current.yml new file mode 100644 index 00000000..3663d5fa --- /dev/null +++ b/test/fixtures/newsletter/current.yml @@ -0,0 +1,88 @@ +- name: December Conference + location: Berlin, Germany + dates: "December 3, 2026" + url: https://example.com/december?utm_source=testingconferences + status: Registration is Open + +- name: Beta November Conference + location: Online + dates: "November 18, 2026" + url: https://example.com/beta?utm_source=testingconferences + status: Registration is Open and Free + +- name: January Conference + location: Paris, France and Online + dates: "January 8-9, 2027" + url: https://example.com/january?utm_source=testingconferences + +- name: Alpha November Conference + location: London, UK + dates: "November 18, 2026" + url: https://example.com/alpha?utm_source=testingconferences + +- name: Cross-Month Conference + location: New York, USA + dates: "November 30 - December 2, 2026" + url: https://example.com/cross-month?utm_source=testingconferences + +- name: February Conference + location: Rome, Italy + dates: "February 1, 2027" + url: https://example.com/february?utm_source=testingconferences + +- name: Date To Be Announced Conference + location: Online + dates: "2027 TBA" + url: https://example.com/tba?utm_source=testingconferences + +- name: Early Bird Conference + location: Hilversum, Netherlands + dates: "March 5, 2027" + url: https://example.com/early-bird?utm_source=testingconferences + status: Early Bird Registration is Open until December 1, 2026 + +- name: Blind Ticket Conference + location: Helsinki, Finland + dates: "April 7-9, 2027" + url: https://example.com/blind-tickets?utm_source=testingconferences + status: Blind Tickets are On Sale + +- name: Blind Registration Conference + location: Leipzig, Germany + dates: "April 10, 2027" + url: https://example.com/blind-registration?utm_source=testingconferences + status: Blind Registration is Open + +- name: Closed Discount Conference + location: Vienna, Austria + dates: "May 4, 2027" + url: https://example.com/closed-discount?utm_source=testingconferences + status: Early Bird Registration is Closed + +- name: Registration Only Conference + location: Madrid, Spain + dates: "June 2, 2027" + url: https://example.com/registration?utm_source=testingconferences + status: Registration is Open + +- name: Open CFP Conference + location: Paris, France + dates: "July 8, 2027" + url: https://example.com/open-cfp?utm_source=testingconferences + status: CFP is Open until January 15, 2027 + +- name: Alternate Open Call for Papers Conference + location: Athens, Greece + dates: "August 11, 2027" + url: https://example.com/open-papers?utm_source=testingconferences + status: Call for Papers is Open + +- name: Closed CFP Conference + location: Oslo, Norway + dates: "September 9, 2027" + url: https://example.com/closed-cfp?utm_source=testingconferences + status: CFP is Closed + +- name: Missing Date Conference + location: Online + url: https://example.com/missing-date?utm_source=testingconferences diff --git a/test/newsletter_test.rb b/test/newsletter_test.rb new file mode 100644 index 00000000..ab0516c8 --- /dev/null +++ b/test/newsletter_test.rb @@ -0,0 +1,466 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require 'date' +require 'minitest/autorun' +require 'stringio' +require 'tmpdir' +require_relative '../tools/newsletter' + +class NewsletterTest < Minitest::Test + FIXTURE = File.expand_path('fixtures/newsletter/current.yml', __dir__) + + def test_target_month_requires_exact_year_month_format + error = assert_raises(Newsletter::InputError) do + Newsletter.parse_target_month('2026-1') + end + + assert_equal 'Month must use YYYY-MM format: 2026-1', error.message + end + + def test_target_month_rejects_an_invalid_calendar_month + error = assert_raises(Newsletter::InputError) do + Newsletter.parse_target_month('2026-13') + end + + assert_equal 'Month is not valid: 2026-13', error.message + end + + def test_target_month_returns_the_first_day + assert_equal Date.new(2026, 11, 1), Newsletter.parse_target_month('2026-11') + end + + def test_parses_supported_event_date_formats + cases = { + 'November 18, 2026' => [Date.new(2026, 11, 18), Date.new(2026, 11, 18)], + 'November 4-6, 2026' => [Date.new(2026, 11, 4), Date.new(2026, 11, 6)], + 'November 30 - December 2, 2026' => [Date.new(2026, 11, 30), Date.new(2026, 12, 2)], + 'March 4-5 March, 2027' => [Date.new(2027, 3, 4), Date.new(2027, 3, 5)], + 'Sept 8-9, 2027' => [Date.new(2027, 9, 8), Date.new(2027, 9, 9)] + } + + cases.each do |source, expected| + range = Newsletter.parse_date_range(source) + + refute_nil range, "expected #{source.inspect} to parse" + assert_equal expected[0], range.start_date, source + assert_equal expected[1], range.end_date, source + end + end + + def test_unparseable_or_ambiguous_dates_are_not_guessed + assert_nil Newsletter.parse_date_range('2027 TBA') + assert_nil Newsletter.parse_date_range('Sometime next spring') + assert_nil Newsletter.parse_date_range(nil) + end + + def test_rejects_reversed_ranges_and_only_rolls_over_at_a_clear_year_boundary + assert_nil Newsletter.parse_date_range('November 19-16, 2026') + assert_nil Newsletter.parse_date_range('November 30 - October 2, 2026') + assert_nil Newsletter.parse_date_range('December 30 - February 2, 2027') + + range = Newsletter.parse_date_range('December 30 - January 2, 2027') + + refute_nil range + assert_equal Date.new(2026, 12, 30), range.start_date + assert_equal Date.new(2027, 1, 2), range.end_date + end + + def test_catalog_keeps_unparseable_events_for_editorial_review + catalog = Newsletter.load_catalog(FIXTURE) + + assert_equal 14, catalog.events.length + assert_equal [ + 'Date To Be Announced Conference', + 'Missing Date Conference' + ], catalog.unparseable.map(&:name) + end + + def test_three_month_window_crosses_year_and_orders_events + catalog = Newsletter.load_catalog(FIXTURE) + target_month = Newsletter.parse_target_month('2026-11') + + groups = Newsletter.group_for_window(catalog.events, target_month) + + assert_equal [Date.new(2026, 11, 1), Date.new(2026, 12, 1), Date.new(2027, 1, 1)], groups.keys + assert_equal [ + 'Alpha November Conference', + 'Beta November Conference', + 'Cross-Month Conference' + ], groups.fetch(Date.new(2026, 11, 1)).map(&:name) + assert_equal ['December Conference'], groups.fetch(Date.new(2026, 12, 1)).map(&:name) + assert_equal ['January Conference'], groups.fetch(Date.new(2027, 1, 1)).map(&:name) + end + + def test_cross_month_event_is_grouped_under_its_start_month + catalog = Newsletter.load_catalog(FIXTURE) + groups = Newsletter.group_for_window(catalog.events, Date.new(2026, 12, 1)) + + refute_includes groups.fetch(Date.new(2026, 12, 1)).map(&:name), 'Cross-Month Conference' + end + + def test_converts_supported_status_html_to_safe_markdown + source = <<~HTML.strip + Early Bird **Registration** & Pricing until December 1, 2026 | Save 20% + HTML + + converted = Newsletter.status_markdown(source) + + assert_equal( + '[Early Bird \*\*Registration\*\* & Pricing]() until December 1, 2026 | Save 20%', + converted + ) + assert_equal 'Review details', Newsletter.status_markdown('Review details') + end + + def test_markdown_links_preserve_parentheses_in_destinations + status = Newsletter.status_markdown( + 'Registration is Open' + ) + event = event_with( + name: 'Parenthesized URL Conference', + url: 'https://example.com/event)preview' + ) + draft = Newsletter.render(Newsletter::Catalog.new(events: [event], unparseable: []), Date.new(2026, 11, 1)) + + assert_equal '[Registration is Open]()', status + assert_includes draft, '### [Parenthesized URL Conference]()' + end + + def test_escapes_markdown_significant_source_text + assert_equal( + 'QA <script>alert(1)</script> & \\[Lab\\] \\*Conference\\* \\#1', + Newsletter.escape_markdown('QA & [Lab] *Conference* #1') + ) + end + + def test_selects_all_upcoming_active_discounts_outside_event_window + catalog = Newsletter.load_catalog(FIXTURE) + + discounts = Newsletter.upcoming_discounts(catalog.events, Date.new(2026, 11, 1)) + + assert_equal [ + 'Early Bird Conference', + 'Blind Ticket Conference', + 'Blind Registration Conference' + ], discounts.map(&:name) + end + + def test_discount_state_is_evaluated_in_the_discount_clause + events = [ + event_with( + name: 'Closed Early Bird', + status: 'Early Bird Registration is Closed | Regular Registration is Open' + ), + event_with( + name: 'Closed Inline Early Bird', + status: 'Early Bird Registration is Closed, regular registration is open' + ), + event_with( + name: 'Closed Reverse Early Bird', + status: 'Regular Registration is Open, Early Bird Registration is Closed' + ), + event_with( + name: 'Open Early Bird', + status: 'Early Bird Registration is Open | CFP is Closed' + ), + event_with( + name: 'Open Early Bird First', + status: 'Early Bird Registration is Open, CFP is Closed' + ), + event_with( + name: 'Open Early Bird Last', + status: 'CFP is Closed, Early Bird Registration is Open' + ), + event_with( + name: 'Open Early Bird After Closed Registration', + status: 'Regular Registration is Closed, Early Bird Registration is Open' + ), + event_with( + name: 'Open Early Bird After Conjunction', + status: 'Early bird registration is open, and the CFP is closed' + ), + event_with( + name: 'Dated Early Bird', + status: 'Early Bird Registration until December 1, 2026' + ) + ] + + discounts = Newsletter.upcoming_discounts(events, Date.new(2026, 11, 1)) + + assert_equal [ + 'Dated Early Bird', + 'Open Early Bird', + 'Open Early Bird After Closed Registration', + 'Open Early Bird After Conjunction', + 'Open Early Bird First', + 'Open Early Bird Last' + ], discounts.map(&:name) + end + + def test_comma_only_splits_when_it_introduces_another_status_subject + events = [ + event_with(name: 'Sold Out Discount', status: 'Early bird discount, sold out'), + event_with( + name: 'Expired Repeated Discount', + status: 'Early bird discount, but the discount has expired' + ), + event_with( + name: 'Expired Repeated Registration', + status: 'Early bird registration is open, but the registration has expired' + ), + event_with( + name: 'Expired Repeated Named Discount', + status: 'Early bird discount is open, but the early bird discount has expired' + ), + event_with( + name: 'Available Registration', + status: 'Early bird registration, available through January 1' + ) + ] + + discounts = Newsletter.upcoming_discounts(events, Date.new(2026, 11, 1)) + + assert_equal ['Available Registration'], discounts.map(&:name) + end + + def test_selects_all_upcoming_open_cfps_outside_event_window + catalog = Newsletter.load_catalog(FIXTURE) + + cfps = Newsletter.open_cfps(catalog.events, Date.new(2026, 11, 1)) + + assert_equal [ + 'Open CFP Conference', + 'Open Call for Papers Conference' + ], cfps.map(&:name) + end + + def test_open_cfp_requires_an_affirmative_state_in_the_cfp_clause + events = [ + event_with(name: 'Closed CFP', status: 'CFP is Closed | Registration is Open'), + event_with(name: 'Closed Reverse CFP', status: 'Registration is Open, CFP is Closed'), + event_with(name: 'Future CFP', status: 'CFP is not open yet'), + event_with(name: 'Open CFP', status: 'CFP is Open | Registration is Closed'), + event_with(name: 'Open CFP First', status: 'CFP is now open, registration is closed'), + event_with(name: 'Open CFP Last', status: 'Registration is closed, CFP is now open'), + event_with(name: 'Open CFP Before Conjunction', status: 'CFP is open, but registration is closed'), + event_with(name: 'Closed Repeated CFP', status: 'CFP is open, but the CFP has closed'), + event_with( + name: 'Closed Repeated Call', + status: 'Call for proposals is open, but the call for proposals has closed' + ), + event_with(name: 'Open Papers', status: 'Registration is Open | Call for Papers is Open'), + event_with(name: 'Colon CFP', status: 'CFP: Open'), + event_with(name: 'Historic Open CFP', status: 'Call for proposals has been open since January 1') + ] + + cfps = Newsletter.open_cfps(events, Date.new(2026, 11, 1)) + + assert_equal [ + 'Colon CFP', + 'Historic Open CFP', + 'Open CFP', + 'Open CFP Before Conjunction', + 'Open CFP First', + 'Open CFP Last', + 'Open Papers' + ], cfps.map(&:name) + end + + def test_ordinary_registration_does_not_enter_global_status_lists + catalog = Newsletter.load_catalog(FIXTURE) + target_month = Date.new(2026, 11, 1) + + discount_names = Newsletter.upcoming_discounts(catalog.events, target_month).map(&:name) + cfp_names = Newsletter.open_cfps(catalog.events, target_month).map(&:name) + + refute_includes discount_names, 'Registration Only Conference' + refute_includes cfp_names, 'Registration Only Conference' + end + + def test_rendered_draft_follows_the_editorial_section_order + catalog = Newsletter.load_catalog(FIXTURE) + draft = Newsletter.render(catalog, Date.new(2026, 11, 1)) + + headings = [ + '## Introduction', + '## Sponsor', + '## November 2026', + '## December 2026', + '## January 2027', + '## Upcoming discounts', + '## Open CFPs', + '## Announcements', + '## Final notes', + '## Review before sending' + ] + + positions = headings.map { |heading| draft.index(heading) } + refute_includes positions, nil + assert_equal positions.sort, positions + assert_includes draft, '**Status:** Registration is Open and Free' + assert_includes draft, '[Early Bird Registration is Open]() until December 1, 2026' + assert_includes draft, '### [Open CFP Conference]()' + refute_includes draft, '### [Registration Only Conference]' + end + + def test_rendered_draft_contains_visible_editorial_placeholders + draft = Newsletter.render(Newsletter.load_catalog(FIXTURE), Date.new(2026, 11, 1)) + + assert_includes draft, '[Write the introduction before sending.]' + assert_includes draft, '[Add sponsor copy or remove this section before sending.]' + assert_includes draft, '[Add announcements or remove this section before sending.]' + assert_includes draft, '[Add final notes before sending.]' + assert_equal 4, draft.scan('', + '## Introduction', + '', + '[Write the introduction before sending.]', + '', + '', + '## Sponsor', + '', + '[Add sponsor copy or remove this section before sending.]', + '' + ] + + groups.each do |month, events| + lines << "## #{month_label(month)}" + lines << '' + if events.empty? + lines << "No conferences or workshops are currently listed for #{month_label(month)}." + lines << '' + else + events.each { |event| lines.concat(event_lines(event)) } + end + end + + lines.concat(collection_lines('Upcoming discounts', discounts, 'No upcoming discounts are currently listed.')) + lines.concat(collection_lines('Open CFPs', cfps, 'No open CFPs are currently listed.')) + lines.concat([ + '', + '## Announcements', + '', + '[Add announcements or remove this section before sending.]', + '', + '', + '## Final notes', + '', + '[Add final notes before sending.]', + '', + 'View the latest conference information at [TestingConferences.org](https://testingconferences.org/).', + '', + 'Know of an event we missed? [Contribute to the community-maintained list](https://github.com/TestingConferences/testingconferences.github.io).', + '', + '## Review before sending', + '', + '- [ ] Replace or remove every editorial placeholder.', + '- [ ] Verify conference details, discount availability, CFP status, and deadlines against official sources.', + '- [ ] Check every link and review the final email on desktop, mobile, and plain text.' + ]) + + if catalog.unparseable.empty? + lines << '- [ ] Confirm there are no newly ambiguous or unparseable conference dates.' + else + lines << '- [ ] Resolve or intentionally omit these ambiguous or unparseable conference dates:' + catalog.unparseable.sort_by { |event| event.name.downcase }.each do |event| + date_description = event.dates.empty? ? 'missing date' : "`#{escape_markdown(event.dates)}`" + lines << " - #{escape_markdown(event.name)} — #{date_description}" + end + end + + "#{lines.join("\n")}\n" + end + + def default_output_path(target_month) + File.join(ROOT, '_drafts', "#{target_month.strftime('%Y-%m')}-newsletter.md") + end + + def run(argv, data_file: DEFAULT_DATA_FILE, stdout: $stdout, stderr: $stderr) + options = parse_options(argv) + raise InputError, 'Missing required option: --month YYYY-MM' if options[:month].to_s.empty? + + target_month = parse_target_month(options[:month]) + catalog = load_catalog(data_file) + output = options[:output] || default_output_path(target_month) + write_draft(output, render(catalog, target_month)) + stdout.puts "Newsletter draft written to #{output}" + 0 + rescue InputError, OptionParser::ParseError => e + stderr.puts e.message + 1 + end + + def upcoming_discounts(events, target_month) + upcoming_events(events, target_month).select do |event| + active_discount?(plain_text(event.status)) + end + end + + def open_cfps(events, target_month) + upcoming_events(events, target_month).select do |event| + status_clauses(plain_text(event.status)).any? { |clause| open_cfp_clause?(clause) } + end + end + + def status_markdown(value) + text = remove_unsafe_elements(value.to_s) + links = [] + + text = text.gsub(%r{]*\bhref=(['"])(.*?)\1[^>]*>(.*?)}mi) do + href = CGI.unescapeHTML(Regexp.last_match(2).to_s) + label = escape_markdown(plain_text(Regexp.last_match(3))) + replacement = markdown_link(label, href) + links << replacement + "NEWSLETTERLINKTOKEN#{links.length - 1}END" + end + + converted = escape_markdown(plain_text(text)) + links.each_with_index do |link, index| + converted = converted.sub("NEWSLETTERLINKTOKEN#{index}END", link) + end + converted + end + + def escape_markdown(value) + text = CGI.escapeHTML(CGI.unescapeHTML(value.to_s)) + text.gsub(/([\\\[\]*#_`])/) { |character| "\\#{character}" } + end + + def markdown_link(label, url) + return label unless http_url?(url) + + destination = url.gsub('<', '%3C').gsub('>', '%3E') + "[#{label}](<#{destination}>)" + end + private_class_method :markdown_link + + def validate_source!(source, index) + raise InputError, "Conference data entry #{index + 1} must be a mapping" unless source.is_a?(Hash) + + %w[name location url].each do |field| + next unless source[field].to_s.strip.empty? + + raise InputError, "Conference data entry #{index + 1} is missing #{field}" + end + return if http_url?(source['url'].to_s) + + raise InputError, "Conference data entry #{index + 1} has an invalid URL" + end + private_class_method :validate_source! + + def parse_options(argv) + options = {} + arguments = argv.dup + parser = OptionParser.new do |opts| + opts.banner = 'Usage: ruby tools/newsletter.rb --month YYYY-MM [--output PATH]' + opts.on('--month YYYY-MM', 'First month in the three-month conference window') { |value| options[:month] = value } + opts.on('--output PATH', 'Write the Markdown draft to PATH') { |value| options[:output] = value } + end + parser.parse!(arguments) + raise OptionParser::InvalidArgument, "Unexpected arguments: #{arguments.join(' ')}" unless arguments.empty? + + options + end + private_class_method :parse_options + + def write_draft(path, content) + destination = resolve_output_path(path) + directory = File.dirname(destination) + temporary = Tempfile.new(['newsletter', '.tmp'], directory) + temporary.binmode + temporary.write(content) + temporary.flush + temporary.fsync + temporary.close + File.rename(temporary.path, destination) + rescue SystemCallError => e + raise InputError, "Could not write newsletter draft: #{e.message}" + ensure + temporary&.close! + end + private_class_method :write_draft + + def resolve_output_path(path) + expanded = File.expand_path(path) + directory = File.realpath(File.dirname(expanded)) + destination = File.join(directory, File.basename(expanded)) + roots = allowed_output_roots + + unless roots.any? { |root| destination.start_with?("#{root}#{File::SEPARATOR}") } + raise InputError, "Output path must be inside #{roots.join(' or ')}" + end + + validate_output_owner!(destination, directory) + destination + rescue Errno::ENOENT + raise InputError, "Output directory does not exist: #{File.dirname(expanded)}" + end + private_class_method :resolve_output_path + + def allowed_output_roots + [ + File.realpath(File.join(ROOT, '_drafts')), + File.realpath(Dir.tmpdir), + File.realpath('/tmp') + ].uniq + end + private_class_method :allowed_output_roots + + def validate_output_owner!(destination, directory) + if File.exist?(destination) || File.symlink?(destination) + file_stat = File.lstat(destination) + raise InputError, "Output path must not be a symlink: #{destination}" if file_stat.symlink? + raise InputError, "Output path must be a regular file: #{destination}" unless file_stat.file? + raise InputError, "Output file is not owned by the current user: #{destination}" unless file_stat.uid == Process.uid + end + + directory_stat = File.stat(directory) + return if directory_stat.uid == Process.uid + temporary_roots = [File.realpath(Dir.tmpdir), File.realpath('/tmp')].uniq + return if temporary_roots.include?(directory) && directory_stat.world_writable? && directory_stat.sticky? + + raise InputError, "Output directory is not owned by the current user: #{directory}" + end + private_class_method :validate_output_owner! + + def event_lines(event) + name = escape_markdown(event.name) + heading = "### #{markdown_link(name, event.url)}" + lines = [ + heading, + '', + "**Location:** #{escape_markdown(event.location)}", + "**Dates:** #{escape_markdown(event.dates)}" + ] + status = status_markdown(event.status) + lines << "**Status:** #{status}" unless status.empty? + lines << '' + lines + end + private_class_method :event_lines + + def collection_lines(heading, events, empty_message) + lines = ["## #{heading}", ''] + if events.empty? + lines.concat([empty_message, '']) + else + events.each { |event| lines.concat(event_lines(event)) } + end + lines + end + private_class_method :collection_lines + + def month_label(month) + month.strftime('%B %Y') + end + private_class_method :month_label + + def pluralize(count, singular) + count == 1 ? singular : "#{singular}s" + end + private_class_method :pluralize + + def upcoming_events(events, target_month) + events.select { |event| event.end_date >= target_month } + .sort_by { |event| [event.start_date, event.name.downcase, event.name] } + end + private_class_method :upcoming_events + + def active_discount?(status) + status_clauses(status).any? do |clause| + next false unless clause.match?(DISCOUNT_PATTERN) + next false if inactive_clause?(clause) + + clause.match?(ACTIVE_DISCOUNT_PATTERN) || clause.match?(/\bdiscounts?\b/i) + end + end + private_class_method :active_discount? + + def open_cfp_clause?(clause) + return false unless clause.match?(CFP_PATTERN) + return false if inactive_clause?(clause) + + subject = CFP_PATTERN.source + clause.match?(/(?:#{subject})(?:\s+submissions?)?\s*:?\s*(?:(?:is|are|remains?|has\s+been|now|currently)\s+){0,3}open\b/i) || + clause.match?(/\bopen\s+(?:#{subject})/i) + end + private_class_method :open_cfp_clause? + + def inactive_clause?(clause) + clause.match?(INACTIVE_PATTERN) || clause.match?(NEGATED_ACTIVE_PATTERN) + end + private_class_method :inactive_clause? + + def status_clauses(status) + status.split(STATUS_SEPARATOR_PATTERN).reject(&:empty?).each_with_object([]) do |clause, clauses| + if clauses.last && same_status_subject?(clauses.last, clause) + clauses[-1] = "#{clauses.last}, #{clause}" + else + clauses << clause + end + end + end + private_class_method :status_clauses + + def same_status_subject?(previous_clause, clause) + previous_subject = status_subject(previous_clause) + subject = status_subject(clause) + return false unless previous_subject && subject + return true if previous_subject == subject + return false unless clause.match?(STATUS_REFERENCE_PATTERN) + + return DISCOUNT_OFFER_SUBJECTS.include?(previous_subject) if subject == :discount + return REGISTRATION_OFFER_SUBJECTS.include?(previous_subject) if subject == :registration + + false + end + private_class_method :same_status_subject? + + def status_subject(clause) + case clause + when CFP_PATTERN + :cfp + when /\bsuper\s+early[ -]?bird\b/i + :super_early_bird + when /\bearly[ -]?bird\b/i + :early_bird + when /\bblind[ -]?bird\b|\bblind\s+(?:tickets?|registration|pricing)\b/i + :blind_bird + when /\bregular\s+(?:registration|tickets?|pricing)\b/i + :regular_registration + when /\b(?:registration|tickets?|pricing)\b/i + :registration + when /\bdiscounts?\b|\bsavings?\b|\breduced\s+pric(?:e|ing)\b/i + :discount + end + end + private_class_method :status_subject + + def plain_text(value) + CGI.unescapeHTML(remove_unsafe_elements(value.to_s).gsub(%r{<[^>]+>}m, ' ')) + .gsub(/\s+/, ' ') + .strip + end + private_class_method :plain_text + + def remove_unsafe_elements(value) + value.gsub(%r{<(script|style)\b[^>]*>.*?}mi, '') + end + private_class_method :remove_unsafe_elements + + def http_url?(value) + uri = URI.parse(value) + uri.is_a?(URI::HTTP) && !uri.host.to_s.empty? + rescue URI::InvalidURIError + false + end + private_class_method :http_url? + + def date_components(text) + case text + when /\A(#{MONTH_PATTERN})\s+(\d{1,2})\s*-\s*(#{MONTH_PATTERN})\s*(\d{1,2}),?\s*(\d{4})\z/i + [month_number(Regexp.last_match(1)), Regexp.last_match(2).to_i, + month_number(Regexp.last_match(3)), Regexp.last_match(4).to_i, + Regexp.last_match(5).to_i] + when /\A(#{MONTH_PATTERN})\s+(\d{1,2})\s*-\s*(\d{1,2}),?\s*(\d{4})\z/i + month = month_number(Regexp.last_match(1)) + [month, Regexp.last_match(2).to_i, month, Regexp.last_match(3).to_i, + Regexp.last_match(4).to_i] + when /\A(#{MONTH_PATTERN})\s+(\d{1,2})\s*-\s*(\d{1,2})\s+(#{MONTH_PATTERN}),?\s*(\d{4})\z/i + [month_number(Regexp.last_match(1)), Regexp.last_match(2).to_i, + month_number(Regexp.last_match(4)), Regexp.last_match(3).to_i, + Regexp.last_match(5).to_i] + when /\A(#{MONTH_PATTERN})\s+(\d{1,2}),?\s*(\d{4})\z/i + month = month_number(Regexp.last_match(1)) + [month, Regexp.last_match(2).to_i, month, Regexp.last_match(2).to_i, + Regexp.last_match(3).to_i] + end + end + private_class_method :date_components + + def month_number(name) + normalized = MONTH_NAMES.fetch(name.downcase, name.capitalize) + Date::MONTHNAMES.index(normalized) + end + private_class_method :month_number +end + +exit Newsletter.run(ARGV) if $PROGRAM_NAME == __FILE__