Merge remote-tracking branch 'origin/staging' into develop

This commit is contained in:
Andrey Antukh 2026-11-24 13:12:08 +01:00
commit 4427b83ae0
16 changed files with 908 additions and 120 deletions

View File

@ -481,7 +481,7 @@ JSON, REPL access, and so on.
| [`review-plan`](skills/review-plan/SKILL.md) | Evaluates a plan before anyone writes code: completeness, ordering, risks. Approves it or asks for changes. | "review this plan before we start" |
| [`implement-plan`](skills/implement-plan/SKILL.md) | Shows you the full flow first — the issue and branch it will create (or the branch it continues on), the execution style, and the task checklist — and, after your go-ahead, executes a ready plan. Default: every task, one commit. On request ("step by step"): one task, one commit, your confirmation between tasks. On request ("direct"): no issue and no branch, commits on the current branch. | "implement the plan" · "step by step, one commit per task" · "direct, no branch" |
| [`review-code`](skills/review-code/SKILL.md) | Reviews a diff, branch, or PR and returns findings ranked by impact. | "review my changes before I push" |
| [`create-pr`](skills/create-pr/SKILL.md) | Opens a pull request for the current branch — with checks on base branch, commits, issue, and push state — or updates an existing PR's title and description. | "open a PR for this branch" |
| [`create-pr`](skills/create-pr/SKILL.md) | Opens a pull request for the current branch with `scripts/gh.py create-pr` (base autodetection, optional issue link) or updates an existing PR's title and description. | "open a PR for this branch" |
| [`resolve-git-conflicts`](skills/resolve-git-conflicts/SKILL.md) | Untangles merge or rebase conflicts: explains both sides, proposes a resolution, applies it after you approve. Never runs `git rebase --continue`. | "resolve these conflicts" |
### References

View File

@ -1,108 +1,66 @@
---
name: create-pr
description: PR flow — open a new PR for the current task branch (validates base branch, commits, issue and push state) or update an existing PR's title or description to match Penpot conventions. Use it when the user asks to open or create a PR, in any phrasing.
description: PR flow — open a new PR for the current task branch or update an existing PR's title or description to match Penpot conventions. Use it when the user asks to open or create a PR, in any phrasing.
---
# Create PR
# Skill: create-pr
Two modes. **Open mode** takes the current task branch to a new, validated
PR. **Update mode** rewrites an existing PR's title or description. Gather
information, validate, and act in one pass. If validation fails, STOP with a
single coherent message that lists every problem and states exactly what
information is missing — never fix or work around problems silently.
Entry point for all GitHub PR work. Authentication, base-branch detection,
push state and the existing-PR check are handled by `python3 scripts/gh.py
create-pr` and by `gh` itself — do not perform them here. The canonical rules
for titles, bodies, merge strategy and issue linking live in
`mem:workflow/creating-prs` (file:
`.serena/memories/workflow/creating-prs.md`). This skill routes to the right
flow.
Both modes require an authenticated `gh` CLI (`gh auth status`) and never
push — the user pushes from their own shell.
## When to Use
## When to use
- The user asks to open or create a NEW PR for the current task branch, in
any phrasing ("open a PR", "create the pull request", "put this up for
review") — or invokes `@create-pr`. → **Open mode**.
- The user asks to fix or update an EXISTING PR's title or description to
match conventions. → **Update mode**.
- **Open mode** — the user asks to open or create a NEW PR for the current
task branch, in any phrasing ("open a PR", "create the pull request",
"put this up for review") — or invokes `@create-pr`.
→ **Open mode** below.
- **Update mode** — the user asks to fix or update an existing PR's title or
description. → **Update mode** below.
If the running agent cannot write (for example, the plan agent), say so and
stop — this skill needs the build agent.
The user pushes from their own shell. Never push, force-push or modify a
remote. If the command reports that the branch was not pushed, tell the user
to push it and invoke the skill again.
For draft PRs, warn that CI does not run on them and only add `--draft` when
the user agrees.
## Open mode
### 1. Gather context (read-only)
- Current branch: `git rev-parse --abbrev-ref HEAD`.
- Target base branch: run `./scripts/detect-target-branch` from the repo root.
It prints the nearest ancestor branch of HEAD (exit 0) or fails (exit 1).
- Commits: `git log --oneline <base>..HEAD`.
- Push state (local): `git rev-parse --verify origin/<branch>` and compare
with HEAD. It reads the local remote-tracking ref — no network, no SSH. It
reflects the last push or fetch this clone knows about.
- Issue: from the session context, or from the branch name — `issue-NNNN`
maps to issue NNNN; recover its title and body with `gh issue view NNNN`.
### 2. Validate — stop with one message if anything fails
Run all checks before reporting, then report every failure together:
1. **Base branch not usable.** If the script fails (exit 1), or its output —
after stripping an optional `remotes/origin/` prefix — is not one of the
canonical branches (`develop`, `staging`, `main`), stop and ask the user
to re-run with more context — for example, passing the base branch
explicitly in their invocation. An explicit base given by the user
overrides the script's output.
2. **On a base branch.** There is no task branch to merge — say so and stop.
3. **No commits.** The branch has no commits ahead of the base — say so and
stop.
4. **No clear issue.** There is no issue in the session context, and the
branch name has no `issue-NNNN` pattern (or `gh issue view` finds nothing)
— say so and stop. Exception: the user's invocation says `no issue` /
`without issue` — then continue without an issue reference.
5. **Branch not pushed.** The remote-tracking ref `origin/<branch>` is
missing, or `git rev-parse origin/<branch>` differs from HEAD — the
branch was never pushed, or has commits the remote does not have. Never
push yourself; ask the user to push and to invoke `@create-pr` again
afterwards, then stop.
### 3. Already-open PR
Check whether a PR already exists for this branch (`gh pr list --head
<branch>`). If one exists, report its URL and stop — do not create a second
one. Title or description fixes belong to Update mode.
### 4. Write and create the PR
Write the title and body following `mem:workflow/creating-prs` (title format,
description structure, writing principles) and `mem:workflow/creating-commits`
(commit type emojis). Derive the title and body from the commits and, when
there is one, from the issue body. Include `Closes #NNNN` for readable context,
but do not treat it as the link; use `python3 scripts/gh.py link-issue <ISSUE_NUMBER> <PR_NUMBER>` after creating the PR.
Repeat the `AI-assisted-by:` trailer in the body, once per model that worked
on the branch, so the PR states the assistance where a reviewer reads it. The
branch commits keep their own trailers, and a squash merge carries every one
of them into the landed message.
Before offering or accepting a draft PR, warn that CI doesn't run on them. Add
`--draft` only when the user agrees to that.
1. Write the title and the body following `mem:workflow/creating-prs`:
`:emoji:` title, the `**Note:**` line, and the `## What` / `## Why` /
`## How` sections. Derive them from the commits and the issue body when
there is one. Repeat the `AI-assisted-by:` trailer once per model that
worked on the branch. Put the body in a temp file to avoid shell quoting.
2. Decide whether the PR resolves an issue. If it does, include `Closes
#NNNN` in the body for human readers and pass `--issue NNNN` so the
command creates the GitHub link. If the user's invocation says `no issue`
/ `without issue`, pass no `--issue`.
3. Run the command:
```bash
gh pr create --repo penpot/penpot --base "<BASE>" --title "<TITLE>" \
--project "Main" --body-file /tmp/pr-body.md
python3 scripts/gh.py create-pr \
--title "<TITLE>" --body-file /tmp/pr-body.md [--issue NNNN] [--base BASE]
```
`--base` is the branch resolved in step 1: without it the PR opens against the
repository default, which is wrong for a branch cut from `staging`. `--project
"Main"` is required by `mem:workflow/creating-prs`.
`--base` is optional: by default the command detects the nearest ancestor
branch of `HEAD`, ported from `scripts/detect-target-branch`. Pass it only
when the detected base is not the one you want. `--head` defaults to the
current branch and `--draft` marks the PR as draft.
If an issue is present, run the explicit assignment command from
`mem:workflow/creating-prs` before reporting success:
If the command fails with `detected base '<name>' is not a local branch; pass
--base explicitly`, rerun it with `--base <name>` using the name from the
error. Do not ask the user and do not add pre-flight checks for this case.
```bash
python3 scripts/gh.py link-issue <ISSUE_NUMBER> <PR_NUMBER>
```
### 5. Report
Report the PR URL and stop.
4. Report the URL from the command's output and stop. If it fails, report
the `gh` error as-is; do not add local pre-flight checks.
## Update mode
@ -127,7 +85,7 @@ python3 scripts/gh.py link-issue <ISSUE_NUMBER> <PR_NUMBER>
## User context
Extra context in the user's invocation (the message that triggered this skill)
plays the role command arguments play elsewhere: overrides such as `no issue` /
`without issue`, an explicit base branch (`from origin/staging`), a PR number
for Update mode, and so on.
Extra context in the user's invocation (the message that triggered this
skill) plays the role command arguments play elsewhere: overrides such as
`no issue` / `without issue`, an explicit base branch (`from origin/staging`),
a PR number for Update mode, and so on.

