Pull request'ler
safran.pulls, pull request'leri, açık olanlar dâhil, şu anki hâlleriyle ve profildeki her kod barındırıcıda okur. Bu sayfa bir iş kaydından onun pull request'ine, oradan da inceleyenlerin oylarına, değişen dosyalara, çözülmemiş yorum dizilerine ve diff'e nasıl gidileceğini gösterir. Yalnızca birleştirilmiş işi bilen ve yerel bir depodan yanıt veren safran.links arayüzünün canlı karşılığıdır.
Buradaki her şey okumadır. Bir pull request'e yorum yazmak ya da bir yorum dizisini yanıtlamak safran.writes üzerinden yapılır.
Bir iş kaydından yorum dizilerine
import { createSafran, groupThreadsByFile } from "@safran/core";
await using safran = await createSafran();
// 1. From a ticket to its pull request. `best` is set when the choice is obvious.
const found = await safran.pulls.find({ ticket: "PAY-10" });
if (!found.best) {
for (const match of found.matches) console.log(`${match.repo}#${match.id} ${match.state} ${match.title}`);
throw new Error(found.matches.length === 0 ? "No pull request carries PAY-10" : "Several pull requests match: pick one");
}
const ref = `${found.best.host}:${found.best.repo}#${found.best.id}`;
// 2. The pull request as it is now, with reviewers and votes.
const pull = await safran.pulls.get(ref);
console.log(`${pull.repo}#${pull.id} ${pull.state}${pull.draft ? " (draft)" : ""} ${pull.title}`);
console.log(` ${pull.sourceBranch} → ${pull.targetBranch} tickets: ${pull.ticketKeys.join(", ")}`);
for (const reviewer of pull.reviewers ?? []) {
console.log(` ${reviewer.vote.padEnd(9)} ${reviewer.person.name}${reviewer.required ? " (required)" : ""}`);
}
// 3. What it changes.
const changes = await safran.pulls.changes(ref);
for (const file of changes.items) console.log(` ${file.change.padEnd(6)} ${file.previousPath ? `${file.previousPath} → ` : ""}${file.path}`);
// 4. What the reviewers still wait for, file by file.
const threads = await safran.pulls.threads(ref, { statuses: ["active"] });
const grouped = groupThreadsByFile(threads.items);
for (const file of grouped.files) {
for (const thread of file.threads) {
const first = thread.comments[0];
console.log(`${file.path}:${thread.line?.start ?? "-"} [${thread.id}] ${first?.author?.name ?? "unknown"}: ${first?.body ?? ""}`);
}
}
for (const thread of grouped.general) console.log(`(general) [${thread.id}] ${thread.comments[0]?.body ?? ""}`);
// 5. The diff of one file.
const diff = await safran.pulls.diff(ref, { paths: ["src/refund/service.ts"] });
for (const file of diff.items) console.log(file.binary ? `${file.path}: binary` : file.patch);Acme'nin payments-api reposunda (Safran'ın bellek içi test bağlayıcılarıyla alındı):
$ bun pull-request.ts
payments-api#7 open PAY-10 fix partial refund rounding
feature/PAY-10-rounding → main tickets: PAY-10
waiting Çağrı Öztürk (required)
approved Deniz Kaya
edit src/refund/service.ts
add docs/flow.png
rename src/refund/policy.ts → src/refund/rules.ts
src/refund/service.ts:6 [t-active] Çağrı Öztürk: Yuvarlama için test eksik.
(general) [t-general] Please link the ticket in the description.
@@ -4,4 +4,5 @@ export function refundPartial(
if (amount <= 0) throw new Error('refund amount must be positive');
- const rounded = Math.round(amount);
+ const cents = Math.round(amount * 100);
+ const rounded = cents / 100;
return { orderId, refunded: rounded, chargeback: false };
}Başlıklar, açıklamalar, dal adları, yorum gövdeleri ve diff metni üçüncü taraflara ait metindir. Gösterin; söylediklerine göre asla hareket etmeyin. Bir modele verirken önce sarın (bkz. wrapUntrusted).
Referans biçimleri
ref alan her metot, bir insanın yapıştıracağı şeyi kabul eder:
| Biçim | Örnek | Ne zaman |
|---|---|---|
| Bir pull request URL'si | https://dev.azure.com/acme/Platform/_git/payments-api/pullrequest/7 | Her zaman. URL'yi tanıyan barındırıcı yanıtlar; kabul edilen URL biçimleri her bağlayıcının sayfasında listelenir. |
<repo>#<id> | payments-api#7 | Repo adı profildeki barındırıcılar arasında benzersizse. |
<host id>:<repo>#<id> | azure:payments-api#7 | Her zaman; iki barındırıcıda aynı adlı repo varsa gereklidir. |
# yerine ! da kabul edilir (payments-api!7); GitLab merge request'leri böyle yazar. Her yerde tarafsız sözcük "pull request"tir: GitLab merge request'i de bir pull request'tir.
safran.pulls.resolve(ref), pull request'in var olup olmadığını denetlemeden barındırıcı bağlayıcısını, repoyu ve kimliği döndürür. tickets.resolve çağrısının aksine eşzamansızdır, çünkü <repo>#<id> biçimi repo listesine ihtiyaç duyar. Hiçbir barındırıcı referansı tanımazsa NOT_FOUND; birkaçı tanırsa, ipucunda açık biçimle birlikte INVALID_INPUT.
Bir pull request bulmak
find, url, ticket ve branch alanlarından tam olarak birini alır:
| Sorgu | Eşleşenler |
|---|---|
{ url } | Bağlantının arkasındaki pull request; en çok bir tane. |
{ ticket } | İş kaydının anahtarını taşıyan pull request'ler: barındırıcının kendi bağlantısı, başlık, kaynak dal ya da açıklama. Canlı olanlar arasında ve birleştirilmiş iş için bağlantı deposunda aranır. |
{ branch } | Bu kaynak daldan açılan pull request'ler: çoğunlukla çalışma ağacınızın dalı. |
repos, ticket ya da branch aramasını daraltır. state, URL için varsayılan olarak all değerindedir; diğerlerinde açık eşleşme varsa yalnızca onlar, yoksa birleştirilmiş ve kapatılmış olanlar döner.
Sonuç { matches, best, truncated, warnings } biçimindedir. matches en yeniden eskiye sıralıdır ve boş olabilir: hiçbir şey bulamamak hata değil, bir yanıttır. best, sormadan okunacak eşleşmedir: tek eşleşme ya da birkaç eşleşme içindeki tek açık olan. Yoksa matches listesini gösterin ve seçimi insana bırakın. options.limit eşleşme sayısını sınırlar (varsayılan DEFAULT_PULL_REQUEST_FIND_LIMIT, 10).
Listeleme
import { createSafran } from "@safran/core";
await using safran = await createSafran();
const page = await safran.pulls.list({ groups: ["backend"], reviewer: "Çağrı Öztürk", draft: false, limit: 20 });
for (const pull of page.items) {
const vote = pull.reviewers?.find((reviewer) => reviewer.person.name === "Çağrı Öztürk")?.vote ?? "unknown";
console.log(`${pull.host}:${pull.repo}#${pull.id} ${vote} ${pull.title}`);
}
for (const warning of page.warnings ?? []) console.error(`${warning.source}: ${warning.code}: ${warning.message}`);
if (page.nextCursor) console.log("more: pass nextCursor back as `cursor`, with the same options");list, barındırıcılar ve repolar üzerinden harmanlanmış tek bir sayfa döndürür; kabaca en yeni başta. Filtreler:
| Seçenek | Anlamı |
|---|---|
state | open (varsayılan), merged, closed ya da all. open taslakları da kapsar; closed, birleştirilmeden kapatılmış demektir. |
draft | Yalnızca taslaklar (true) ya da yalnızca taslak olmayanlar (false). |
author, reviewer | Görünen adla ya da e-posta adresiyle büyük-küçük harf ayrımı olmadan, kimlikle ise birebir eşleştirilir. Asla alt string olarak aranmaz: an, Jan adını seçmez. |
sourceBranch, targetBranch | Dalın tam adı; refs/heads/ olmadan. |
createdSince, updatedSince | ISO tarihleri. updatedSince, etkinlik tarihi tutmayan barındırıcıda UNSUPPORTED olur. |
host | Tek bir kod barındırıcı girdisinin kimliği. Varsayılan: pull-requests-live yeteneği olan her barındırıcı. |
repos, groups | Repo kısa adları ve profil grupları (birleşim); kod aramasındaki gibi birleştirilir. |
limit, cursor | Sayfa boyutu (varsayılan DEFAULT_PULL_REQUEST_LIST_LIMIT, 20; 100 ile sınırlanır) ve önceki sayfanın nextCursor değeri. |
Hiçbir filtre yok sayılmaz. Başarısız olan, canlı pull request'i olmayan ya da filtrelerden birini uygulayamayan barındırıcı warnings içinde adıyla yer alır; diğerleri yine yanıt verir. Yapılandırılmış hiçbir barındırıcı canlı pull request listeleyemiyorsa çağrı UNSUPPORTED fırlatır.
Bir listelemenin satırlarında reviewers, mergeability ve counts bulunmayabilir: bazı barındırıcılar bunları listelemede taşımaz. reviewers: [] kimseye sorulmadığı anlamına gelir; reviewers alanının hiç olmaması ise "öğrenmek için pull request'i getirin" demektir. get, barındırıcının bildiğini her zaman doldurur.
Tek bir pull request
| Metot | Döndürdüğü | Gereken yetenek |
|---|---|---|
get(ref) | LivePullRequest: ayrıntılar, barındırıcı girdisinin kimliği ve bulunan bütün iş kaydı anahtarları | pull-requests-live |
changes(ref, options?) | Page<PullRequestChange>: hedefe göre değişen dosyalar, içerikleri olmadan | pull-requests-live |
diff(ref, options?) | Page<PullRequestDiff>: değişen dosya başına bir öğe | pr-diff |
threads(ref, options?) | Page<ReviewThread>: satırlardaki, dosyalardaki yorumlar ve genel konuşma | pr-threads |
İnceleyenler ve oylar
Her inceleyen, son kararını barındırıcıdan bağımsız ortak sözcüklerle taşır:
vote | Anlamı |
|---|---|
approved | Onaylıyor. |
approved_with_suggestions | Onaylıyor ama notlar bıraktı. Bu düzeyi olmayan barındırıcılar hiç kullanmaz. |
waiting | Yazarı bekliyor: engellemeden değişiklik istendi. |
rejected | Birleştirmeyi engelliyor ("request changes", "rejected"). |
none | İnceleme istendi, henüz karar yok ya da yalnızca yorum yapıldı. |
required, barındırıcının ilkesi bu inceleyenin onayını gerektiriyorsa true olur; böyle bir kavramı olmayan barındırıcılarda bulunmaz. mergeability şunlardan biridir: clean, conflicts, blocked ya da unknown (barındırıcı henüz hesaplamadı). counts içindeki sayılar bilinmiyorsa tahmin edilmez; alan hiç bulunmaz.
Diff'ler
patch, dosya başlığı olmadan birleşik diff parçalarını tutar (@@ -a,b +c,d @@ başlıkları, ardından , + ve - satırları): yol ve değişiklik türü ayrı alanlardır. İkili dosyada (binary: true), yalnızca yeniden adlandırmada ve barındırıcı yama vermediğinde boştur. Hiçbir dosya atlanmaz; böylece "gösterilmedi" ile "değişmedi" ayırt edilebilir.
| Seçenek | Varsayılan | Anlamı |
|---|---|---|
paths | değişen her dosya | Yalnızca repo köküne göre verilen bu yollar; yeniden adlandırmanın eski yolu da çalışır. |
contextLines | DEFAULT_PR_DIFF_CONTEXT_LINES (3) | Her değişikliğin çevresindeki değişmemiş satırlar. Bunu değiştiremeyen barındırıcı kendi değerini kullanır. |
maxFileChars | DEFAULT_PR_DIFF_MAX_FILE_CHARS (60.000) | Her dosyanın yaması bu kadar karakterde, satır sınırında kesilir ve truncated olarak işaretlenir. |
limit, cursor | limit dosyaları sayar. |
Yorum dizileri
Bir yorum dizisinin bir status değeri, en az bir yorumu (ilki, yorum dizisini açandır) ve bir konumu vardır: path ile isteğe bağlı line aralığı ve side; genel konuşma için ise path yoktur.
status | Anlamı |
|---|---|
active | Tartışmaya açık. |
resolved | Biri kapattı. resolution, barındırıcının kendi sözcüğünü saklar: "fixed", "wontfix", "by design". |
outdated | Üzerine yazıldığı kod o günden beri değişti ve kimse çözmedi. Bu kavramı olmayan barındırıcı hiç kullanmaz. |
Yalnızca sistem girdilerinden (bir oy, bir push) oluşan yorum dizileri atılır; insanların yazdığı bir yorum dizisinin içindeki sistem girdisi system: true ile korunur. side: "old", silinmiş bir satır demektir; numarası dosyanın hedefteki sürümüne göredir.
groupThreadsByFile(threads) yorum dizilerini bir insanın üzerinden geçeceği biçimde dizer: yola göre sıralı dosya dosya, dosya içinde satıra göre, genel konuşma en sonda; durum başına sayılarla birlikte. Saf bir fonksiyondur ve filtrelemez: gösterilmesini istediğinizi verin. ReviewThread.id, bir pull_request.reply yazma işleminin threadId olarak aldığı değerdir.
Her barındırıcının kendi inceleme ve yorum dizisi durumlarını bu sözcüklere nasıl eşlediği ve hangi uç noktaların canlı bir serviste doğrulandığı Pull request'ler nasıl okunur sayfasında ve bağlayıcı sayfalarındadır: Azure Repos, GitHub, GitLab.
Barındırıcı bunu yapamadığında
Gereken yeteneği olmayan barındırıcı, çağrıyı UNSUPPORTED ile başarısız kılar; barındırıcının adını ve yapabildiklerini söyler. local barındırıcının hiç pull request'i yoktur.
import { createSafran, isSafranError } from "@safran/core";
await using safran = await createSafran();
try {
const diff = await safran.pulls.diff("payments-api#7");
console.log(`${diff.items.length} files`);
} catch (error) {
if (isSafranError(error, "UNSUPPORTED")) console.error(`${error.message}. ${error.hint ?? ""}`);
else if (isSafranError(error, "NOT_FOUND")) console.error(error.message);
else throw error;
}Repoda bulunmayan bir pull request kimliği NOT_FOUND olur; hiçbir barındırıcının listelemediği bir repo adı da öyle (ipucunda en yakın adlarla).
Türler
/**
* Live pull requests across every code host of the profile, with the conventions of
* `TicketsApi`. `ref` is whatever a person would paste: a pull request URL, the explicit form
* `<host id>:<repo>#<id>`, or `<repo>#<id>` when the repo name is unique across hosts
* (`!` is accepted for `#`). A host without the needed capability makes the call UNSUPPORTED,
* naming the host and its capabilities.
*/
export interface PullsApi {
/**
* Finds the host and repo a reference belongs to. NOT_FOUND when no host recognises it,
* INVALID_INPUT when several do (the hint shows the explicit form). Asynchronous, unlike
* `tickets.resolve`: the `<repo>#<id>` form needs the repo listing. It does not check that the
* pull request exists.
*/
resolve(ref: string, options?: CallOptions): Promise<ResolvedPullRequestRef>;
find(query: PullRequestFindQuery, options?: PullRequestFindOptions): Promise<PullRequestFindResult>;
/** One merged page over hosts and repos, roughly newest first. The cursor is opaque and belongs to the same options. */
list(options?: PullRequestListOptions): Promise<PullRequestListResult>;
get(ref: string, options?: CallOptions): Promise<LivePullRequest>;
changes(ref: string, options?: PageOptions): Promise<Page<PullRequestChange>>;
/** Needs `pr-diff`. */
diff(ref: string, options?: PullRequestDiffOptions): Promise<Page<PullRequestDiff>>;
/** Needs `pr-threads`. Group the result for display with kit `groupThreadsByFile`. */
threads(ref: string, options?: ReviewThreadQuery): Promise<Page<ReviewThread>>;
}
/**
* A pull request as it is now, with the code host entry it came from and every ticket key
* found for it: the host's native links plus keys recognised in the title, the source branch
* and the description (the same recognition the link store uses).
*/
export interface LivePullRequest extends PullRequestDetails {
host: string;
ticketKeys: string[];
}
export interface PullRequestFindResult {
/** Newest first. Empty when nothing matches (that is an answer, not an error). */
matches: LivePullRequest[];
/**
* The match a caller should read without asking: the only one, or the only OPEN one among
* several. Absent when the choice is not obvious; show `matches` and ask.
*/
best?: LivePullRequest;
/** True when more matched than `limit`. */
truncated: boolean;
warnings?: SafranWarning[];
}tanımlandığı yer: packages/core/src/api.ts
/**
* A pull request in its current state. Extends the wave 1 `PullRequest` (which only ever
* described merged ones), so everything that reads a `PullRequest` also reads this.
*/
export interface PullRequestDetails extends PullRequest {
state: PullRequestState;
/** Open but marked not ready for review ("draft", "work in progress"). Always false once merged or closed. */
draft: boolean;
createdAt?: string;
/** Last activity the host records: a push, a comment, a vote. Absent when the host has no such date. */
updatedAt?: string;
/** When it was closed without merging. `mergedAt` (inherited) is the date of a merge. */
closedAt?: string;
/** Empty when nobody was asked. ABSENT when a listing does not carry reviewers: fetch the pull request to know. */
reviewers?: PullRequestReviewer[];
/** Label / tag names, as the host shows them. Empty when the host has no labels on pull requests. */
labels: string[];
/** Tip of the source branch: the commit a line comment is anchored to. */
headSha?: string;
/** Commit of the target branch the changes are compared against. */
baseSha?: string;
mergeability?: PullRequestMergeability;
counts?: PullRequestCounts;
}
/** One file a pull request changes. */
export interface PullRequestChange {
/** Repo-relative path after the change (for a delete: the path that was removed). */
path: string;
/** Only for `rename`: where the file was. A rename that also edits content is still `rename`. */
previousPath?: string;
change: PullRequestChangeType;
/** Line counts, when the host reports them. Absent for binary files and on hosts that list paths only. */
additions?: number;
deletions?: number;
}
/** The diff of one file. */
export interface PullRequestDiff extends PullRequestChange {
/**
* Unified-diff hunks: `@@ -a,b +c,d @@` headers followed by ` `, `+` and `-` lines, joined
* with `\n`. No `diff --git` / `---` / `+++` file header (path and change type are fields).
* Empty for a binary file, for a pure rename, and when the host gave no patch.
*/
patch: string;
/** True when `patch` is shorter than the real diff: cut at `maxFileChars`, or withheld by the host as too large. */
truncated: boolean;
binary: boolean;
}
export interface ReviewThread {
/** What `replyToPullRequestThread` takes. Unique inside one pull request. */
id: string;
/** Repo-relative file the thread is on. Absent for the general conversation. */
path?: string;
/** 1-based line range in the file version `side` names. Absent for file-level and general threads. `end` is absent for a single line. */
line?: { start: number; end?: number };
/** `new`: the file after the change (the usual case). `old`: a removed line, numbered in the target's version. */
side?: "old" | "new";
status: ReviewThreadStatus;
/** The host's own word for a resolved thread: "fixed", "wontfix", "by design", … */
resolution?: string;
/** At least one comment, oldest first. The first one opened the thread. */
comments: ReviewComment[];
createdAt?: string;
updatedAt?: string;
}
export interface ReviewComment {
id: string;
author?: Person;
/** Markdown. */
body: string;
createdAt?: string;
updatedAt?: string;
/** Written by the host, not a person ("pushed 2 commits", "voted 10"). Never true for a whole returned thread. */
system: boolean;
}tanımlandığı yer: packages/kit/src/pulls.ts
Sık yapılan hatalar
- Açık bir pull request için
safran.linkskullanmak. Bağlantı deposu yalnızca birleştirilmiş işi tutar.safran.pullsbarındırıcıya şimdi sorar. found.bestyerinefound.matches[0]almak. Bir iş kaydı anahtarını birden çok pull request taşıyabilir.bestyalnızca seçim açıksa doludur.reviewersalanını listelemeden okumak. Orada bulunmayabilir. Oylar içingetçağırın.closeddurumunu "bitti" saymak.closedvazgeçilmiş demektir; birleştirilmiş pull requestmergedolur.authorya dareviewerolarak adın bir parçasını vermek. Eşleşme birebirdir (adlarda ve e-posta adreslerinde büyük-küçük harf ayrımı yapılmaz).- Bir imleci başka filtrelerle yeniden kullanmak. İmleç, üretildiği seçeneklere aittir; başkası
INVALID_INPUTolur.