View File

@ -41,7 +41,8 @@ This is a monorepo. Principles that apply to one module do *not* generally apply
- `scripts/nrepl-eval.mjs` — Evaluate Clojure/ClojureScript code via nREPL. Supports `--backend` (port 6064) and `--frontend` (port 3447) aliases. See `mem:scripts/nrepl-eval`.
- `scripts/psql` — PostgreSQL client wrapper with devenv defaults. Companion: `scripts/db-schema` for DDL dumps. See `mem:scripts/psql`.
- `scripts/gh.py` — GitHub operations helper: list milestone issues, fetch PR details, compare against CHANGES.md, create issues with their Issue Type in one command. Requires `gh` CLI. See `mem:scripts/gh`.
- `scripts/gh.py` — GitHub operations helper: list milestone issues, fetch PR details, compare against CHANGES.md, create issues with their Issue Type, and create PRs with optional issue linking. Requires `gh` CLI. See `mem:scripts/gh`.
- `scripts/coverage-summary.mjs` and `scripts/coverage-comment.mjs` — Write test coverage summaries and update the coverage PR comment. See `mem:scripts/coverage-reporting`.
- Before changing coverage summaries or PR comments, read `mem:scripts/coverage-reporting` for metrics, concurrent comment updates, and fork permissions.
- `scripts/project-anomalies.py` — Main-board anomaly check for a milestone (`check` writes `tmp/<MILESTONE>-ANOMALIES.md`). Bulk resolution via `scripts/gh.py`. See `mem:scripts/project-anomalies`.
- Changelog release and audit workflow: `mem:workflow/updating-changelog`.

View File

@ -4,5 +4,6 @@ Use authenticated `gh` with `python3 scripts/gh.py <subcommand> --help` for curr
- `issues` lists issues by milestone (exact title) or with no milestone; milestone queries default to closed issues. `issue` and `comments` fetch issue details and comments. `prs` fetches specific PRs or lists a milestone (merged only by default); request all states when auditing unmerged PRs.
- `create-issue` creates the issue and then sets its Issue Type; this is not atomic. For authorization, metadata, and recovery after a partial creation, read `mem:workflow/creating-issues`. `link-issue` sets the Development association, not the PR body; follow `mem:workflow/creating-prs`. The helper trusts the successful mutation because GitHub's link readback can omit mutation-created links.
- `create-pr` creates a pull request and can optionally link an issue through the Development association. It detects the default base from branch ancestry; pass `--base` to override it. A link failure leaves the PR in place. Follow `mem:workflow/creating-prs`.
- `advisories` lists or inspects repo advisories. Patched-version matching compares exact tokens, not prefixes, and does not require publication. The endpoint uses cursor pagination: use `gh api --paginate --slurp`, not numeric pages, which can repeat the same data.
- `issues --compare` can mistake a same-numbered Taiga reference or prose token for a GitHub issue. Use the changelog-specific reconciliation in `mem:workflow/updating-changelog` when reference targets matter.

View File

@ -10,13 +10,15 @@ PR only on explicit request.
## Target Branch
Auto-detect the base branch with `scripts/detect-target-branch`:
```bash
TARGET=$(scripts/detect-target-branch)
```
This outputs `staging` or `develop` by walking the local commit graph (pure local, no remote/network). Do not ask the user for the target branch unless the tool fails.
The `create-pr` shortcut detects the base branch automatically: it ports the
heuristic of `scripts/detect-target-branch` into `detect_target_branch()` in
`scripts/gh.py` (local commit graph, no remote/network), usually yielding
`staging` or `develop`. Do not ask the user for the target branch unless the
command fails. Pass `--base` only when the detected branch is not the one
wanted; explicit user context overrides the detection. If detection fails
with `detected base '<name>' is not a local branch; pass --base explicitly`,
rerun with `--base <name>` using the name from the error; do not ask the
user and do not add pre-flight checks for this case.
## Metadata
@ -107,20 +109,22 @@ When the PR requests a regular merge instead of a squash merge, its
## Creating the PR
Write the body to a temp file and run the shortcut. It detects the base, runs
`gh pr create` with `--project Main`, parses the PR number and, with
`--issue N`, creates the explicit issue link (see `mem:scripts/gh`):
```bash
cat > /tmp/pr-body.md << 'PR_BODY'
<body content here>
PR_BODY
TARGET=$(scripts/detect-target-branch)
gh pr create \
--repo penpot/penpot \
--base "$TARGET" \
--head <branch> \
--title "<title>" \
--project "Main" \
--body-file /tmp/pr-body.md
python3 scripts/gh.py create-pr \
--title "<title>" --body-file /tmp/pr-body.md \
[--issue NNNN] [--base <branch>] [--project <project>]
rm -f /tmp/pr-body.md
```
Do not pre-check authentication, push state or an existing PR: the command
and `gh` report those errors. Never push yourself; ask the user if the
command reports that the branch was not pushed.

View File

@ -135,6 +135,12 @@ If you upgrade blindly: on fresh databases and small instances the startup migra
- Fix workspace memory growing on every page switch with the WebGL renderer [#13028](https://github.com/penpot/penpot/issues/13028) (PR: [#12877](https://github.com/penpot/penpot/pull/12877))
- Fix workspace showing React error #310 when the team container renders without a team id (by @filipsajdak) [#12728](https://github.com/penpot/penpot/issues/12728) (PR: [#12920](https://github.com/penpot/penpot/pull/12920))
## 2.19.5
### :bug: Bugs fixed
- Revert [#13165](https://github.com/penpot/penpot/issues/13165), because it causes more regression, the issue is already correctly fixed on the upcoming 2.20.0
## 2.19.4
### :bug: Bugs fixed

View File

@ -125,8 +125,8 @@
[frontend-tests.plugins.wait-for-save-test]
[frontend-tests.render-dimensions-test]
[frontend-tests.render-wasm.call-test]
[frontend-tests.render-wasm.modifiers-test]
[frontend-tests.render-wasm.fonts-test]
[frontend-tests.render-wasm.modifiers-test]
[frontend-tests.render-wasm.process-objects-test]
[frontend-tests.render-wasm.serialization-test]
[frontend-tests.render-wasm.shape-proxy-test]

View File

@ -1796,6 +1796,11 @@ impl Shape {
}
}
/// Whether flex layout places this shape: neither absolute nor hidden.
pub fn is_in_flow(&self) -> bool {
!self.is_absolute() && !self.hidden()
}
pub fn z_index(&self) -> i32 {
match &self.layout_item {
Some(LayoutItem {

View File

@ -1039,4 +1039,229 @@ mod tests {
assert!(is_close_to(bounds.min_x(), 0.0));
}
#[derive(Clone, Copy)]
enum TestLayout {
None,
Flex,
Grid,
}
#[derive(Clone, Copy, PartialEq)]
enum Child {
InFlow,
Absolute,
Hidden,
}
/// Adds a shape with no gaps or padding: auto-sized at the root, fixed below.
fn add_shape(
state: &mut State,
parent: Option<Uuid>,
(left, top, right, bottom): (f32, f32, f32, f32),
layout: TestLayout,
) -> Uuid {
let id = Uuid::new_v4();
let sizing = if parent.is_some() {
Sizing::Fix
} else {
Sizing::Auto
};
let shape = state.shapes.add_shape(id);
if !matches!(layout, TestLayout::None) {
shape.set_shape_type(Type::Frame(Frame::default()));
}
let (align, justify) = (AlignItems::Start, JustifyContent::Start);
let (content, items) = (AlignContent::Start, JustifyItems::Start);
match layout {
TestLayout::Flex => shape.set_flex_layout_data(
FlexDirection::Row,
0.0,
0.0,
align,
content,
items,
justify,
WrapType::NoWrap,
0.0,
0.0,
0.0,
0.0,
),
TestLayout::Grid => shape.set_grid_layout_data(
GridDirection::Row,
0.0,
0.0,
align,
content,
items,
justify,
0.0,
0.0,
0.0,
0.0,
),
TestLayout::None => {}
}
shape.set_selrect(left, top, right, bottom);
shape.set_flex_layout_child_data(
0.0, 0.0, 0.0, 0.0, sizing, sizing, None, None, None, None, None, false, None,
);
if let Some(parent) = parent {
shape.set_parent(parent);
state.shapes.get_mut(&parent).unwrap().add_child(id);
}
id
}
fn shape_mut(state: &mut State, id: Uuid) -> &mut Shape {
state.shapes.get_mut(&id).unwrap()
}
fn set_absolute(state: &mut State, id: Uuid) {
shape_mut(state, id)
.layout_item
.as_mut()
.unwrap()
.is_absolute = true;
}
fn rotate(state: &mut State, id: Uuid, degrees: f32) {
let (sin, cos) = degrees.to_radians().sin_cos();
let shape = shape_mut(state, id);
shape.set_rotation(degrees);
shape.set_transform(cos, sin, -sin, cos, 0.0, 0.0);
}
/// Reflows every layout above `id`, as a committed text resize does.
fn reflow(state: &State, id: Uuid) -> Vec<TransformEntry> {
let entry = TransformEntry::from_input(id, Matrix::default());
propagate_modifiers(state, &[entry], PixelPrecision::Disabled).unwrap()
}
fn size_after(state: &State, result: &[TransformEntry], id: Uuid) -> (f32, f32) {
let mut bounds = state.shapes.get_raw(&id).unwrap().bounds();
if let Some(entry) = result.iter().find(|e| e.id == id) {
bounds = bounds.transform(&entry.transform);
}
(bounds.width(), bounds.height())
}
fn assert_size((width, height): (f32, f32), (expected_w, expected_h): (f32, f32)) {
assert!(
is_close_to(width, expected_w) && is_close_to(height, expected_h),
"got {width}x{height}, expected {expected_w}x{expected_h}"
);
}
#[test]
fn test_rotated_shape_under_absolute_child_of_auto_flex_does_not_collapse() {
// Tree from #12763: auto flex > absolute frame > rotated flex row > leaf.
for absolute_layout in [TestLayout::Flex, TestLayout::Grid] {
let mut state = State::new();
state.shapes.initialize(10);
let root = (-1545.0, -72.0, 232.0, 824.0);
let auto = add_shape(&mut state, None, root, TestLayout::Flex);
let frame = (-1399.0, 9.0, 72.75, 763.0);
let absolute = add_shape(&mut state, Some(auto), frame, absolute_layout);
set_absolute(&mut state, absolute);
let row = (-1379.0, 29.0, -1043.0, 83.0);
let row = add_shape(&mut state, Some(absolute), row, TestLayout::Flex);
let leaf = (-1365.0, 47.0, -1335.0, 64.0);
let leaf = add_shape(&mut state, Some(row), leaf, TestLayout::None);
rotate(&mut state, row, 0.0915);
rotate(&mut state, leaf, 0.0915);
let result = reflow(&state, leaf);
for entry in &result {
let (width, height) = size_after(&state, &result, entry.id);
assert!(width > 1.0 && height > 1.0, "{} collapsed", entry.id);
}
}
}
#[test]
fn test_collapsing_a_rotated_frame_is_a_recoverable_error() {
let mut state = State::new();
state.shapes.initialize(10);
let frame = (0.0, 0.0, 300.0, 100.0);
let frame = add_shape(&mut state, None, frame, TestLayout::Flex);
let child = add_shape(
&mut state,
Some(frame),
(10.0, 10.0, 50.0, 50.0),
TestLayout::None,
);
set_absolute(&mut state, child);
rotate(&mut state, frame, 0.0915);
// Squash the frame to zero width: its rotated corners end on one line.
let entry = TransformEntry::from_input(frame, Matrix::scale((0.0, 1.0)));
let result = propagate_modifiers(&state, &[entry], PixelPrecision::Disabled);
assert!(matches!(
result,
Err(crate::error::Error::RecoverableError(_))
));
}
/// Size of an auto-size 500x300 frame with one 100x50 child, after reflow.
/// Grids get two fixed 100px columns and one fixed 50px row.
fn auto_frame_size(layout: TestLayout, child: Child) -> (f32, f32) {
let mut state = State::new();
state.shapes.initialize(10);
let frame = add_shape(&mut state, None, (0.0, 0.0, 500.0, 300.0), layout);
let rect = (10.0, 10.0, 110.0, 60.0);
let child_id = add_shape(&mut state, Some(frame), rect, TestLayout::None);
match child {
Child::Absolute => set_absolute(&mut state, child_id),
Child::Hidden => shape_mut(&mut state, child_id).set_hidden(true),
Child::InFlow => {}
}
if matches!(layout, TestLayout::Grid) {
let column = GridTrack {
track_type: GridTrackType::Fixed,
value: 100.0,
};
let row = GridTrack {
track_type: GridTrackType::Fixed,
value: 50.0,
};
let shape = shape_mut(&mut state, frame);
shape.set_grid_columns(vec![column.clone(), column]);
shape.set_grid_rows(vec![row]);
if child != Child::Absolute {
shape.set_grid_cells(vec![GridCell {
row: 1,
row_span: 1,
column: 1,
column_span: 1,
align_self: None,
justify_self: None,
shape: Some(child_id),
}]);
}
}
let result = reflow(&state, frame);
size_after(&state, &result, frame)
}
#[test]
fn test_auto_flex_size_by_child_kind() {
use Child::*;
assert_size(auto_frame_size(TestLayout::Flex, InFlow), (100.0, 50.0));
assert_size(auto_frame_size(TestLayout::Flex, Absolute), (500.0, 300.0));
// Known difference from CLJS, which sizes the frame to hidden children.
assert_size(auto_frame_size(TestLayout::Flex, Hidden), (500.0, 300.0));
}
#[test]
fn test_auto_grid_size_by_child_kind() {
use Child::*;
assert_size(auto_frame_size(TestLayout::Grid, InFlow), (200.0, 50.0));
assert_size(auto_frame_size(TestLayout::Grid, Absolute), (500.0, 300.0));
// Grid takes its size from its tracks; hidden children still count.
assert_size(auto_frame_size(TestLayout::Grid, Hidden), (200.0, 50.0));
}
}

View File

@ -2,6 +2,7 @@ use std::collections::HashMap;
use crate::math::Bounds;
use crate::shapes::Shape;
use crate::state::ShapesPoolRef;
use crate::uuid::Uuid;
pub trait GetBounds {
@ -13,3 +14,20 @@ impl GetBounds for HashMap<Uuid, Bounds> {
self.get(&shape.id).copied().unwrap_or(shape.bounds())
}
}
/// Whether a flex layout has a child it places (see `Shape::is_in_flow`).
pub fn has_in_flow_children(shape: &Shape, shapes: ShapesPoolRef) -> bool {
shape
.children_ids_iter(true)
.filter_map(|id| shapes.get(id))
.any(Shape::is_in_flow)
}
/// Whether a layout has a child that is not absolute. Hidden children count,
/// as in the CLJS layout.
pub fn has_non_absolute_children(shape: &Shape, shapes: ShapesPoolRef) -> bool {
shape
.children_ids_iter(true)
.filter_map(|id| shapes.get(id))
.any(|child| !child.is_absolute())
}

View File

@ -134,7 +134,7 @@ pub fn propagate_shape_constraints(
parent_transform.post_translate(center);
parent_transform.pre_translate(-center);
let parent_transform_inv = &parent_transform.invert().ok_or(Error::CriticalError(
let parent_transform_inv = &parent_transform.invert().ok_or(Error::RecoverableError(
"Failed to invert parent transform".to_string(),
))?;
let origin = parent_transform_inv.map_point(child_bounds_after.nw);

View File

@ -9,7 +9,7 @@ use crate::uuid::Uuid;
use std::collections::{HashMap, VecDeque};
use super::common::GetBounds;
use super::common::{has_in_flow_children, GetBounds};
const MIN_SIZE: f32 = 0.01;
const MAX_SIZE: f32 = f32::INFINITY;
@ -202,7 +202,7 @@ fn initialize_tracks(
continue;
};
if child.is_absolute() || child.hidden() {
if !child.is_in_flow() {
continue;
}
@ -686,7 +686,11 @@ pub fn reflow_flex_layout(
}
}
if layout_axis.is_auto_across || layout_axis.is_auto_main {
// With nothing to place, keep the size instead of collapsing to padding.
// CLJS would also size to hidden children; flex here leaves them out.
if (layout_axis.is_auto_across || layout_axis.is_auto_main)
&& has_in_flow_children(shape, shapes)
{
let width = layout_bounds.width();
let height = layout_bounds.height();
@ -749,7 +753,7 @@ pub fn reflow_flex_layout(
let parent_transform = layout_bounds.transform_matrix().unwrap_or_default();
let parent_transform_inv = &parent_transform.invert().ok_or(Error::CriticalError(
let parent_transform_inv = &parent_transform.invert().ok_or(Error::RecoverableError(
"Failed to invert parent transform".to_string(),
))?;
let origin = parent_transform_inv.map_point(layout_bounds.nw);

View File

@ -10,7 +10,7 @@ use crate::uuid::Uuid;
use std::collections::{HashMap, HashSet, VecDeque};
use super::common::GetBounds;
use super::common::{has_non_absolute_children, GetBounds};
const MIN_SIZE: f32 = 0.01;
const MAX_SIZE: f32 = f32::INFINITY;
@ -890,7 +890,11 @@ pub fn reflow_grid_layout(
}
}
if shape.is_layout_horizontal_auto() || shape.is_layout_vertical_auto() {
// Like the CLJS layout, skip auto-size when every child is absolute: the
// size comes from the tracks, and hidden children still count.
if (shape.is_layout_horizontal_auto() || shape.is_layout_vertical_auto())
&& has_non_absolute_children(shape, shapes)
{
let width = layout_bounds.width();
let height = layout_bounds.height();
@ -915,7 +919,7 @@ pub fn reflow_grid_layout(
let parent_transform = layout_bounds.transform_matrix().unwrap_or_default();
let parent_transform_inv = &parent_transform.invert().ok_or(Error::CriticalError(
let parent_transform_inv = &parent_transform.invert().ok_or(Error::RecoverableError(
"Failed to invert parent transform".to_string(),
))?;
let origin = parent_transform_inv.map_point(layout_bounds.nw);

View File

@ -7,6 +7,8 @@ set -euo pipefail
#
# Uses git name-rev to find the nearest ref (branch/tag) that is an ancestor of
# HEAD, falling back to a graph walk if name-rev returns the current branch.
# The ref description is normalized to a local branch name and checked
# against the local branches before it is printed.
#
# Pure local — no remote, no SSH, no network. Works even when the current
# branch shares its tip commit with the target (not yet diverged).
@ -17,7 +19,8 @@ set -euo pipefail
#
# Exit status:
# 0 — target found
# 1 — no target found (orphan commit, no other branches)
# 1 — no target found (orphan commit, no other branches), or the detected
# ref is not a local branch (pass --base explicitly)
verbose=false
@ -39,9 +42,30 @@ done
current=$(git rev-parse --abbrev-ref HEAD)
# git name-rev describes refs, not branch names: "remotes/origin/staging~1",
# "develop^2~1" and "tags/v2.0" are all possible outputs.
normalize_ref() {
local name="$1"
name=${name%%[~^]*}
case "$name" in
refs/heads/*) name=${name#refs/heads/} ;;
heads/*) name=${name#heads/} ;;
remotes/*)
name=${name#remotes/}
if [[ "$name" == */* ]]; then
name=${name#*/}
else
name=""
fi
;;
tags/*) name=${name#tags/} ;;
esac
printf '%s' "$name"
}
# Use name-rev to find the nearest ref — it has smart tie-breaking
raw=$(git name-rev --name-only HEAD 2>/dev/null)
target=${raw%%~[0-9]*} # strip ~N distance suffix
raw=$(git name-rev --name-only HEAD 2>/dev/null || true)
target=$(normalize_ref "$raw")
# If name-rev returned the current branch itself, walk backwards
if [ "$target" = "$current" ] || [ -z "$target" ]; then
@ -61,6 +85,16 @@ if [ "$target" = "$current" ] || [ -z "$target" ]; then
fi
fi
target=$(normalize_ref "$target")
if [ -z "$target" ]; then
echo "error: unable to determine target branch" >&2
exit 1
fi
if ! git show-ref --verify --quiet "refs/heads/$target"; then
echo "error: detected base '$target' is not a local branch; pass --base explicitly" >&2
exit 1
fi
if [ "$verbose" = true ]; then
target_commit=$(git rev-parse "$target" 2>/dev/null || true)
if [ -n "$target_commit" ]; then

View File

@ -12,6 +12,7 @@ Subcommands:
advisories List or inspect GitHub security advisories
link-issue Explicitly link a GitHub issue to a pull request
create-issue Create an issue and set its Issue Type in one command
create-pr Create a pull request, optionally linking its issue
Usage:
python3 scripts/gh.py issues <milestone-title> (default: state=closed)
@ -37,6 +38,8 @@ Usage:
python3 scripts/gh.py link-issue 11235 11243
python3 scripts/gh.py create-issue --type task \
--title "Expand backend email tests" --body-file /tmp/issue-body.md
python3 scripts/gh.py create-pr --title "Expand backend email tests" \
--body-file /tmp/pr-body.md --issue 13202 [--base staging]
Prerequisites:
- gh CLI authenticated (gh auth status)
@ -135,6 +138,17 @@ def run_gh_rest(path: str) -> Any:
fail_gh(err.stderr)
def run_git(*args: str) -> str:
"""Run a ``git`` command and return its stripped stdout.
Raises `GhCommandFailed` on failure so callers can degrade gracefully.
"""
result = subprocess.run(["git", *args], capture_output=True, text=True)
if result.returncode != 0:
raise GhCommandFailed(result.stderr)
return result.stdout.strip()
# ─────────────────────────────────────────────
# Subcommand: create-issue
# ─────────────────────────────────────────────
@ -255,6 +269,166 @@ def cmd_create_issue(args: argparse.Namespace) -> None:
print(json.dumps(result, indent=2))
# ─────────────────────────────────────────────
# Subcommand: create-pr
# ─────────────────────────────────────────────
PR_URL_RE = re.compile(r"/pull/(\d+)")
def normalize_branch_ref(ref: str) -> str:
"""Turn a ``git name-rev`` description into a local branch name.
``name-rev`` can return ``remotes/origin/staging~1``, ``develop^2~1`` or
``tags/v2.0``; none of them is a valid ``--base`` value.
"""
name = re.split(r"[~^]", ref.strip(), maxsplit=1)[0]
for prefix in ("refs/heads/", "heads/"):
if name.startswith(prefix):
return name[len(prefix):]
if name.startswith("remotes/"):
name = name[len("remotes/"):]
return name.split("/", 1)[1] if "/" in name else ""
if name.startswith("tags/"):
return name[len("tags/"):]
return name
def local_branch_exists(name: str) -> bool:
"""Return whether ``name`` is a local branch (no network involved)."""
try:
run_git("show-ref", "--verify", "--quiet", f"refs/heads/{name}")
return True
except GhCommandFailed:
return False
def detect_target_branch() -> str:
"""Return the nearest ancestor branch of HEAD, using only local git.
Port of ``scripts/detect-target-branch``: ``git name-rev`` picks the
closest ref and a graph walk is the fallback when it resolves to the
current branch. The result is normalized and checked against the local
branches because ``name-rev`` describes refs, not branch names.
"""
current = run_git("rev-parse", "--abbrev-ref", "HEAD")
try:
raw = run_git("name-rev", "--name-only", "HEAD")
except GhCommandFailed:
raw = ""
target = normalize_branch_ref(raw) if raw else ""
if not target or target == current:
target = ""
for commit in run_git("rev-list", "HEAD").splitlines():
branches = run_git(
"branch", "--points-at", commit, "--format=%(refname:short)"
).splitlines()
found = next(
(
branch.strip()
for branch in branches
if branch.strip() and branch.strip() != current
),
None,
)
if found:
target = normalize_branch_ref(found)
break
if not target:
raise RuntimeError("unable to determine target branch")
if not local_branch_exists(target):
raise RuntimeError(
f"detected base {target!r} is not a local branch; pass --base explicitly"
)
return target
def create_pr(
title: str,
body_file: str,
base: str | None = None,
head: str | None = None,
issue_number: int | None = None,
project: str = "Main",
draft: bool = False,
) -> dict:
"""Create a PR and optionally link its issue in one sequence of calls.
The base defaults to the nearest ancestor branch of HEAD and the head to
the current branch, so the caller only needs to supply the title and the
body. A failed issue link leaves the PR in place and reports its URL.
"""
if not title.strip():
raise ValueError("pull request title must not be empty")
resolved_base = (base or detect_target_branch()).strip()
if not resolved_base:
raise ValueError("pull request base must not be empty")
resolved_head = (head or run_git("rev-parse", "--abbrev-ref", "HEAD")).strip()
cmd = [
"gh", "pr", "create",
"--repo", REPO,
"--base", resolved_base,
"--head", resolved_head,
"--title", title,
"--project", project,
"--body-file", body_file,
]
if draft:
cmd.append("--draft")
stdout = run_gh_command(cmd)
url = stdout.strip().splitlines()[-1].strip()
match = PR_URL_RE.search(url)
if not match:
raise RuntimeError(
f"could not read PR number from gh output: {url!r};"
" check whether the PR was created"
)
number = int(match.group(1))
print(f"Created PR #{number}: {url}", file=sys.stderr)
linked_issue = None
if issue_number is not None:
try:
link_issue_to_pr(issue_number, number)
except SystemExit:
raise RuntimeError(
f"issue linking failed; the PR was created at {url}"
) from None
except (ValueError, RuntimeError) as error:
raise RuntimeError(f"{error}; the PR was created at {url}") from error
linked_issue = issue_number
return {
"number": number,
"url": url,
"title": title,
"base": resolved_base,
"head": resolved_head,
"linked_issue": linked_issue,
}
def cmd_create_pr(args: argparse.Namespace) -> None:
"""Handle the ``create-pr`` subcommand."""
print("Creating pull request...", file=sys.stderr)
try:
result = create_pr(
args.title,
args.body_file,
base=args.base,
head=args.head,
issue_number=args.issue,
project=args.project,
draft=args.draft,
)
except (ValueError, RuntimeError, GhCommandFailed) as error:
print(f"ERROR: {error}", file=sys.stderr)
sys.exit(1)
print(json.dumps(result, indent=2))
# ─────────────────────────────────────────────
# Subcommand: link-issue
# ─────────────────────────────────────────────
@ -1291,6 +1465,33 @@ def main() -> None:
)
p_create.set_defaults(func=cmd_create_issue)
# --- create-pr ---
p_create_pr = sub.add_parser(
"create-pr",
help="Create a pull request, optionally linking its issue",
)
p_create_pr.add_argument("--title", required=True, help="Pull request title")
p_create_pr.add_argument(
"--body-file", required=True,
help="Path to the file holding the Markdown body",
)
p_create_pr.add_argument(
"--base", help="Base branch (default: nearest ancestor branch of HEAD)"
)
p_create_pr.add_argument(
"--head", help="Head branch (default: current branch)"
)
p_create_pr.add_argument(
"--issue", type=int, help="Issue number to link to the new PR"
)
p_create_pr.add_argument(
"--draft", action="store_true", help="Create the PR as a draft"
)
p_create_pr.add_argument(
"--project", default="Main", help="Project to add the PR to (default: Main)"
)
p_create_pr.set_defaults(func=cmd_create_pr)
# --- issue (by-number lookup) ---
p_issue = sub.add_parser(
"issue", help="Fetch details for one or more issues by number (batched)"

View File

@ -179,6 +179,333 @@ class CreateIssueTests(unittest.TestCase):
self.assertIn("boom", stderr.getvalue())
class CreatePrBaseDetectionTests(unittest.TestCase):
@staticmethod
def fake_git(mapping):
def run(*args):
return mapping.get(args, "")
return run
def test_normalize_branch_ref(self):
cases = [
("remotes/origin/staging~2", "staging"),
("develop^2~1", "develop"),
("tags/v2.0", "v2.0"),
("refs/heads/topic~1", "topic"),
("heads/topic", "topic"),
]
for raw, expected in cases:
with self.subTest(raw=raw):
self.assertEqual(gh.normalize_branch_ref(raw), expected)
@patch.object(gh, "run_git")
def test_detects_normalized_base_and_validates_it(self, run_git):
calls = []
def fake(*args):
calls.append(args)
if args == ("rev-parse", "--abbrev-ref", "HEAD"):
return "topic"
if args == ("name-rev", "--name-only", "HEAD"):
return "remotes/origin/staging~2"
return ""
run_git.side_effect = fake
self.assertEqual(gh.detect_target_branch(), "staging")
self.assertIn(
("show-ref", "--verify", "--quiet", "refs/heads/staging"), calls
)
@patch.object(gh, "run_git")
def test_rejects_detected_base_without_local_branch(self, run_git):
def fake(*args):
if args == ("rev-parse", "--abbrev-ref", "HEAD"):
return "topic"
if args == ("name-rev", "--name-only", "HEAD"):
return "tags/v2.0"
if args[:1] == ("show-ref",):
raise gh.GhCommandFailed("not found")
return ""
run_git.side_effect = fake
with self.assertRaisesRegex(RuntimeError, "pass --base"):
gh.detect_target_branch()
@patch.object(gh, "run_git")
def test_detects_base_from_name_rev(self, run_git):
run_git.side_effect = self.fake_git({
("rev-parse", "--abbrev-ref", "HEAD"): "issue-13202",
("name-rev", "--name-only", "HEAD"): "staging~3",
})
self.assertEqual(gh.detect_target_branch(), "staging")
@patch.object(gh, "run_git")
def test_falls_back_to_graph_walk(self, run_git):
def fake(*args):
if args == ("rev-parse", "--abbrev-ref", "HEAD"):
return "issue-13202"
if args == ("name-rev", "--name-only", "HEAD"):
return "issue-13202"
if args == ("rev-list", "HEAD"):
return "a\nb\nc\n"
if args[:2] == ("branch", "--points-at"):
return "staging\n" if args[2] == "b" else ""
return ""
run_git.side_effect = fake
self.assertEqual(gh.detect_target_branch(), "staging")
@patch.object(gh, "run_git")
def test_tolerates_name_rev_failure(self, run_git):
def fake(*args):
if args == ("name-rev", "--name-only", "HEAD"):
raise gh.GhCommandFailed("boom")
if args == ("rev-parse", "--abbrev-ref", "HEAD"):
return "topic"
if args == ("rev-list", "HEAD"):
return "a\n"
if args[:2] == ("branch", "--points-at"):
return "staging\n"
return ""
run_git.side_effect = fake
self.assertEqual(gh.detect_target_branch(), "staging")
@patch.object(gh, "run_git")
def test_raises_when_no_other_branch(self, run_git):
run_git.side_effect = self.fake_git({
("rev-parse", "--abbrev-ref", "HEAD"): "topic",
("name-rev", "--name-only", "HEAD"): "",
("rev-list", "HEAD"): "a\n",
})
with self.assertRaisesRegex(RuntimeError, "unable to determine target branch"):
gh.detect_target_branch()
class CreatePrTests(unittest.TestCase):
def setUp(self):
self.url = "https://github.com/penpot/penpot/pull/13204"
self.create_response = self.url + "\n"
def args(self, **overrides):
values = dict(
title="A title",
body_file="/tmp/pr-body.md",
base=None,
head=None,
issue=None,
project="Main",
draft=False,
)
values.update(overrides)
return types.SimpleNamespace(**values)
@patch.object(gh, "link_issue_to_pr")
@patch.object(gh, "run_gh_command")
@patch.object(gh, "run_git")
@patch.object(gh, "detect_target_branch")
def test_create_pr_detects_base_and_links_issue(
self, detect, run_git, run_command, link_issue
):
detect.return_value = "staging"
run_git.return_value = "issue-13202"
run_command.return_value = self.create_response
with contextlib.redirect_stderr(io.StringIO()):
result = gh.create_pr(
"A title", "/tmp/pr-body.md", issue_number=13202
)
self.assertEqual(result, {
"number": 13204,
"url": self.url,
"title": "A title",
"base": "staging",
"head": "issue-13202",
"linked_issue": 13202,
})
self.assertEqual(run_command.call_args.args[0], [
"gh", "pr", "create",
"--repo", "penpot/penpot",
"--base", "staging",
"--head", "issue-13202",
"--title", "A title",
"--project", "Main",
"--body-file", "/tmp/pr-body.md",
])
link_issue.assert_called_once_with(13202, 13204)
detect.assert_called_once_with()
@patch.object(gh, "run_gh_command")
@patch.object(gh, "run_git")
@patch.object(gh, "detect_target_branch")
def test_create_pr_uses_explicit_base(self, detect, run_git, run_command):
run_git.return_value = "topic"
run_command.return_value = self.create_response
with contextlib.redirect_stderr(io.StringIO()):
result = gh.create_pr("T", "/tmp/pr-body.md", base="release/1.0")
self.assertEqual(result["base"], "release/1.0")
detect.assert_not_called()
cmd = run_command.call_args.args[0]
self.assertEqual(cmd[cmd.index("--base") + 1], "release/1.0")
@patch.object(gh, "run_gh_command")
@patch.object(gh, "detect_target_branch", return_value="staging")
def test_create_pr_passes_head_and_draft(self, _detect, run_command):
run_command.return_value = self.create_response
with contextlib.redirect_stderr(io.StringIO()):
result = gh.create_pr(
"T", "/tmp/pr-body.md", head="custom", draft=True
)
cmd = run_command.call_args.args[0]
self.assertEqual(cmd[cmd.index("--head") + 1], "custom")
self.assertIn("--draft", cmd)
self.assertIsNone(result["linked_issue"])
@patch.object(gh, "run_gh_command")
@patch.object(gh, "detect_target_branch")
def test_create_pr_rejects_empty_title(self, _detect, run_command):
with self.assertRaisesRegex(ValueError, "title must not be empty"):
gh.create_pr(" ", "/tmp/pr-body.md")
run_command.assert_not_called()
@patch.object(gh, "run_gh_command", return_value="created")
@patch.object(gh, "run_git", return_value="topic")
@patch.object(gh, "detect_target_branch", return_value="staging")
def test_create_pr_fails_when_url_has_no_number(
self, _detect, _run_git, _run_command
):
with self.assertRaisesRegex(RuntimeError, "could not read PR number"):
gh.create_pr("T", "/tmp/pr-body.md")
@patch.object(gh, "run_gh_command", side_effect=gh.GhCommandFailed("boom"))
@patch.object(gh, "run_git", return_value="topic")
@patch.object(gh, "detect_target_branch", return_value="staging")
def test_create_pr_propagates_gh_failure(
self, _detect, _run_git, _run_command
):
with self.assertRaises(gh.GhCommandFailed):
gh.create_pr("T", "/tmp/pr-body.md")
@patch.object(gh, "link_issue_to_pr")
@patch.object(gh, "run_gh_command")
@patch.object(gh, "run_git", return_value="topic")
@patch.object(gh, "detect_target_branch", return_value="staging")
def test_create_pr_prints_url_once_on_success(
self, _detect, _run_git, run_command, _link_issue
):
run_command.return_value = self.create_response
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
gh.create_pr("T", "/tmp/pr-body.md", issue_number=13202)
self.assertEqual(stderr.getvalue().count("Created PR #13204"), 1)
@patch.object(gh, "link_issue_to_pr", side_effect=RuntimeError("link missing"))
@patch.object(gh, "run_gh_command")
@patch.object(gh, "run_git", return_value="topic")
@patch.object(gh, "detect_target_branch", return_value="staging")
def test_cmd_create_pr_keeps_url_when_link_raises_runtime_error(
self, _detect, _run_git, run_command, _link_issue
):
run_command.return_value = self.create_response
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
with self.assertRaises(SystemExit) as error:
gh.cmd_create_pr(self.args(issue=13202))
self.assertEqual(error.exception.code, 1)
self.assertIn("Created PR #13204", stderr.getvalue())
self.assertIn(self.url, stderr.getvalue())
@patch.object(gh, "link_issue_to_pr", side_effect=SystemExit(1))
@patch.object(gh, "run_gh_command")
@patch.object(gh, "run_git", return_value="topic")
@patch.object(gh, "detect_target_branch", return_value="staging")
def test_cmd_create_pr_keeps_url_when_link_exits(
self, _detect, _run_git, run_command, _link_issue
):
run_command.return_value = self.create_response
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
with self.assertRaises(SystemExit) as error:
gh.cmd_create_pr(self.args(issue=13202))
self.assertEqual(error.exception.code, 1)
self.assertIn("Created PR #13204", stderr.getvalue())
self.assertIn("issue linking failed", stderr.getvalue())
self.assertIn(self.url, stderr.getvalue())
self.assertNotIn("ERROR: 1", stderr.getvalue())
@patch.object(gh, "create_pr")
def test_cmd_create_pr_outputs_result(self, create_pr):
expected = {
"number": 13204,
"url": self.url,
"title": "T",
"base": "staging",
"head": "topic",
"linked_issue": None,
}
create_pr.return_value = expected
stdout = io.StringIO()
stderr = io.StringIO()
with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
gh.cmd_create_pr(self.args())
self.assertEqual(json.loads(stdout.getvalue()), expected)
self.assertIn("Creating pull request...", stderr.getvalue())
create_pr.assert_called_once_with(
"A title", "/tmp/pr-body.md",
base=None, head=None, issue_number=None,
project="Main", draft=False,
)
@patch.object(gh, "create_pr")
def test_cmd_create_pr_forwards_project(self, create_pr):
create_pr.return_value = {"number": 13204, "url": self.url}
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(
io.StringIO()
):
gh.cmd_create_pr(self.args(project="Other"))
self.assertEqual(create_pr.call_args.kwargs["project"], "Other")
@patch.object(gh, "run_gh_command")
@patch.object(gh, "run_git", return_value="topic")
@patch.object(gh, "detect_target_branch", return_value="staging")
def test_create_pr_uses_explicit_project(self, _detect, _run_git, run_command):
run_command.return_value = self.create_response
with contextlib.redirect_stderr(io.StringIO()):
gh.create_pr("T", "/tmp/pr-body.md", project="Other")
cmd = run_command.call_args.args[0]
self.assertEqual(cmd[cmd.index("--project") + 1], "Other")
@patch.object(gh, "create_pr", side_effect=gh.GhCommandFailed("boom"))
def test_cmd_create_pr_exits_on_error(self, _create_pr):
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
with self.assertRaises(SystemExit) as error:
gh.cmd_create_pr(self.args())
self.assertEqual(error.exception.code, 1)
self.assertIn("boom", stderr.getvalue())
class LinkIssueTests(unittest.TestCase):
def setUp(self):
self.target_response = {