дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-26 03:14:38 +02:00
Порівняти коміти
23
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
a5fb30e04f | ||
|
|
f2b8db548f | ||
|
|
89475f4fed | ||
|
|
2bc5e8d0c8 | ||
|
|
79e4233c56 | ||
|
|
df6ed5ccba | ||
|
|
f592ff5b05 | ||
|
|
c0c9553550 | ||
|
|
059fd8a69b | ||
|
|
696377acc2 | ||
|
|
52834088fe | ||
|
|
c3d29dc842 | ||
|
|
8dc1ee062f | ||
|
|
fcc36d67e7 | ||
|
|
00108a669e | ||
|
|
c08b0f543e | ||
|
|
7f9dda50b6 | ||
|
|
98c8c55b9e | ||
|
|
8fabf054ef | ||
|
|
a3cd99db1f | ||
|
|
0660f3c020 | ||
|
|
2754cf327f | ||
|
|
986b0ade58 |
No files matched your search
Створено
+36
-35
@@ -4038,7 +4038,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4061,7 +4061,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4075,7 +4075,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4090,7 +4090,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
@@ -4099,7 +4099,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4115,7 +4115,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4129,7 +4129,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -4147,7 +4147,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"bb8",
|
||||
"dirs 6.0.0",
|
||||
@@ -4169,7 +4169,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4183,7 +4183,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4194,7 +4194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4208,7 +4208,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -4253,7 +4253,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4271,7 +4271,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4293,7 +4293,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4309,7 +4309,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4364,7 +4364,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"globset",
|
||||
@@ -4372,6 +4372,7 @@ dependencies = [
|
||||
"ide-jsonrpc",
|
||||
"ide-language",
|
||||
"ide-text",
|
||||
"ignore",
|
||||
"lsp-types",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
@@ -4386,7 +4387,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4409,7 +4410,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4427,7 +4428,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4440,7 +4441,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"globset",
|
||||
"ide-core",
|
||||
@@ -4457,7 +4458,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4478,7 +4479,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4497,7 +4498,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"globset",
|
||||
@@ -4517,7 +4518,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4530,7 +4531,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4549,7 +4550,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4564,7 +4565,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4577,7 +4578,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4589,7 +4590,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4610,7 +4611,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4629,7 +4630,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4651,7 +4652,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"open",
|
||||
@@ -4667,7 +4668,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6137,7 +6138,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dirs 6.0.0",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.28"
|
||||
version = "0.1.29"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -12,6 +12,8 @@ use std::collections::BTreeMap;
|
||||
pub struct EditorGeneralSettings {
|
||||
/// Change font size with ⌘ + mouse wheel.
|
||||
pub wheel_zoom: bool,
|
||||
pub markdown_image_folder: String,
|
||||
pub markdown_image_name_pattern: String,
|
||||
/// Drag-and-drop of selected text inside the editor.
|
||||
pub drag_and_drop: bool,
|
||||
/// When the caret moves out of view: `minimize` scrolling | `center` the caret line.
|
||||
@@ -35,6 +37,8 @@ impl Default for EditorGeneralSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
wheel_zoom: false,
|
||||
markdown_image_folder: "assets".into(),
|
||||
markdown_image_name_pattern: "image-{timestamp}".into(),
|
||||
drag_and_drop: true,
|
||||
caret_scroll: "minimize".into(),
|
||||
soft_wrap_files: "*.md; *.txt; *.rst; *.adoc".into(),
|
||||
|
||||
@@ -21,6 +21,10 @@ pub enum IdeEvent {
|
||||
modified: Vec<crate::IpcPath>,
|
||||
removed: Vec<crate::IpcPath>,
|
||||
},
|
||||
/// Excluded or ignored folders whose contents changed; they stay out of `FsChanged`.
|
||||
ExcludedDirsChanged {
|
||||
dirs: Vec<crate::IpcPath>,
|
||||
},
|
||||
/// The backend changed a document (reload from disk, formatting, refactoring).
|
||||
/// The UI applies `changes` on top of `base_version`, yielding `version`.
|
||||
DocPatched {
|
||||
|
||||
@@ -80,6 +80,8 @@ const USER_DIRS: &[&str] = &[
|
||||
".cargo/bin",
|
||||
".local/bin",
|
||||
"go/bin",
|
||||
// `dotnet tool install --global` puts fsautocomplete, csharp-ls and friends here.
|
||||
".dotnet/tools",
|
||||
".bun/bin",
|
||||
".deno/bin",
|
||||
".npm-global/bin",
|
||||
@@ -96,6 +98,12 @@ const USER_DIRS: &[&str] = &[
|
||||
|
||||
const SYSTEM_DIRS: &[&str] = &["/opt/homebrew/bin", "/usr/local/go/bin", "/usr/local/bin", "/usr/bin", "/bin"];
|
||||
|
||||
/// Whether `dir` is one of the system's own bin directories, which [`search_path`] adds
|
||||
/// whatever `PATH` holds.
|
||||
pub fn is_system_dir(dir: &Path) -> bool {
|
||||
SYSTEM_DIRS.iter().any(|d| Path::new(d) == dir)
|
||||
}
|
||||
|
||||
/// The `bin` directories of nvm's Node versions in `dir`, newest first.
|
||||
fn nvm_bins(dir: &Path) -> Vec<PathBuf> {
|
||||
let mut versions: Vec<(Vec<u64>, PathBuf)> = std::fs::read_dir(dir)
|
||||
@@ -170,6 +178,8 @@ mod tests {
|
||||
let at = |d: &str| dirs.iter().position(|p| p == Path::new(d)).unwrap();
|
||||
assert_eq!(dirs[..3], [PathBuf::from("/usr/bin"), "/opt/tools".into(), "/home/me/.asdf/shims".into()]);
|
||||
assert!(at("/home/me/.npm-global/bin") < at("/home/me/.pyenv/shims"));
|
||||
// Global .NET tools (fsautocomplete, csharp-ls) install here, off PATH.
|
||||
assert!(at("/home/me/.dotnet/tools") < at("/usr/local/bin"));
|
||||
assert!(at("/home/me/.local/share/mise/shims") < at("/usr/local/bin"));
|
||||
assert!(dirs.iter().all(|d| d.is_absolute()));
|
||||
let unique: HashSet<&PathBuf> = dirs.iter().collect();
|
||||
|
||||
@@ -107,7 +107,7 @@ pub fn availability(root: &Path) -> GhAvailability {
|
||||
}
|
||||
let (repo, login) = std::thread::scope(|s| {
|
||||
let repo = s.spawn(|| {
|
||||
let cmd = command(root, &["repo", "view", "--json", "nameWithOwner,url,defaultBranchRef"])?;
|
||||
let cmd = command(root, &["repo", "view", "--json", REPO_FIELDS])?;
|
||||
process::run(cmd, QUICK, None)
|
||||
});
|
||||
let login = s.spawn(|| run(root, &["api", "user", "--jq", ".login"]));
|
||||
@@ -278,6 +278,53 @@ pub fn add_comment(root: &Path, number: u32, body: &str) -> IdeResult<()> {
|
||||
run(root, &["pr", "comment", &n, "--body", body]).map(drop)
|
||||
}
|
||||
|
||||
/// A GitHub API call through `gh api`: GraphQL (`endpoint` `graphql`, `body`
|
||||
/// `{"query", "variables"}`) or REST (`repos/{owner}/{repo}/…`, gh fills in the
|
||||
/// placeholders from the project's remote).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GhApiRequest {
|
||||
/// `GET`, `POST`, `PATCH`, `PUT`, `DELETE`.
|
||||
pub method: String,
|
||||
pub endpoint: String,
|
||||
/// JSON request body, sent on stdin.
|
||||
pub body: Option<String>,
|
||||
/// Follow REST `Link` pages; the result is the array of all pages (`--slurp`).
|
||||
pub paginate: bool,
|
||||
}
|
||||
|
||||
const METHODS: &[&str] = &["GET", "POST", "PATCH", "PUT", "DELETE"];
|
||||
|
||||
/// `gh api` arguments for `req`.
|
||||
pub fn api_args(req: &GhApiRequest) -> IdeResult<Vec<String>> {
|
||||
let method = req.method.to_ascii_uppercase();
|
||||
if !METHODS.contains(&method.as_str()) {
|
||||
return Err(IdeError::invalid(format!("unsupported HTTP method {}", req.method)));
|
||||
}
|
||||
let endpoint = req.endpoint.trim();
|
||||
if endpoint.is_empty() || endpoint.starts_with('-') || endpoint.contains("://") {
|
||||
return Err(IdeError::invalid(format!("not a GitHub API endpoint: {endpoint}")));
|
||||
}
|
||||
let mut args: Vec<String> = vec!["api".into(), "--method".into(), method, endpoint.into()];
|
||||
if req.body.is_some() {
|
||||
args.push("--input".into());
|
||||
args.push("-".into());
|
||||
}
|
||||
if req.paginate {
|
||||
args.push("--paginate".into());
|
||||
args.push("--slurp".into());
|
||||
}
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// Runs `req`; returns the response body (JSON text, empty for `204 No Content`).
|
||||
pub fn api(root: &Path, req: &GhApiRequest) -> IdeResult<String> {
|
||||
let args = api_args(req)?;
|
||||
let refs: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
let out = process::run_with_input(command(root, &refs)?, req.body.as_deref(), QUICK, None)?;
|
||||
if out.success { Ok(out.stdout) } else { Err(failure(&out.stderr, &out.stdout)) }
|
||||
}
|
||||
|
||||
/// Revisions to diff a pull request's files with, present in the local repository.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -34,6 +34,12 @@ pub struct GhRepo {
|
||||
pub name_with_owner: String,
|
||||
pub url: String,
|
||||
pub default_branch: Option<String>,
|
||||
/// Merge methods the repository allows (all of them when gh does not say).
|
||||
pub merge_commit_allowed: bool,
|
||||
pub squash_merge_allowed: bool,
|
||||
pub rebase_merge_allowed: bool,
|
||||
/// The signed-in user's permission: `ADMIN`, `MAINTAIN`, `WRITE`, `TRIAGE`, `READ`; empty when unknown.
|
||||
pub viewer_permission: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -152,6 +158,8 @@ pub struct PullRequestDetails {
|
||||
pub base_oid: String,
|
||||
/// `MERGEABLE`, `CONFLICTING`, `UNKNOWN`.
|
||||
pub mergeable: String,
|
||||
/// GitHub's merge box state: `CLEAN`, `UNSTABLE`, `HAS_HOOKS`, `BLOCKED`, `BEHIND`, `DIRTY`, `DRAFT`, `UNKNOWN`.
|
||||
pub merge_state_status: String,
|
||||
pub is_cross_repository: bool,
|
||||
pub merged_at: Option<String>,
|
||||
pub closed_at: Option<String>,
|
||||
@@ -242,7 +250,7 @@ impl RawSummary {
|
||||
pub const LIST_FIELDS: &str = "number,title,author,state,isDraft,headRefName,baseRefName,createdAt,updatedAt,labels,reviewDecision,url,additions,deletions";
|
||||
|
||||
/// Fields requested from `gh pr view`.
|
||||
pub const VIEW_FIELDS: &str = "number,title,author,state,isDraft,headRefName,baseRefName,createdAt,updatedAt,labels,reviewDecision,url,additions,deletions,body,headRefOid,baseRefOid,mergeable,isCrossRepository,mergedAt,closedAt,statusCheckRollup,reviewRequests,reviews,assignees,commits,files,comments";
|
||||
pub const VIEW_FIELDS: &str = "number,title,author,state,isDraft,headRefName,baseRefName,createdAt,updatedAt,labels,reviewDecision,url,additions,deletions,body,headRefOid,baseRefOid,mergeable,mergeStateStatus,isCrossRepository,mergedAt,closedAt,statusCheckRollup,reviewRequests,reviews,assignees,commits,files,comments";
|
||||
|
||||
pub fn parse_list(json: &str) -> serde_json::Result<Vec<PullRequestSummary>> {
|
||||
let raw: Vec<RawSummary> = serde_json::from_str(json)?;
|
||||
@@ -348,6 +356,7 @@ struct RawDetails {
|
||||
head_ref_oid: String,
|
||||
base_ref_oid: String,
|
||||
mergeable: String,
|
||||
merge_state_status: String,
|
||||
is_cross_repository: bool,
|
||||
merged_at: Option<String>,
|
||||
closed_at: Option<String>,
|
||||
@@ -442,6 +451,7 @@ pub fn parse_view(json: &str) -> serde_json::Result<PullRequestDetails> {
|
||||
head_oid: raw.head_ref_oid,
|
||||
base_oid: raw.base_ref_oid,
|
||||
mergeable: raw.mergeable,
|
||||
merge_state_status: raw.merge_state_status,
|
||||
is_cross_repository: raw.is_cross_repository,
|
||||
merged_at: raw.merged_at.filter(|s| !s.is_empty()),
|
||||
closed_at: raw.closed_at.filter(|s| !s.is_empty()),
|
||||
@@ -534,6 +544,10 @@ struct RawRepo {
|
||||
name_with_owner: String,
|
||||
url: String,
|
||||
default_branch_ref: Option<RawBranchRef>,
|
||||
merge_commit_allowed: Option<bool>,
|
||||
squash_merge_allowed: Option<bool>,
|
||||
rebase_merge_allowed: Option<bool>,
|
||||
viewer_permission: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
@@ -542,13 +556,21 @@ struct RawBranchRef {
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// `gh repo view --json nameWithOwner,url,defaultBranchRef`.
|
||||
/// Fields requested from `gh repo view`.
|
||||
pub const REPO_FIELDS: &str =
|
||||
"nameWithOwner,url,defaultBranchRef,mergeCommitAllowed,squashMergeAllowed,rebaseMergeAllowed,viewerPermission";
|
||||
|
||||
/// `gh repo view --json` with [`REPO_FIELDS`].
|
||||
pub fn parse_repo(json: &str) -> serde_json::Result<GhRepo> {
|
||||
let raw: RawRepo = serde_json::from_str(json)?;
|
||||
Ok(GhRepo {
|
||||
name_with_owner: raw.name_with_owner,
|
||||
url: raw.url,
|
||||
default_branch: raw.default_branch_ref.map(|b| b.name).filter(|n| !n.is_empty()),
|
||||
merge_commit_allowed: raw.merge_commit_allowed.unwrap_or(true),
|
||||
squash_merge_allowed: raw.squash_merge_allowed.unwrap_or(true),
|
||||
rebase_merge_allowed: raw.rebase_merge_allowed.unwrap_or(true),
|
||||
viewer_permission: raw.viewer_permission.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -60,9 +60,30 @@ fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<Str
|
||||
|
||||
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
|
||||
/// a non-zero exit is reported in [`Output::success`], not as an error.
|
||||
pub(crate) fn run(mut cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
|
||||
pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
|
||||
run_with_input(cmd, None, timeout, cancel)
|
||||
}
|
||||
|
||||
/// [`run`] with `input` written to the child's stdin (then closed).
|
||||
pub(crate) fn run_with_input(
|
||||
mut cmd: Command,
|
||||
input: Option<&str>,
|
||||
timeout: Duration,
|
||||
cancel: Option<&CancellationToken>,
|
||||
) -> IdeResult<Output> {
|
||||
prepare(&mut cmd);
|
||||
if input.is_some() {
|
||||
cmd.stdin(Stdio::piped());
|
||||
}
|
||||
let mut child = spawn(&mut cmd)?;
|
||||
if let (Some(input), Some(mut stdin)) = (input, child.stdin.take()) {
|
||||
let input = input.to_owned();
|
||||
// A writer thread: a large body must not block on a full pipe while gh is not reading yet.
|
||||
std::thread::spawn(move || {
|
||||
use std::io::Write;
|
||||
let _ = stdin.write_all(input.as_bytes());
|
||||
});
|
||||
}
|
||||
let out = child.stdout.take().map(read_all);
|
||||
let err = child.stderr.take().map(read_all);
|
||||
let deadline = Instant::now() + timeout;
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"additions":42,"assignees":[],"author":{"id":"MDQ6VXNlcjM2NzI4OTMx","is_bot":false,"login":"babakks","name":"Babak K. Shandiz"},"baseRefName":"trunk","baseRefOid":"ae7b9715976c5508398b11dc8546e1279e10f6fc","body":"### Description\n\nThis PR moves gh to the tagged version of `cli/oauth`.","closedAt":"2026-10-21T12:29:58Z","comments":[{"id":"IC_1","author":{"login":"babakks"},"authorAssociation":"MEMBER","body":"Rebased on trunk.","createdAt":"2026-10-21T08:00:00Z","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/cli/cli/pull/14768#issuecomment-1","viewerDidAuthor":false}],"commits":[{"authoredDate":"2026-10-20T16:37:24Z","authors":[{"email":"[email protected]","id":"MDQ6VXNlcjM2NzI4OTMx","login":"babakks","name":"Babak K. Shandiz"}],"committedDate":"2026-10-21T12:06:51Z","messageBody":"cli/oauth v1.3.0 exposes the token expiry fields as time.Duration values.","messageHeadline":"chore(deps): bump github.com/cli/oauth to v1.3.0","oid":"fd1b1feb222dde885d00262b2c21b107c6c6e416"}],"createdAt":"2026-10-20T16:40:41Z","deletions":48,"files":[{"path":"go.mod","additions":1,"deletions":1,"changeType":"MODIFIED"},{"path":"pkg/cmd/status/status.go","additions":3,"deletions":2,"changeType":"MODIFIED"}],"headRefName":"babakks/refresh-token-bump-deps","headRefOid":"6ec1ba54542baca6cc5932582634104c83f36a28","isCrossRepository":false,"isDraft":false,"labels":[],"mergeable":"UNKNOWN","mergedAt":"2026-10-21T12:29:58Z","number":14768,"reviewDecision":"APPROVED","reviewRequests":[{"__typename":"User","login":"niik"}],"reviews":[{"id":"PRR_1","author":{"login":"copilot-pull-request-reviewer"},"authorAssociation":"CONTRIBUTOR","body":"","submittedAt":"2026-10-21T09:46:01Z","includesCreatedEdit":false,"reactionGroups":[],"state":"COMMENTED","commit":{"oid":"831b9343fa77c2f11f521a49fd01da2d2d007b8e"}},{"id":"PRR_2","author":{"login":"williammartin"},"authorAssociation":"MEMBER","body":"LGTM","submittedAt":"2026-10-21T12:20:00Z","includesCreatedEdit":false,"reactionGroups":[],"state":"APPROVED","commit":{"oid":"6ec1ba54542baca6cc5932582634104c83f36a28"}}],"state":"MERGED","statusCheckRollup":[{"__typename":"CheckRun","completedAt":"2026-10-21T12:09:03Z","conclusion":"SUCCESS","detailsUrl":"https://github.com/cli/cli/actions/runs/1/job/1","name":"build (ubuntu)","startedAt":"2026-10-21T12:07:01Z","status":"COMPLETED","workflowName":"Tests"},{"__typename":"CheckRun","completedAt":"0001-01-01T00:00:00Z","conclusion":"","detailsUrl":"https://github.com/cli/cli/actions/runs/1/job/2","name":"build (windows)","startedAt":"2026-10-21T12:07:01Z","status":"IN_PROGRESS","workflowName":"Tests"},{"__typename":"CheckRun","completedAt":"2026-10-21T12:08:00Z","conclusion":"FAILURE","detailsUrl":"https://github.com/cli/cli/actions/runs/1/job/3","name":"lint","startedAt":"2026-10-21T12:07:01Z","status":"COMPLETED","workflowName":"Lint"},{"__typename":"CheckRun","completedAt":"2026-10-21T12:08:00Z","conclusion":"SKIPPED","detailsUrl":"","name":"docs","startedAt":"2026-10-21T12:07:01Z","status":"COMPLETED","workflowName":""},{"__typename":"StatusContext","context":"ci/legacy","state":"PENDING","targetUrl":"https://ci.example.com/1","startedAt":"2026-10-21T12:07:01Z"}],"title":"Refreshable tokens: bump cli/oauth to v1.3.0 and fix `gh status` column width","updatedAt":"2026-10-21T12:30:00Z","url":"https://github.com/cli/cli/pull/14768"}
|
||||
{"additions":42,"assignees":[],"author":{"id":"MDQ6VXNlcjM2NzI4OTMx","is_bot":false,"login":"babakks","name":"Babak K. Shandiz"},"baseRefName":"trunk","baseRefOid":"ae7b9715976c5508398b11dc8546e1279e10f6fc","body":"### Description\n\nThis PR moves gh to the tagged version of `cli/oauth`.","closedAt":"2026-10-21T12:29:58Z","comments":[{"id":"IC_1","author":{"login":"babakks"},"authorAssociation":"MEMBER","body":"Rebased on trunk.","createdAt":"2026-10-21T08:00:00Z","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/cli/cli/pull/14768#issuecomment-1","viewerDidAuthor":false}],"commits":[{"authoredDate":"2026-10-20T16:37:24Z","authors":[{"email":"[email protected]","id":"MDQ6VXNlcjM2NzI4OTMx","login":"babakks","name":"Babak K. Shandiz"}],"committedDate":"2026-10-21T12:06:51Z","messageBody":"cli/oauth v1.3.0 exposes the token expiry fields as time.Duration values.","messageHeadline":"chore(deps): bump github.com/cli/oauth to v1.3.0","oid":"fd1b1feb222dde885d00262b2c21b107c6c6e416"}],"createdAt":"2026-10-20T16:40:41Z","deletions":48,"files":[{"path":"go.mod","additions":1,"deletions":1,"changeType":"MODIFIED"},{"path":"pkg/cmd/status/status.go","additions":3,"deletions":2,"changeType":"MODIFIED"}],"headRefName":"babakks/refresh-token-bump-deps","headRefOid":"6ec1ba54542baca6cc5932582634104c83f36a28","isCrossRepository":false,"isDraft":false,"labels":[],"mergeable":"UNKNOWN","mergeStateStatus":"UNKNOWN","mergedAt":"2026-10-21T12:29:58Z","number":14768,"reviewDecision":"APPROVED","reviewRequests":[{"__typename":"User","login":"niik"}],"reviews":[{"id":"PRR_1","author":{"login":"copilot-pull-request-reviewer"},"authorAssociation":"CONTRIBUTOR","body":"","submittedAt":"2026-10-21T09:46:01Z","includesCreatedEdit":false,"reactionGroups":[],"state":"COMMENTED","commit":{"oid":"831b9343fa77c2f11f521a49fd01da2d2d007b8e"}},{"id":"PRR_2","author":{"login":"williammartin"},"authorAssociation":"MEMBER","body":"LGTM","submittedAt":"2026-10-21T12:20:00Z","includesCreatedEdit":false,"reactionGroups":[],"state":"APPROVED","commit":{"oid":"6ec1ba54542baca6cc5932582634104c83f36a28"}}],"state":"MERGED","statusCheckRollup":[{"__typename":"CheckRun","completedAt":"2026-10-21T12:09:03Z","conclusion":"SUCCESS","detailsUrl":"https://github.com/cli/cli/actions/runs/1/job/1","name":"build (ubuntu)","startedAt":"2026-10-21T12:07:01Z","status":"COMPLETED","workflowName":"Tests"},{"__typename":"CheckRun","completedAt":"0001-01-01T00:00:00Z","conclusion":"","detailsUrl":"https://github.com/cli/cli/actions/runs/1/job/2","name":"build (windows)","startedAt":"2026-10-21T12:07:01Z","status":"IN_PROGRESS","workflowName":"Tests"},{"__typename":"CheckRun","completedAt":"2026-10-21T12:08:00Z","conclusion":"FAILURE","detailsUrl":"https://github.com/cli/cli/actions/runs/1/job/3","name":"lint","startedAt":"2026-10-21T12:07:01Z","status":"COMPLETED","workflowName":"Lint"},{"__typename":"CheckRun","completedAt":"2026-10-21T12:08:00Z","conclusion":"SKIPPED","detailsUrl":"","name":"docs","startedAt":"2026-10-21T12:07:01Z","status":"COMPLETED","workflowName":""},{"__typename":"StatusContext","context":"ci/legacy","state":"PENDING","targetUrl":"https://ci.example.com/1","startedAt":"2026-10-21T12:07:01Z"}],"title":"Refreshable tokens: bump cli/oauth to v1.3.0 and fix `gh status` column width","updatedAt":"2026-10-21T12:30:00Z","url":"https://github.com/cli/cli/pull/14768"}
|
||||
@@ -22,6 +22,7 @@ fn pr_view() {
|
||||
assert_eq!(pr.summary.number, 14768);
|
||||
assert_eq!(pr.summary.head_ref, "babakks/refresh-token-bump-deps");
|
||||
assert_eq!(pr.head_oid, "6ec1ba54542baca6cc5932582634104c83f36a28");
|
||||
assert_eq!(pr.merge_state_status, "UNKNOWN");
|
||||
assert_eq!(pr.files.len(), 2);
|
||||
assert_eq!(pr.files[0].change_type, "MODIFIED");
|
||||
assert_eq!(pr.commits[0].headline, "chore(deps): bump github.com/cli/oauth to v1.3.0");
|
||||
@@ -69,6 +70,16 @@ fn repo_view() {
|
||||
.unwrap();
|
||||
assert_eq!(r.name_with_owner, "l0ng-ai/openidea");
|
||||
assert_eq!(r.default_branch.as_deref(), Some("main"));
|
||||
assert!(r.merge_commit_allowed && r.squash_merge_allowed && r.rebase_merge_allowed, "unknown: allowed");
|
||||
assert_eq!(r.viewer_permission, "");
|
||||
|
||||
let r = parse_repo(
|
||||
r#"{"mergeCommitAllowed":true,"nameWithOwner":"o/r","url":"","rebaseMergeAllowed":false,"squashMergeAllowed":false,"viewerPermission":"WRITE"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(r.merge_commit_allowed);
|
||||
assert!(!r.squash_merge_allowed && !r.rebase_merge_allowed);
|
||||
assert_eq!(r.viewer_permission, "WRITE");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -87,3 +98,24 @@ fn list_arguments() {
|
||||
assert!(joined.contains("--limit 500 --state merged --author @me"));
|
||||
assert_eq!(args.last().map(String::as_str), Some("review-requested:@me fix login"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_arguments() {
|
||||
let req =
|
||||
GhApiRequest { method: "post".into(), endpoint: "graphql".into(), body: Some("{}".into()), paginate: false };
|
||||
assert_eq!(api_args(&req).unwrap(), ["api", "--method", "POST", "graphql", "--input", "-"]);
|
||||
let req = GhApiRequest {
|
||||
method: "GET".into(),
|
||||
endpoint: "repos/{owner}/{repo}/labels".into(),
|
||||
body: None,
|
||||
paginate: true,
|
||||
};
|
||||
assert_eq!(
|
||||
api_args(&req).unwrap(),
|
||||
["api", "--method", "GET", "repos/{owner}/{repo}/labels", "--paginate", "--slurp"]
|
||||
);
|
||||
for bad in ["--hostname", "https://evil.example/x", ""] {
|
||||
assert!(api_args(&GhApiRequest { endpoint: bad.into(), ..req.clone() }).is_err(), "{bad}");
|
||||
}
|
||||
assert!(api_args(&GhApiRequest { method: "TRACE".into(), ..req }).is_err());
|
||||
}
|
||||
@@ -49,6 +49,10 @@ pub fn create_file(host: &Host, window: &str, path: PathBuf) -> IdeResult<()> {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_file_bytes(host: &Host, path: PathBuf, data: Vec<u8>) -> IdeResult<()> {
|
||||
host.blocking(move || ide_vfs::create_file_bytes(&path, &data)).await
|
||||
}
|
||||
|
||||
/// Toggle Read-only Attribute: sets the writable bit (and the open document's
|
||||
/// state). Returns whether the file is read-only now.
|
||||
pub fn set_writable(host: &Host, window: &str, path: PathBuf, writable: bool) -> IdeResult<bool> {
|
||||
|
||||
@@ -736,6 +736,19 @@ pub async fn vcs_diff_revisions(
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.diff_revisions(&from, &to))).await
|
||||
}
|
||||
|
||||
/// The best common ancestor of `a` and `b` (`git merge-base`), if any: the New Pull
|
||||
/// Request tab's three-dot diff.
|
||||
pub async fn vcs_merge_base(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
a: String,
|
||||
b: String,
|
||||
) -> IdeResult<Option<String>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.merge_base(&a, &b))).await
|
||||
}
|
||||
|
||||
pub async fn vcs_create_patch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -976,6 +989,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("vcs_diff_revisions", |c| async move {
|
||||
vcs_diff_revisions(&c.host, &c.window, c.arg("repo")?, c.arg("from")?, c.arg("to")?).await
|
||||
});
|
||||
d.add("vcs_merge_base", |c| async move {
|
||||
vcs_merge_base(&c.host, &c.window, c.arg("repo")?, c.arg("a")?, c.arg("b")?).await
|
||||
});
|
||||
d.add("vcs_create_patch", |c| async move {
|
||||
vcs_create_patch(&c.host, &c.window, c.arg("repo")?, c.arg("source")?).await
|
||||
});
|
||||
|
||||
@@ -223,6 +223,7 @@ impl Host {
|
||||
let history = history.clone();
|
||||
let remote = self.remote.clone();
|
||||
let runtime = self.runtime.clone();
|
||||
let lsp = lsp.clone();
|
||||
Watcher::start(
|
||||
&root.clone(),
|
||||
excludes.clone(),
|
||||
@@ -230,6 +231,7 @@ impl Host {
|
||||
Box::new(move |batch| {
|
||||
let changed: Vec<PathBuf> = batch.created.iter().chain(&batch.modified).cloned().collect();
|
||||
index.update(&changed, &batch.removed);
|
||||
lsp.project_files_changed(batch.created.iter().chain(&batch.removed));
|
||||
// Atomic saves by external tools surface as `created`.
|
||||
documents.on_disk_changed(&changed);
|
||||
// A framework's root marker (`angular.json`) created or deleted: its
|
||||
@@ -358,6 +360,12 @@ impl Host {
|
||||
weak.upgrade().map(|p| p.reference_candidates(q, cancel)).unwrap_or_default()
|
||||
}));
|
||||
}
|
||||
{
|
||||
let weak = Arc::downgrade(&project);
|
||||
project.lsp.set_project_excludes_hook(Box::new(move || {
|
||||
weak.upgrade().map(|p| p.exclude_globs()).unwrap_or_default()
|
||||
}));
|
||||
}
|
||||
self.insert_project(window, project.clone());
|
||||
if let Some(cmd) = post_start {
|
||||
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
|
||||
|
||||
@@ -168,6 +168,9 @@ impl Dispatcher {
|
||||
.add("cancel_task", |c| async move { Ok(ide_core::task::cancel(c.arg::<TaskId>("id")?)) })
|
||||
.add("fs_read_dir", |c| async move { ops::fs::read_dir(&c.host, &c.window, c.arg("path")?) })
|
||||
.add("fs_create_file", |c| async move { ops::fs::create_file(&c.host, &c.window, c.arg("path")?) })
|
||||
.add("fs_create_file_bytes", |c| async move {
|
||||
ops::fs::create_file_bytes(&c.host, c.arg("path")?, c.arg("data")?).await
|
||||
})
|
||||
.add("fs_create_dir", |c| async move { ide_vfs::create_dir(&c.arg::<PathBuf>("path")?) })
|
||||
.add("fs_rename", |c| async move { ide_vfs::rename(&c.arg::<PathBuf>("from")?, &c.arg::<PathBuf>("to")?) })
|
||||
.add("fs_set_writable", |c| async move {
|
||||
|
||||
@@ -120,6 +120,9 @@ pub struct LanguageServerConfig {
|
||||
/// a JDK 21+); reported as the failure instead of launching it.
|
||||
#[serde(skip)]
|
||||
pub launch_error: Option<String>,
|
||||
/// Register source files with tsserver when no project configuration exists.
|
||||
#[serde(default)]
|
||||
pub tsserver_project: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
|
||||
@@ -19,6 +19,7 @@ parking_lot.workspace = true
|
||||
tracing.workspace = true
|
||||
futures.workspace = true
|
||||
globset.workspace = true
|
||||
ignore.workspace = true
|
||||
toml.workspace = true
|
||||
percent-encoding = "2"
|
||||
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
//! Give tsserver a project for unopened sources, without creating a config file.
|
||||
use crate::LspManager;
|
||||
use crate::server::{Running, Server};
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
pub type ExcludesFn = dyn Fn() -> Vec<String> + Send + Sync;
|
||||
const COMMAND: &str = "typescript.tsserverRequest";
|
||||
const LIMIT: usize = 10_000;
|
||||
const SCAN_LIMIT: usize = 100_000;
|
||||
/// tsserver turns its language service off past 20 MiB of JavaScript in a project.
|
||||
const SCRIPT_BYTES_LIMIT: u64 = 16 << 20;
|
||||
const REFRESH_DELAY: Duration = Duration::from_millis(300);
|
||||
const TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct State {
|
||||
generation: u64,
|
||||
files: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
fn supported(server: &Server, run: &Running) -> bool {
|
||||
server.config.tsserver_project
|
||||
&& run
|
||||
.caps
|
||||
.read()
|
||||
.raw
|
||||
.pointer("/executeCommandProvider/commands")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|commands| commands.iter().any(|c| c.as_str() == Some(COMMAND)))
|
||||
}
|
||||
|
||||
fn configured(dir: &Path) -> bool {
|
||||
["tsconfig.json", "jsconfig.json"].iter().any(|name| dir.join(name).is_file())
|
||||
}
|
||||
|
||||
fn is_script(ext: &str) -> bool {
|
||||
matches!(ext, "js" | "jsx" | "mjs" | "cjs")
|
||||
}
|
||||
|
||||
fn is_source(ext: &str) -> bool {
|
||||
is_script(ext) || matches!(ext, "ts" | "tsx" | "mts" | "cts")
|
||||
}
|
||||
|
||||
/// All-or-nothing at the caps: a partial project could displace an inferred
|
||||
/// project while omitting some of its files. Configured trees stay with tsserver.
|
||||
fn source_files(root: &Path, exclude_root: &Path, excludes: Vec<String>, limit: usize) -> Vec<PathBuf> {
|
||||
if root.ancestors().any(configured) {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut ignores = ignore::gitignore::GitignoreBuilder::new(exclude_root);
|
||||
for pattern in excludes {
|
||||
if ignores.add_line(None, &pattern).is_err() {
|
||||
return Vec::new();
|
||||
}
|
||||
}
|
||||
let Ok(ignores) = ignores.build() else { return Vec::new() };
|
||||
let mut walk = ignore::WalkBuilder::new(root);
|
||||
walk.require_git(false).follow_links(false).filter_entry(move |entry| {
|
||||
if entry.depth() == 0 {
|
||||
return true;
|
||||
}
|
||||
let path = entry.path();
|
||||
let name = entry.file_name().to_string_lossy();
|
||||
!matches!(name.as_ref(), "node_modules" | "dist" | "build" | "out" | "coverage" | "target" | ".git")
|
||||
&& !ignores.matched_path_or_any_parents(path, entry.file_type().is_some_and(|t| t.is_dir())).is_ignore()
|
||||
});
|
||||
let mut files = Vec::new();
|
||||
let mut script_bytes = 0;
|
||||
for (visited, entry) in walk.build().enumerate() {
|
||||
// Do not claim a tree is config-less if we could not inspect it fully.
|
||||
let Ok(entry) = entry else { return Vec::new() };
|
||||
if visited >= SCAN_LIMIT {
|
||||
return Vec::new();
|
||||
}
|
||||
if entry.file_type().is_some_and(|t| t.is_dir()) && configured(entry.path()) {
|
||||
return Vec::new();
|
||||
}
|
||||
let ext = entry.path().extension().and_then(|s| s.to_str()).unwrap_or_default();
|
||||
if entry.file_type().is_some_and(|t| t.is_file()) && is_source(ext) {
|
||||
if is_script(ext) {
|
||||
script_bytes += entry.metadata().map_or(0, |m| m.len());
|
||||
if script_bytes > SCRIPT_BYTES_LIMIT {
|
||||
tracing::debug!("external TypeScript project exceeds its script size; retaining inferred projects");
|
||||
return Vec::new();
|
||||
}
|
||||
}
|
||||
files.push(entry.into_path());
|
||||
if files.len() > limit {
|
||||
tracing::debug!("external TypeScript project exceeds {limit} files; retaining inferred projects");
|
||||
return Vec::new();
|
||||
}
|
||||
}
|
||||
}
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
|
||||
fn project_name(server: &Server) -> PathBuf {
|
||||
server.root.join(".openidea-external-project")
|
||||
}
|
||||
|
||||
async fn request(run: &Running, command: &str, args: Value) -> bool {
|
||||
let request = run.peer.request::<_, Value>(
|
||||
"workspace/executeCommand",
|
||||
json!({
|
||||
"command": COMMAND,
|
||||
"arguments": [command, args, { "isAsync": false, "expectsResult": true }]
|
||||
}),
|
||||
None,
|
||||
);
|
||||
match tokio::time::timeout(TIMEOUT, request).await {
|
||||
Ok(Ok(result)) if result.get("success").and_then(Value::as_bool) == Some(true) => true,
|
||||
result => {
|
||||
tracing::debug!("tsserver {command}: {result:?}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LspManager {
|
||||
pub fn set_project_excludes_hook(&self, hook: Box<ExcludesFn>) {
|
||||
*self.excludes_hook.write() = Some(Arc::from(hook));
|
||||
}
|
||||
|
||||
pub(crate) async fn refresh_external_project(&self, server: &Server, run: &Running) {
|
||||
if !supported(server, run) {
|
||||
return;
|
||||
}
|
||||
let mut state = server.external_project.lock().await;
|
||||
if state.generation != run.generation {
|
||||
*state = State { generation: run.generation, files: Vec::new() };
|
||||
server.external_diagnostics.store(false, Ordering::Release);
|
||||
}
|
||||
let root = server.root.clone();
|
||||
let exclude_root = self.project_root_for(&root);
|
||||
let hook = self.excludes_hook.read().clone();
|
||||
let files = tokio::task::spawn_blocking(move || {
|
||||
source_files(&root, &exclude_root, hook.map(|h| h()).unwrap_or_default(), LIMIT)
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
if state.files == files {
|
||||
return;
|
||||
}
|
||||
if files.is_empty() {
|
||||
if request(run, "closeExternalProject", json!({ "projectFileName": project_name(server) })).await {
|
||||
state.files.clear();
|
||||
// Keep suppressing delayed diagnostics for unopened files from this instance.
|
||||
}
|
||||
return;
|
||||
}
|
||||
server.external_diagnostics.store(true, Ordering::Release);
|
||||
let roots: Vec<_> = files.iter().map(|p| json!({ "fileName": p })).collect();
|
||||
if request(
|
||||
run,
|
||||
"openExternalProject",
|
||||
json!({
|
||||
"projectFileName": project_name(server), "rootFiles": roots,
|
||||
// What an inferred project assumes, so sharing a project changes no diagnostics.
|
||||
"options": { "allowJs": true, "target": "ES2022", "module": "ESNext",
|
||||
"moduleResolution": "Node", "allowNonTsExtensions": true, "jsx": "preserve",
|
||||
"allowSyntheticDefaultImports": true, "strictNullChecks": true,
|
||||
"strictFunctionTypes": true, "moduleDetection": "force" }
|
||||
}),
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::debug!(
|
||||
"{}: registered {} external project files at {}",
|
||||
server.name,
|
||||
files.len(),
|
||||
server.root.display()
|
||||
);
|
||||
state.files = files;
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-registers config-less projects after sources or configurations changed on disk.
|
||||
pub fn project_files_changed<'a>(&self, paths: impl IntoIterator<Item = &'a PathBuf>) {
|
||||
let relevant = paths.into_iter().any(|p| {
|
||||
p.extension().and_then(|s| s.to_str()).is_some_and(is_source)
|
||||
|| p.file_name().is_some_and(|n| n == "tsconfig.json" || n == "jsconfig.json")
|
||||
});
|
||||
if !relevant {
|
||||
return;
|
||||
}
|
||||
for server in self.servers.lock().iter().filter(|s| s.config.tsserver_project) {
|
||||
if server.external_refresh_queued.swap(true, Ordering::AcqRel) {
|
||||
continue;
|
||||
}
|
||||
let (me, server) = (self.me.clone(), server.clone());
|
||||
self.runtime.spawn(async move {
|
||||
tokio::time::sleep(REFRESH_DELAY).await;
|
||||
server.external_refresh_queued.store(false, Ordering::Release);
|
||||
if let (Some(me), Some(run)) = (me.upgrade(), server.running()) {
|
||||
me.refresh_external_project(&server, &run).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn close_external_project(&self, server: &Server, run: &Running) {
|
||||
let mut state = server.external_project.lock().await;
|
||||
if state.generation == run.generation && !state.files.is_empty() {
|
||||
request(run, "closeExternalProject", json!({ "projectFileName": project_name(server) })).await;
|
||||
state.files.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(root: &Path, path: &str) {
|
||||
let path = root.join(path);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "").unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_sources_honouring_ignores_exclusions_and_roots() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
for path in [
|
||||
"a.ts",
|
||||
"src/b.js",
|
||||
"src/c.tsx",
|
||||
"readme.md",
|
||||
"node_modules/n.ts",
|
||||
"dist/d.js",
|
||||
"excluded/e.ts",
|
||||
"ignored/i.ts",
|
||||
"other/f.py",
|
||||
] {
|
||||
write(root, path);
|
||||
}
|
||||
std::fs::write(root.join(".gitignore"), "ignored/\n").unwrap();
|
||||
assert_eq!(
|
||||
source_files(root, root, vec!["excluded".into()], LIMIT),
|
||||
vec![root.join("a.ts"), root.join("src/b.js"), root.join("src/c.tsx")]
|
||||
);
|
||||
assert!(source_files(root, root, vec![], 1).is_empty());
|
||||
std::fs::File::create(root.join("large.js")).unwrap().set_len(SCRIPT_BYTES_LIMIT + 1).unwrap();
|
||||
assert!(source_files(root, root, vec![], LIMIT).is_empty());
|
||||
std::fs::remove_file(root.join("large.js")).unwrap();
|
||||
std::fs::File::create(root.join("large.ts")).unwrap().set_len(SCRIPT_BYTES_LIMIT + 1).unwrap();
|
||||
assert_eq!(source_files(root, root, vec!["excluded".into()], LIMIT).len(), 4);
|
||||
std::fs::remove_file(root.join("large.ts")).unwrap();
|
||||
assert_eq!(source_files(&root.join("src"), root, vec![], LIMIT).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_ancestor_and_nested_configs_keep_existing_projects() {
|
||||
for name in ["tsconfig.json", "jsconfig.json"] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
write(root, "a.ts");
|
||||
write(root, "pkg/b.js");
|
||||
assert_eq!(source_files(root, root, vec![], LIMIT).len(), 2);
|
||||
write(root, &format!("pkg/{name}"));
|
||||
assert!(source_files(root, root, vec![], LIMIT).is_empty());
|
||||
std::fs::remove_file(root.join("pkg").join(name)).unwrap();
|
||||
write(root, name);
|
||||
assert!(source_files(root, root, vec![], LIMIT).is_empty());
|
||||
assert!(source_files(&root.join("pkg"), root, vec![], LIMIT).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additions_deletions_and_renames_change_membership() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write(dir.path(), "a.js");
|
||||
let first = source_files(dir.path(), dir.path(), vec![], LIMIT);
|
||||
write(dir.path(), "b.ts");
|
||||
assert_eq!(source_files(dir.path(), dir.path(), vec![], LIMIT).len(), 2);
|
||||
std::fs::rename(dir.path().join("b.ts"), dir.path().join("b.txt")).unwrap();
|
||||
assert_eq!(source_files(dir.path(), dir.path(), vec![], LIMIT), first);
|
||||
std::fs::remove_file(dir.path().join("a.js")).unwrap();
|
||||
assert!(source_files(dir.path(), dir.path(), vec![], LIMIT).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -120,7 +120,10 @@ impl ClientHandler {
|
||||
};
|
||||
let Some(path) = uri_to_path(params.uri.as_str()) else { return };
|
||||
// Files opened only for a request (references search) are not the user's problems.
|
||||
if self.server.suppresses_diagnostics(&path) {
|
||||
if (self.server.external_diagnostics.load(std::sync::atomic::Ordering::Acquire)
|
||||
&& !mgr.docs.lock().values().any(|d| d.path == path))
|
||||
|| self.server.suppresses_diagnostics(&path)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let conv = mgr.conv(self.encoding());
|
||||
|
||||
@@ -192,7 +192,7 @@ impl LspManager {
|
||||
ide_core::event::ServerStatus::Missing => {
|
||||
"jdtls is not installed (Settings › Languages & Frameworks › Language Servers)".to_owned()
|
||||
}
|
||||
ide_core::event::ServerStatus::Misconfigured => {
|
||||
ide_core::event::ServerStatus::Misconfigured | ide_core::event::ServerStatus::Crashed => {
|
||||
server.status_message().unwrap_or_else(|| "jdtls cannot start".to_owned())
|
||||
}
|
||||
_ => format!("jdtls is not ready ({status:?})"),
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
mod angular;
|
||||
mod caps;
|
||||
mod convert;
|
||||
mod external_project;
|
||||
mod file_ops;
|
||||
mod handler;
|
||||
mod inspect;
|
||||
@@ -169,6 +170,7 @@ pub struct LspManager {
|
||||
prepare_hook: RwLock<Option<Arc<PrepareFn>>>,
|
||||
servers_hook: RwLock<Option<Arc<ServersFn>>>,
|
||||
candidates_hook: RwLock<Option<Arc<CandidateFn>>>,
|
||||
excludes_hook: RwLock<Option<Arc<external_project::ExcludesFn>>>,
|
||||
shutting_down: AtomicBool,
|
||||
/// `window/showMessage` texts already surfaced; servers repeat them on every restart/reconfigure.
|
||||
shown_messages: Mutex<HashSet<(String, String)>>,
|
||||
@@ -299,6 +301,7 @@ impl LspManager {
|
||||
prepare_hook: RwLock::new(None),
|
||||
servers_hook: RwLock::new(None),
|
||||
candidates_hook: RwLock::new(None),
|
||||
excludes_hook: RwLock::new(None),
|
||||
shutting_down: AtomicBool::new(false),
|
||||
shown_messages: Mutex::new(HashSet::new()),
|
||||
virtual_origins: Mutex::new(HashMap::new()),
|
||||
@@ -459,24 +462,37 @@ impl LspManager {
|
||||
let cfg = server.effective_config();
|
||||
let message =
|
||||
cfg.install_hint.clone().unwrap_or_else(|| format!("`{}` was not found on PATH", cfg.command));
|
||||
if server.finish_start(generation, Conn::Missing) {
|
||||
server.set_status(&self.sink, ide_core::event::ServerStatus::Missing, Some(message));
|
||||
if server.fail_start(
|
||||
generation,
|
||||
Conn::Missing,
|
||||
&self.sink,
|
||||
ide_core::event::ServerStatus::Missing,
|
||||
Some(message),
|
||||
) {
|
||||
self.attach_fallbacks();
|
||||
}
|
||||
return;
|
||||
}
|
||||
Err(LaunchError::Config(message)) => {
|
||||
tracing::warn!("{}: {message}", server.name);
|
||||
if server.finish_start(generation, Conn::Failed) {
|
||||
server.set_status(&self.sink, ide_core::event::ServerStatus::Misconfigured, Some(message));
|
||||
}
|
||||
server.fail_start(
|
||||
generation,
|
||||
Conn::Failed,
|
||||
&self.sink,
|
||||
ide_core::event::ServerStatus::Misconfigured,
|
||||
Some(message),
|
||||
);
|
||||
return;
|
||||
}
|
||||
Err(LaunchError::Failed(message)) => {
|
||||
tracing::warn!("{}: {message}", server.name);
|
||||
if server.finish_start(generation, Conn::Failed) {
|
||||
server.set_status(&self.sink, ide_core::event::ServerStatus::Crashed, Some(message));
|
||||
}
|
||||
server.fail_start(
|
||||
generation,
|
||||
Conn::Failed,
|
||||
&self.sink,
|
||||
ide_core::event::ServerStatus::Crashed,
|
||||
Some(message),
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
@@ -517,6 +533,8 @@ impl LspManager {
|
||||
}
|
||||
let run = Running { generation, peer: peer.clone(), caps: Arc::new(RwLock::new(caps)) };
|
||||
|
||||
self.refresh_external_project(&server, &run).await;
|
||||
|
||||
// Publish readiness and (re)open attached documents atomically w.r.t. did_change.
|
||||
{
|
||||
let mut docs = self.docs.lock();
|
||||
@@ -559,6 +577,7 @@ impl LspManager {
|
||||
};
|
||||
self.clear_server_state(&server);
|
||||
if intentional {
|
||||
server.announce_down();
|
||||
return;
|
||||
}
|
||||
let tail = server.stderr_tail(5);
|
||||
@@ -575,6 +594,9 @@ impl LspManager {
|
||||
match server.record_crash() {
|
||||
Some(delay) => {
|
||||
server.set_status(&self.sink, ServerStatus::Crashed, Some(format!("{message}\nRestarting…")));
|
||||
// Woken after the crash is reported: a request that finds no instance
|
||||
// reads this status to say why. The restart sets `Starting` again.
|
||||
server.announce_down();
|
||||
tokio::time::sleep(delay).await;
|
||||
if server.is_idle_gen(generation) {
|
||||
self.ensure_started(&server);
|
||||
@@ -587,6 +609,8 @@ impl LspManager {
|
||||
ServerStatus::Crashed,
|
||||
Some(format!("{message}\nCrashed repeatedly; restart it manually.")),
|
||||
);
|
||||
// Requests still waiting for a start read this status for their error.
|
||||
server.announce_down();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2212,6 +2236,7 @@ impl LspManager {
|
||||
return;
|
||||
}
|
||||
let graceful = async {
|
||||
self.close_external_project(server, &run).await;
|
||||
peer.request::<_, Value>("shutdown", (), None).await.ok();
|
||||
peer.notify("exit", ()).ok();
|
||||
peer.closed().await;
|
||||
|
||||
@@ -99,6 +99,9 @@ pub struct Server {
|
||||
/// Woken when the last `$/progress` task ends.
|
||||
idle_notify: Notify,
|
||||
transient: Mutex<HashMap<PathBuf, Transient>>,
|
||||
pub external_project: tokio::sync::Mutex<crate::external_project::State>,
|
||||
pub external_diagnostics: std::sync::atomic::AtomicBool,
|
||||
pub external_refresh_queued: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
@@ -123,6 +126,9 @@ impl Server {
|
||||
published_notify: Notify::new(),
|
||||
idle_notify: Notify::new(),
|
||||
transient: Mutex::new(HashMap::new()),
|
||||
external_project: tokio::sync::Mutex::new(Default::default()),
|
||||
external_diagnostics: std::sync::atomic::AtomicBool::new(false),
|
||||
external_refresh_queued: std::sync::atomic::AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,15 +168,27 @@ impl Server {
|
||||
Some(st.generation)
|
||||
}
|
||||
|
||||
/// Starting → Missing/Failed.
|
||||
pub fn finish_start(&self, generation: u64, conn: Conn) -> bool {
|
||||
let mut st = self.state.lock();
|
||||
if st.generation == generation && matches!(st.conn, Conn::Starting) {
|
||||
/// Starting → Missing/Failed, publishing the status the failed start reports
|
||||
/// before waiters wake: a request that wakes on `Phase::Down` reads the status
|
||||
/// to say why it has no server, and must not still see `Starting`.
|
||||
pub fn fail_start(
|
||||
&self,
|
||||
generation: u64,
|
||||
conn: Conn,
|
||||
sink: &SharedSink,
|
||||
status: ServerStatus,
|
||||
message: Option<String>,
|
||||
) -> bool {
|
||||
{
|
||||
let mut st = self.state.lock();
|
||||
if st.generation != generation || !matches!(st.conn, Conn::Starting) {
|
||||
return false;
|
||||
}
|
||||
st.conn = conn;
|
||||
self.phase.send_replace(Phase::Down);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
self.set_status(sink, status, message);
|
||||
self.announce_down();
|
||||
true
|
||||
}
|
||||
|
||||
/// Starting → Ready. False when the start was superseded or cancelled.
|
||||
@@ -191,6 +209,12 @@ impl Server {
|
||||
}
|
||||
}
|
||||
|
||||
/// Wakes requests waiting for a start that ended without an instance, after
|
||||
/// its status is published.
|
||||
pub fn announce_down(&self) {
|
||||
self.phase.send_replace(Phase::Down);
|
||||
}
|
||||
|
||||
pub fn running(&self) -> Option<Running> {
|
||||
match &self.state.lock().conn {
|
||||
Conn::Ready(r) => Some(r.clone()),
|
||||
@@ -246,7 +270,8 @@ impl Server {
|
||||
}
|
||||
|
||||
/// Instance `generation`'s connection closed. `None` if superseded, else whether
|
||||
/// the close was intentional.
|
||||
/// the close was intentional. Waiters are woken by [`Self::announce_down`] once
|
||||
/// the crash is reported, not here: they read the status to say why.
|
||||
pub fn on_closed(&self, generation: u64) -> Option<bool> {
|
||||
let mut st = self.state.lock();
|
||||
if st.generation != generation {
|
||||
@@ -255,7 +280,6 @@ impl Server {
|
||||
match &st.conn {
|
||||
Conn::Ready(_) | Conn::Starting => {
|
||||
st.conn = Conn::Idle;
|
||||
self.phase.send_replace(Phase::Down);
|
||||
Some(false)
|
||||
}
|
||||
_ => Some(true),
|
||||
@@ -529,6 +553,36 @@ mod tests {
|
||||
assert_eq!(s.record_crash(), Some(Duration::from_millis(500)));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_failed_start_reports_its_status_before_waiters_wake() {
|
||||
// The race behind "jdtls is not ready (Starting)": a request woken by the
|
||||
// phase change reads the status to say why it has no server, so the status
|
||||
// must already be the failure's.
|
||||
let s = Arc::new(server());
|
||||
let sink: SharedSink = Arc::new(|_: IdeEvent| {});
|
||||
let generation = s.begin_start().unwrap();
|
||||
let waiter = {
|
||||
let s = s.clone();
|
||||
tokio::spawn(async move {
|
||||
let run = s.wait_ready(Duration::from_secs(30)).await;
|
||||
(run.is_none(), s.status())
|
||||
})
|
||||
};
|
||||
tokio::task::yield_now().await;
|
||||
assert!(s.fail_start(generation, Conn::Failed, &sink, ServerStatus::Crashed, Some("boom".into())));
|
||||
assert_eq!(waiter.await.unwrap(), (true, ServerStatus::Crashed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_superseded_start_is_not_announced() {
|
||||
let s = server();
|
||||
let generation = s.begin_start().unwrap();
|
||||
s.begin_stop(); // abandons the start and invalidates its generation
|
||||
let sink: SharedSink = Arc::new(|_: IdeEvent| {});
|
||||
assert!(!s.fail_start(generation, Conn::Failed, &sink, ServerStatus::Crashed, Some("boom".into())));
|
||||
assert_eq!(s.status(), ServerStatus::Stopped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crash_excerpt_keeps_the_exception_line() {
|
||||
// Node.js 24 crash of vue-language-server (issue #25), verbatim shape.
|
||||
|
||||
@@ -210,6 +210,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
|
||||
fallback: false,
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
tsserver_project: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2258,3 +2259,67 @@ async fn rename_edits_files_outside_the_analysis_scope() {
|
||||
assert_eq!(paths, vec![a, b.clone()]);
|
||||
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn external_projects_are_capability_gated_and_follow_lifecycle() {
|
||||
for capable in [false, true] {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"] = json!({ "commands": if capable {
|
||||
vec!["typescript.tsserverRequest"]
|
||||
} else { vec!["_typescript.organizeImports"] } });
|
||||
let h = harness_configured("typescript", "ts", &[("arbitrary-name", caps)], |cfg| {
|
||||
cfg.tsserver_project = true;
|
||||
});
|
||||
let s = h.launcher.state("arbitrary-name");
|
||||
s.respond("workspace/executeCommand", json!({ "success": true, "body": true }));
|
||||
std::fs::write(h.root.join("unopened.ts"), "export const helper = 1;").unwrap();
|
||||
h.open("main.ts", "helper");
|
||||
h.wait_status("arbitrary-name", ServerStatus::Ready).await;
|
||||
if !capable {
|
||||
assert!(s.requested("workspace/executeCommand").is_empty());
|
||||
h.mgr.shutdown_all().await;
|
||||
assert!(s.requested("workspace/executeCommand").is_empty());
|
||||
continue;
|
||||
}
|
||||
let requests = s.requested("workspace/executeCommand");
|
||||
assert_eq!(requests[0]["arguments"][0], "openExternalProject");
|
||||
assert_eq!(requests[0]["arguments"][1]["rootFiles"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(s.docs.lock().len(), 1, "registration must not open source documents");
|
||||
std::fs::write(h.root.join("new.ts"), "export const newHelper = 1;").unwrap();
|
||||
h.mgr.project_files_changed([&h.root.join("new.ts")]);
|
||||
eventually(|| s.requested("workspace/executeCommand").len() >= 2).await;
|
||||
assert_eq!(
|
||||
s.requested("workspace/executeCommand")[1]["arguments"][1]["rootFiles"].as_array().unwrap().len(),
|
||||
3
|
||||
);
|
||||
std::fs::rename(h.root.join("new.ts"), h.root.join("renamed.ts")).unwrap();
|
||||
h.mgr.project_files_changed([&h.root.join("renamed.ts")]);
|
||||
eventually(|| s.requested("workspace/executeCommand").len() >= 3).await;
|
||||
assert!(s.requested("workspace/executeCommand")[2].to_string().contains("renamed.ts"));
|
||||
std::fs::remove_file(h.root.join("renamed.ts")).unwrap();
|
||||
h.mgr.project_files_changed([&h.root.join("renamed.ts")]);
|
||||
eventually(|| s.requested("workspace/executeCommand").len() >= 4).await;
|
||||
let id = h.mgr.servers()[0].id;
|
||||
h.mgr.restart(id).await.unwrap();
|
||||
h.wait_status("arbitrary-name", ServerStatus::Ready).await;
|
||||
eventually(|| {
|
||||
s.requested("workspace/executeCommand")
|
||||
.iter()
|
||||
.filter(|r| r["arguments"][0] == "openExternalProject")
|
||||
.count()
|
||||
>= 5
|
||||
})
|
||||
.await;
|
||||
std::fs::write(h.root.join("tsconfig.json"), "{}").unwrap();
|
||||
h.mgr.project_files_changed([&h.root.join("tsconfig.json")]);
|
||||
eventually(|| {
|
||||
s.requested("workspace/executeCommand")
|
||||
.iter()
|
||||
.filter(|r| r["arguments"][0] == "closeExternalProject")
|
||||
.count()
|
||||
>= 2
|
||||
})
|
||||
.await;
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
}
|
||||
@@ -78,6 +78,7 @@ async fn missing_binary_is_reported_with_install_hint() {
|
||||
fallback: false,
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
tsserver_project: false,
|
||||
};
|
||||
let (mgr, events) = manager(dir.path(), LanguageRegistry::from_configs(vec![lang("nope", "nope", server)]));
|
||||
let path = dir.path().join("a.nope");
|
||||
@@ -247,6 +248,7 @@ async fn typescript_language_server_end_to_end() {
|
||||
fallback: false,
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
tsserver_project: false,
|
||||
};
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![lang("typescript", "ts", server)]));
|
||||
let doc = DocId::next();
|
||||
@@ -292,6 +294,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
|
||||
fallback: false,
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
tsserver_project: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
#![cfg(unix)]
|
||||
|
||||
use ide_core::event::ServerStatus;
|
||||
use ide_core::{DocId, IdeEvent, LanguageId};
|
||||
use ide_core::{CancellationToken, DocId, IdeEvent, LanguageId};
|
||||
use ide_language::{LanguageConfig, LanguageRegistry, LanguageServerConfig};
|
||||
use ide_lsp::{LspManager, ProcessLauncher};
|
||||
use parking_lot::Mutex;
|
||||
@@ -65,3 +65,40 @@ async fn crash_before_the_handshake_reports_what_the_server_printed() {
|
||||
assert!(message.contains(". . ."), "{message}");
|
||||
mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_request_that_needs_a_crashed_jdtls_reports_why_it_crashed() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().to_path_buf();
|
||||
let script = root.join("fake-jdtls");
|
||||
std::fs::write(&script, LAUNCHER).unwrap();
|
||||
std::fs::set_permissions(&script, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
|
||||
|
||||
let server: LanguageServerConfig =
|
||||
toml::from_str(&format!("name = \"jdtls\"\ncommand = {:?}", script.to_string_lossy())).unwrap();
|
||||
let lang: LanguageConfig = toml::from_str("id = \"java\"\nname = \"Java\"\nextensions = [\"java\"]").unwrap();
|
||||
let lang = LanguageConfig { language_servers: vec![server], ..lang };
|
||||
let registry = Arc::new(LanguageRegistry::from_configs(vec![lang]));
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = {
|
||||
let events = events.clone();
|
||||
Arc::new(move |e: IdeEvent| events.lock().push(e))
|
||||
};
|
||||
let mgr = LspManager::with_launcher(root.clone(), registry, sink, Arc::new(ProcessLauncher));
|
||||
let path = root.join("A.java");
|
||||
std::fs::write(&path, "class A {}\n").unwrap();
|
||||
mgr.did_open(DocId::next(), &path, &LanguageId::new("java"), 1, "class A {}\n");
|
||||
for _ in 0..1000 {
|
||||
let crashed =
|
||||
events.lock().iter().any(|e| matches!(e, IdeEvent::LanguageServer { status: ServerStatus::Crashed, .. }));
|
||||
if crashed {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
|
||||
let error = mgr.java_classpath(&path, false, &CancellationToken::new()).await.unwrap_err();
|
||||
assert!(error.message.contains("jdtls exited with code 1"), "{}", error.message);
|
||||
assert!(error.message.contains("'python' is not recognized"), "{}", error.message);
|
||||
mgr.shutdown_all().await;
|
||||
}
|
||||
@@ -78,6 +78,7 @@ struct FileConfig {
|
||||
#[serde(default)]
|
||||
args: Vec<String>,
|
||||
cwd: Option<PathBuf>,
|
||||
module: Option<String>,
|
||||
#[serde(default)]
|
||||
env: BTreeMap<String, String>,
|
||||
#[serde(default, alias = "isTest", alias = "is_test")]
|
||||
@@ -161,6 +162,7 @@ fn convert(configs: Vec<FileConfig>, local: bool) -> Vec<RunConfig> {
|
||||
debug_adapter: c.debug_adapter.filter(|d| !d.is_empty()),
|
||||
allow_parallel: c.allow_parallel,
|
||||
extras: RunExtras {
|
||||
module: c.module,
|
||||
params: c.params,
|
||||
folder: non_empty(c.folder),
|
||||
local,
|
||||
@@ -210,6 +212,9 @@ fn to_table(c: &RunConfig) -> Table {
|
||||
if !c.args.is_empty() {
|
||||
t.insert("args", value(c.args.iter().collect::<Array>()));
|
||||
}
|
||||
if let Some(module) = &c.extras.module {
|
||||
t.insert("module", value(module));
|
||||
}
|
||||
if let Some(cwd) = &c.cwd {
|
||||
t.insert("cwd", value(cwd.to_string_lossy().replace('\\', "/")));
|
||||
}
|
||||
|
||||
@@ -548,11 +548,11 @@ fn spring_boot_apps(root: &Path, build: &Path, out: &mut Vec<RunConfig>) {
|
||||
Some(m) => format!("application:{m}:{class}"),
|
||||
None => format!("application:{class}"),
|
||||
};
|
||||
out.push(
|
||||
config(id, simple, "spring-boot", "java", &["-cp", "${classpath}", &class])
|
||||
.in_dir(module_rel.as_ref().map(PathBuf::from))
|
||||
.debug("java-debug"),
|
||||
);
|
||||
let mut app = config(id, simple, "spring-boot", "java", &["-cp", "${classpath}", &class])
|
||||
.in_dir(module_rel.as_ref().map(PathBuf::from))
|
||||
.debug("java-debug");
|
||||
app.extras.module = Some(module_rel.clone().unwrap_or_default());
|
||||
out.push(app);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,6 +70,10 @@ fn is_true(b: &bool) -> bool {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RunExtras {
|
||||
/// Module supplying a JVM application's classpath; empty means the project root.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub module: Option<String>,
|
||||
/// Values of the configuration type's own form fields (the command line derives from them).
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(optional)]
|
||||
@@ -137,6 +141,7 @@ pub struct RunExtras {
|
||||
impl Default for RunExtras {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
module: None,
|
||||
params: BTreeMap::new(),
|
||||
folder: None,
|
||||
local: false,
|
||||
|
||||
@@ -234,3 +234,31 @@ fn suppression_round_trip_and_resaving() {
|
||||
assert_eq!(load_suppressed_config_ids(dir.path()).unwrap(), vec![ids[1].clone()]);
|
||||
assert!(fs::read_to_string(dir.path().join(".openidea/.gitignore")).unwrap().contains("/run.local.toml"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_module_is_optional_and_independent_of_working_directory() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = user_configs_path(dir.path());
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(
|
||||
&path,
|
||||
r#"[[configurations]]
|
||||
id = "user:main"
|
||||
name = "Main"
|
||||
kind = "application"
|
||||
command = "java"
|
||||
args = ["-cp", "${classpath}", "a.Main"]
|
||||
cwd = "sibling"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let mut configs = load_user_configs(dir.path()).unwrap();
|
||||
assert_eq!(configs[0].extras.module, None);
|
||||
for module in ["app", ""] {
|
||||
configs[0].extras.module = Some(module.into());
|
||||
save_user_configs(dir.path(), &configs).unwrap();
|
||||
let loaded = load_user_configs(dir.path()).unwrap();
|
||||
assert_eq!(loaded, configs);
|
||||
assert_eq!(loaded[0].cwd.as_deref(), Some(std::path::Path::new("sibling")));
|
||||
}
|
||||
}
|
||||
@@ -216,6 +216,7 @@ fn builds_nested_in_a_folder_of_repositories() {
|
||||
assert_eq!(app.kind, "spring-boot");
|
||||
assert_eq!(cmdline(app), "java -cp ${classpath} org.dromara.DromaraApplication");
|
||||
assert_eq!(app.cwd.as_deref(), Some(Path::new("RuoYi-Vue-Plus/ruoyi-admin")));
|
||||
assert_eq!(app.extras.module.as_deref(), Some("RuoYi-Vue-Plus/ruoyi-admin"));
|
||||
assert_eq!(app.debug_adapter.as_deref(), Some("java-debug"));
|
||||
let package = find(&c, "maven:package:RuoYi-Vue-Plus");
|
||||
assert_eq!(package.name, "RuoYi-Vue-Plus: mvn package");
|
||||
|
||||
@@ -462,6 +462,7 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi
|
||||
fallback: false,
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
tsserver_project: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Finding installed interpreters and toolchains.
|
||||
|
||||
use crate::exec::{query, search_path, which};
|
||||
use crate::exec::{executables_in, query, search_path, which};
|
||||
use crate::{Sdk, SdkKind, bin_dir, exe, home_dir, pinned, venv_of};
|
||||
use ide_core::version_managers::{self, Tool};
|
||||
use std::collections::HashSet;
|
||||
@@ -236,11 +236,32 @@ fn subdirs(dir: &Path) -> Vec<PathBuf> {
|
||||
|
||||
// ------------------------------------------------------------------ node
|
||||
|
||||
/// Node's own version managers, by where they keep installs below the home directory.
|
||||
const NODE_MANAGERS: &[(&str, &str)] =
|
||||
&[(".nvm/versions/node", "nvm"), (".volta/tools/image/node", "volta"), (".local/share/fnm/node-versions", "fnm")];
|
||||
|
||||
/// Where a Node on the search path comes from: its version manager, "system" for one
|
||||
/// of the system's own bin directories, "path" for anything else the user put on `PATH`.
|
||||
pub(crate) fn node_source(path: &Path, home: Option<&Path>) -> &'static str {
|
||||
let managed = home.and_then(|home| {
|
||||
NODE_MANAGERS.iter().find(|(dir, _)| path.starts_with(home.join(dir))).map(|(_, manager)| *manager)
|
||||
});
|
||||
managed.or_else(|| version_managers::manager_of(path)).unwrap_or_else(|| {
|
||||
if path.parent().is_some_and(ide_core::tool_path::is_system_dir) { "system" } else { "path" }
|
||||
})
|
||||
}
|
||||
|
||||
fn node() -> Vec<Sdk> {
|
||||
let mut found: Vec<(PathBuf, &'static str)> = Vec::new();
|
||||
// A mise / asdf shim picks the version by directory: its installs are listed instead.
|
||||
if let Some(p) = which("node").filter(|p| !version_managers::is_shim(p)) {
|
||||
let source = version_managers::manager_of(&p).unwrap_or("path");
|
||||
// Every Node on the search path, not only the first one `which` finds: an SSH
|
||||
// session's minimal PATH puts /usr/bin ahead of the user's own ~/.local/bin, so
|
||||
// /usr/bin/node would be the only install listed (#440).
|
||||
for p in executables_in("node", std::env::split_paths(&search_path())) {
|
||||
// A mise / asdf shim picks the version by directory: its installs are listed instead.
|
||||
if version_managers::is_shim(&p) {
|
||||
continue;
|
||||
}
|
||||
let source = node_source(&p, home_dir().as_deref());
|
||||
found.push((p, source));
|
||||
}
|
||||
if let Some(home) = home_dir() {
|
||||
@@ -257,9 +278,6 @@ fn node() -> Vec<Sdk> {
|
||||
for (v, manager) in version_managers::installs(Tool::Node).into_iter().rev() {
|
||||
found.push((v.join("bin").join(exe("node")), manager));
|
||||
}
|
||||
for p in ["/opt/homebrew/bin/node", "/usr/local/bin/node", "/usr/bin/node"] {
|
||||
found.push((PathBuf::from(p), "system"));
|
||||
}
|
||||
let found = dedupe_by_real_path(found);
|
||||
par_map(&found, |(path, source)| {
|
||||
let version = query(path, &["--version"], VERSION_TIMEOUT)?;
|
||||
|
||||
@@ -26,6 +26,17 @@ pub(crate) fn which(name: &str) -> Option<PathBuf> {
|
||||
ide_core::process::find_executable(name, &path)
|
||||
}
|
||||
|
||||
/// Every install of `name` on `dirs`, one per directory holding it, in `dirs` order (the
|
||||
/// first is what `which` returns). Tool detection lists them all: a login shell's `PATH`
|
||||
/// and an SSH exec channel's minimal one disagree on which comes first (#440).
|
||||
pub(crate) fn executables_in(name: &str, dirs: impl Iterator<Item = PathBuf>) -> Vec<PathBuf> {
|
||||
let pathext = ide_core::process::host_var_os("PATHEXT");
|
||||
let names = ide_core::process::executable_names(name, cfg!(windows), pathext.as_deref().and_then(|p| p.to_str()));
|
||||
dirs.filter(|d| !d.as_os_str().is_empty())
|
||||
.filter_map(|dir| names.iter().map(|n| dir.join(n)).find(|p| p.is_file()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Runs `program args` and returns trimmed stdout (stderr when stdout is empty)
|
||||
/// on success; `None` on failure or after `timeout`.
|
||||
pub(crate) fn query(program: &Path, args: &[&str], timeout: Duration) -> Option<String> {
|
||||
|
||||
@@ -35,6 +35,7 @@ fn server(name: &str) -> LanguageServerConfig {
|
||||
fallback: false,
|
||||
max_java: None,
|
||||
launch_error: None,
|
||||
tsserver_project: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -938,3 +939,31 @@ fn gradle_settings_precedence() {
|
||||
assert_eq!(gradle_command(root, root, &settings), if local { expected } else { wrapper.clone() });
|
||||
}
|
||||
}
|
||||
|
||||
/// The reporter of #440 has Node 26 in `~/.local/bin` and an 18 in `/usr/bin`; an SSH
|
||||
/// exec channel's PATH puts `/usr/bin` first, so only the system's Node was listed.
|
||||
#[test]
|
||||
fn node_lists_every_install_on_the_search_path_not_only_the_first() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (system, user) = (tmp.path().join("usr-bin"), tmp.path().join("local-bin"));
|
||||
for dir in [&system, &user] {
|
||||
std::fs::create_dir(dir).unwrap();
|
||||
std::fs::write(dir.join(exe("node")), "").unwrap();
|
||||
}
|
||||
let found = crate::exec::executables_in("node", [system.clone(), user.clone()].into_iter());
|
||||
assert_eq!(found, [system.join(exe("node")), user.join(exe("node"))]);
|
||||
// A directory without the executable contributes nothing.
|
||||
let found = crate::exec::executables_in("node", [tmp.path().join("empty"), user.clone()].into_iter());
|
||||
assert_eq!(found, [user.join(exe("node"))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_on_the_search_path_keeps_its_version_manager_as_source() {
|
||||
let home = Path::new("/home/me");
|
||||
let source = |p: &str| crate::discover::node_source(Path::new(p), Some(home));
|
||||
assert_eq!(source("/home/me/.nvm/versions/node/v24.0.0/bin/node"), "nvm");
|
||||
assert_eq!(source("/home/me/.volta/tools/image/node/24.0.0/bin/node"), "volta");
|
||||
assert_eq!(source("/home/me/.local/share/fnm/node-versions/v24/installation/bin/node"), "fnm");
|
||||
assert_eq!(source("/home/me/.local/bin/node"), "path");
|
||||
assert_eq!(source("/usr/bin/node"), "system");
|
||||
}
|
||||
@@ -723,6 +723,8 @@ pub(crate) fn push(
|
||||
})
|
||||
.ok_or_else(|| IdeError::invalid("no remote configured"))?;
|
||||
args.extend(["--set-upstream".into(), remote, short]);
|
||||
} else if let Some((remote, target)) = renamed_upstream(r)? {
|
||||
args.extend([remote, format!("HEAD:{target}")]);
|
||||
}
|
||||
let argv: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
cli::run_streaming(r.root(), &argv, cancel, on_output)?;
|
||||
@@ -814,6 +816,23 @@ pub(crate) fn update_branch(
|
||||
}
|
||||
|
||||
/// The remote the current branch pushes to (`origin`, or the only remote, by default).
|
||||
/// The remote and ref HEAD's branch tracks when the ref has another name: a plain
|
||||
/// `git push` refuses that under the default `push.default=simple`.
|
||||
fn renamed_upstream(r: &Repo) -> IdeResult<Option<(String, String)>> {
|
||||
let repo = r.gix()?;
|
||||
let Some(head) = repo.head_name().map_err(gx)? else { return Ok(None) };
|
||||
let direction = gix::remote::Direction::Fetch;
|
||||
let Some(Ok(merge)) = repo.branch_remote_ref_name(head.as_ref(), direction) else { return Ok(None) };
|
||||
if merge.as_ref() == head.as_ref() {
|
||||
return Ok(None);
|
||||
}
|
||||
let target = merge.as_bstr().to_str_lossy().into_owned();
|
||||
let short = head.as_ref().shorten().to_str_lossy().into_owned();
|
||||
Ok(repo
|
||||
.branch_remote_name(short.as_str(), direction)
|
||||
.map(|remote| (remote.as_bstr().to_str_lossy().into_owned(), target)))
|
||||
}
|
||||
|
||||
fn push_remote(r: &Repo) -> IdeResult<String> {
|
||||
let repo = r.gix()?;
|
||||
let from_branch = repo.head_name().map_err(gx)?.and_then(|head| {
|
||||
|
||||
@@ -467,6 +467,32 @@ fn push_with_tags() {
|
||||
assert_eq!(git_in(&bare, &["rev-parse", "main"]), fx.git(&["rev-parse", "HEAD"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_goes_to_an_upstream_with_another_name() {
|
||||
let fx = Fixture::new();
|
||||
let bare = fx._tmp.path().join("origin.git");
|
||||
git_in(fx._tmp.path(), &["init", "-q", "--bare", bare.to_str().unwrap()]);
|
||||
fx.write("a.txt", "1\n");
|
||||
fx.commit_all("one");
|
||||
fx.git(&["remote", "add", "origin", bare.to_str().unwrap()]);
|
||||
fx.git(&["push", "-q", "origin", "main:release/one"]);
|
||||
fx.git(&["fetch", "-q", "origin"]);
|
||||
fx.git(&["checkout", "-q", "-b", "local-name", "--track", "origin/release/one"]);
|
||||
fx.write("a.txt", "2\n");
|
||||
let c2 = fx.commit_all("two");
|
||||
let repo = fx.repo();
|
||||
let (cancel, out) = quiet();
|
||||
|
||||
repo.push(false, false, &cancel, &out).unwrap();
|
||||
assert_eq!(git_in(&bare, &["rev-parse", "release/one"]), c2);
|
||||
assert_eq!(git_in(&bare, &["branch", "--list", "local-name"]), "");
|
||||
|
||||
fx.write("a.txt", "3\n");
|
||||
let c3 = fx.commit_all("three");
|
||||
repo.push_with_tags(false, false, Some(ide_vcs::PushTags::CurrentBranch), &cancel, &out).unwrap();
|
||||
assert_eq!(git_in(&bare, &["rev-parse", "release/one"]), c3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_branch_and_up_to_revision() {
|
||||
let fx = Fixture::new();
|
||||
|
||||
@@ -232,6 +232,12 @@ pub fn save_text(path: &Path, text: &str, encoding: &str, has_bom: bool) -> IdeR
|
||||
pub fn create_file(path: &Path) -> IdeResult<()> {
|
||||
ops::create_file(path)
|
||||
}
|
||||
|
||||
/// Creates a binary file exclusively, including missing parent directories.
|
||||
pub fn create_file_bytes(path: &Path, data: &[u8]) -> IdeResult<()> {
|
||||
ops::create_file_bytes(path, data)
|
||||
}
|
||||
|
||||
/// Creates a directory and missing parents; `AlreadyExists` if present.
|
||||
pub fn create_dir(path: &Path) -> IdeResult<()> {
|
||||
ops::create_dir(path)
|
||||
@@ -310,11 +316,18 @@ pub struct FsBatch {
|
||||
/// refresh as a worktree edit and schedule another `vcs_status` (which
|
||||
/// writes `.git/index` again — an idle refresh loop).
|
||||
pub vcs: Vec<PathBuf>,
|
||||
/// Folders holding changes filtered out as excluded or ignored. Only a view already
|
||||
/// showing such a folder cares, so they don't count as worktree changes.
|
||||
pub excluded_dirs: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl FsBatch {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.created.is_empty() && self.modified.is_empty() && self.removed.is_empty() && self.vcs.is_empty()
|
||||
self.created.is_empty()
|
||||
&& self.modified.is_empty()
|
||||
&& self.removed.is_empty()
|
||||
&& self.vcs.is_empty()
|
||||
&& self.excluded_dirs.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,17 @@ pub(crate) fn create_file(path: &Path) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn create_file_bytes(path: &Path, data: &[u8]) -> IdeResult<()> {
|
||||
use std::io::Write;
|
||||
if exists(path) {
|
||||
return Err(already_exists(path));
|
||||
}
|
||||
ensure_parent(path)?;
|
||||
let mut file = fs::OpenOptions::new().write(true).create_new(true).open(path)?;
|
||||
file.write_all(data)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// IDEA's "Toggle Read-only Attribute": read-only clears every write bit,
|
||||
/// writable adds the owner's.
|
||||
pub(crate) fn set_writable(path: &Path, writable: bool) -> IdeResult<()> {
|
||||
|
||||
@@ -87,6 +87,9 @@ impl Watcher {
|
||||
removed: batch.removed.iter().map(Into::into).collect(),
|
||||
});
|
||||
}
|
||||
if !batch.excluded_dirs.is_empty() {
|
||||
sink.emit(IdeEvent::ExcludedDirsChanged { dirs: batch.excluded_dirs.iter().map(Into::into).collect() });
|
||||
}
|
||||
on_change(batch);
|
||||
};
|
||||
let inner = match mode {
|
||||
@@ -520,6 +523,7 @@ impl EventFilter {
|
||||
}
|
||||
|
||||
let mut batch = FsBatch::default();
|
||||
let mut excluded_dirs = BTreeSet::new();
|
||||
for (path, change) in changes {
|
||||
if change == Change::Vcs {
|
||||
batch.vcs.push(path);
|
||||
@@ -551,10 +555,12 @@ impl EventFilter {
|
||||
// itself — reporting one extra file removal is harmless.
|
||||
let self_excluded = (is_dir || change == Change::Removed)
|
||||
&& (self.excludes.read().is_match(rel) || self.gitignore.is_ignored_self(&path, true));
|
||||
if !self_excluded && self.excludes.read().is_excluded(rel) {
|
||||
continue;
|
||||
}
|
||||
if !self_excluded && self.gitignore.is_ignored(&path, is_dir) {
|
||||
if !self_excluded && (self.excludes.read().is_excluded(rel) || self.gitignore.is_ignored(&path, is_dir))
|
||||
{
|
||||
// Only a file appearing or going changes what the folder lists.
|
||||
if change != Change::Modified {
|
||||
excluded_dirs.extend(path.parent().map(Path::to_path_buf));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -564,6 +570,7 @@ impl EventFilter {
|
||||
_ => batch.modified.push(path),
|
||||
}
|
||||
}
|
||||
batch.excluded_dirs = excluded_dirs.into_iter().collect();
|
||||
(batch, rule_dirs.into_iter().collect())
|
||||
}
|
||||
}
|
||||
@@ -661,7 +668,8 @@ mod tests {
|
||||
ev(create_file, vec![root.join("dist/app.js")]),
|
||||
ev(create_file, vec![root.join("debug.log")]),
|
||||
]);
|
||||
assert!(batch.is_empty(), "{batch:?}");
|
||||
assert!(batch.created.is_empty() && batch.modified.is_empty() && batch.removed.is_empty(), "{batch:?}");
|
||||
assert_eq!(batch.excluded_dirs, vec![root.clone(), root.join("dist"), root.join("target/debug")]);
|
||||
|
||||
// Sibling files in unignored directories still come through.
|
||||
let batch = filter.batch(&[ev(create_file, vec![root.join("src/main.rs")])]);
|
||||
|
||||
@@ -367,3 +367,34 @@ fn worktree_and_nested_repository_local_excludes_are_reflected_in_listings() {
|
||||
let entries = ide_vfs::read_dir(&nested, &[]).unwrap();
|
||||
assert!(entries.iter().find(|e| e.name == "private").unwrap().ignored);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_file_bytes_is_exclusive() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("image.png");
|
||||
let bytes = [0, 255, 128, 10];
|
||||
ide_vfs::create_file_bytes(&path, &bytes).unwrap();
|
||||
let error = ide_vfs::create_file_bytes(&path, b"replacement").unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::AlreadyExists);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_file_bytes_creates_parents() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("nested/assets/image.png");
|
||||
ide_vfs::create_file_bytes(&path, &[0, 255]).unwrap();
|
||||
assert_eq!(std::fs::read(path).unwrap(), [0, 255]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn create_file_bytes_does_not_follow_existing_symlink() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let target = dir.path().join("target.png");
|
||||
let link = dir.path().join("link.png");
|
||||
std::os::unix::fs::symlink(&target, &link).unwrap();
|
||||
let error = ide_vfs::create_file_bytes(&link, b"data").unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::AlreadyExists);
|
||||
assert!(!target.exists());
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
/** Supply detected configurations without launching desktop processes. */
|
||||
async function configure(page: Page, extra = 0) {
|
||||
await page.evaluate(async (extra) => {
|
||||
const storePath = "/src/features/run/store.ts";
|
||||
const projectPath = "/src/platform/project.ts";
|
||||
const { useRun } = await import(storePath);
|
||||
const { useProject } = await import(projectPath);
|
||||
localStorage.setItem(`openidea.services.runTypes:${useProject.getState().project.root}`, '["spring-boot","npm"]');
|
||||
useRun.setState({
|
||||
configs: [
|
||||
["gateway", "spring-boot"],
|
||||
["portal", "spring-boot"],
|
||||
["web", "npm"],
|
||||
["worker", "npm"],
|
||||
...Array.from({ length: extra }, (_, i) => [`app-${i}`, "spring-boot"]),
|
||||
].map(([id, kind]) => ({
|
||||
id,
|
||||
name: id,
|
||||
kind,
|
||||
command: kind,
|
||||
args: [],
|
||||
env: {},
|
||||
cwd: null,
|
||||
detected: true,
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
})),
|
||||
});
|
||||
}, extra);
|
||||
if (!(await page.getByRole("tree", { name: "Services", exact: true }).isVisible()))
|
||||
await page.keyboard.press("Meta+8");
|
||||
await expect(page.getByRole("tree", { name: "Services", exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
async function move(page: Page, source: string, target: string) {
|
||||
const tree = page.getByRole("tree", { name: "Services", exact: true });
|
||||
const sourceRow = tree.getByRole("treeitem", { name: source, exact: true });
|
||||
await sourceRow.click();
|
||||
const from = await sourceRow.boundingBox();
|
||||
const to = await tree.getByRole("treeitem", { name: target, exact: true }).boundingBox();
|
||||
if (!from || !to) throw new Error("Service row is not visible");
|
||||
await page.mouse.move(from.x + 70, from.y + from.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(to.x + 70, to.y + 3, { steps: 8 });
|
||||
await page.mouse.up();
|
||||
}
|
||||
|
||||
test("service pointer ordering works for Java and npm and survives reload", async ({ workbench: page }) => {
|
||||
await configure(page);
|
||||
const tree = page.getByRole("tree", { name: "Services", exact: true });
|
||||
await move(page, "portal", "gateway");
|
||||
await expect(tree.getByRole("treeitem")).toHaveText(["Spring Boot", "portal", "gateway", "npm", "web", "worker"]);
|
||||
await expect(tree.getByRole("treeitem", { name: "portal", exact: true })).toHaveAttribute("aria-selected", "true");
|
||||
await move(page, "worker", "web");
|
||||
await expect(tree.getByRole("treeitem")).toHaveText(["Spring Boot", "portal", "gateway", "npm", "worker", "web"]);
|
||||
await page.reload();
|
||||
await expect(page.getByRole("tree", { name: "Project" })).toBeVisible();
|
||||
await configure(page);
|
||||
await expect(tree.getByRole("treeitem")).toHaveText(["Spring Boot", "portal", "gateway", "npm", "worker", "web"]);
|
||||
await tree.getByRole("treeitem", { name: "web", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Move Up", exact: true }).click();
|
||||
await expect(tree.getByRole("treeitem")).toHaveText(["Spring Boot", "portal", "gateway", "npm", "web", "worker"]);
|
||||
});
|
||||
|
||||
test("service dragging scrolls across virtual rows without losing source identity", async ({ workbench: page }) => {
|
||||
await configure(page, 100);
|
||||
const tree = page.getByRole("tree", { name: "Services", exact: true });
|
||||
const source = tree.getByRole("treeitem", { name: "portal", exact: true });
|
||||
await source.click();
|
||||
const from = await source.boundingBox();
|
||||
const bounds = await tree.boundingBox();
|
||||
if (!from || !bounds) throw new Error("Service rows are not visible");
|
||||
await page.mouse.move(from.x + 70, from.y + from.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(bounds.x + 100, bounds.y + bounds.height - 5, { steps: 8 });
|
||||
await expect.poll(() => tree.evaluate((el) => el.scrollTop)).toBeGreaterThan(1000);
|
||||
const target = tree.getByRole("treeitem", { name: "app-99", exact: true });
|
||||
await target.scrollIntoViewIfNeeded();
|
||||
const to = await target.boundingBox();
|
||||
if (!to) throw new Error("Drop target is not visible");
|
||||
await page.mouse.move(to.x + 70, to.y + to.height - 3);
|
||||
await page.mouse.up();
|
||||
await expect(source).toHaveAttribute("aria-selected", "true");
|
||||
await expect
|
||||
.poll(() =>
|
||||
page.evaluate(() => {
|
||||
const key = Object.keys(localStorage).find((k) => k.startsWith("openidea.services.runOrder:"));
|
||||
return key ? JSON.parse(localStorage.getItem(key)!)["spring-boot"].slice(-2) : [];
|
||||
}),
|
||||
)
|
||||
.toEqual(["app-99", "portal"]);
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { useState } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { Tree } from "../src/ui/Tree";
|
||||
|
||||
interface Node {
|
||||
key: string;
|
||||
label: string;
|
||||
children?: Node[];
|
||||
}
|
||||
const longLabel = `z_${"long_file_name_".repeat(16)}.ts`;
|
||||
const initial: Node[] = [
|
||||
{ key: "src", label: "src", children: [{ key: "child", label: "child.ts" }] },
|
||||
...Array.from({ length: 160 }, (_, i) => ({ key: `file-${i}`, label: `file_${i}.ts` })),
|
||||
{ key: "wide", label: longLabel },
|
||||
];
|
||||
const shorten = (nodes: Node[]): Node[] =>
|
||||
nodes.map((node) => ({
|
||||
...node,
|
||||
label: node.key === "wide" ? "short.ts" : node.label,
|
||||
children: node.children ? shorten(node.children) : undefined,
|
||||
}));
|
||||
const getKey = (node: Node) => node.key;
|
||||
const getLabel = (node: Node) => node.label;
|
||||
const getChildren = (node: Node) => node.children;
|
||||
const isExpandable = (node: Node) => !!node.children;
|
||||
|
||||
function Fixture() {
|
||||
const [roots, setRoots] = useState(initial);
|
||||
const [width, setWidth] = useState(240);
|
||||
const [font, setFont] = useState(14);
|
||||
const [indent, setIndent] = useState(16);
|
||||
const [hidden, setHidden] = useState(false);
|
||||
const [horizontal, setHorizontal] = useState(true);
|
||||
return (
|
||||
<>
|
||||
<style>{`* { box-sizing: border-box; } body { font-family: monospace; } button { margin: 4px; }`}</style>
|
||||
<button onClick={() => setRoots((nodes) => nodes.filter((node) => node.key !== "wide"))}>Delete widest</button>
|
||||
<button onClick={() => setRoots(shorten)}>Shorten same key</button>
|
||||
<button onClick={() => setRoots((nodes) => [{ key: "folder", label: "folder", children: nodes }])}>
|
||||
Nest rows
|
||||
</button>
|
||||
<button onClick={() => setWidth((value) => (value === 240 ? 2400 : 240))}>Resize panel</button>
|
||||
<button onClick={() => setFont((value) => (value === 14 ? 20 : 14))}>Change font</button>
|
||||
<button onClick={() => setIndent((value) => (value === 16 ? 40 : 16))}>Change indent</button>
|
||||
<button onClick={() => setHorizontal((value) => !value)}>Toggle horizontal</button>
|
||||
<button onClick={() => setHidden((value) => !value)}>Toggle visibility</button>
|
||||
<div hidden={hidden} style={{ width, height: 300, fontSize: font }}>
|
||||
<Tree
|
||||
aria-label="Width fixture"
|
||||
roots={roots}
|
||||
getKey={getKey}
|
||||
getLabel={getLabel}
|
||||
getChildren={getChildren}
|
||||
isExpandable={isExpandable}
|
||||
defaultExpanded={["folder"]}
|
||||
horizontalScroll={horizontal}
|
||||
indent={indent}
|
||||
speedSearchMode="filter"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
createRoot(document.getElementById("root")!).render(<Fixture />);
|
||||
@@ -0,0 +1,11 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Tree width regression</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/e2e/treeWidth.fixture.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,158 @@
|
||||
import { expect, test, type Locator, type Page } from "@playwright/test";
|
||||
|
||||
const metrics = (tree: Locator) =>
|
||||
tree.evaluate((node) => ({ width: node.scrollWidth, left: node.scrollLeft, viewport: node.clientWidth }));
|
||||
async function open(page: Page) {
|
||||
await page.goto("/e2e/treeWidth.html");
|
||||
const tree = page.getByRole("tree", { name: "Width fixture" });
|
||||
await expect(tree.getByRole("treeitem", { name: "src", exact: true })).toBeVisible();
|
||||
return tree;
|
||||
}
|
||||
async function wheel(page: Page, tree: Locator, x: number, y: number) {
|
||||
await tree.hover();
|
||||
await page.mouse.wheel(x, y);
|
||||
await expect
|
||||
.poll(async () => tree.evaluate((node) => node.scrollTop === node.scrollHeight - node.clientHeight))
|
||||
.toBe(y > 0);
|
||||
if (y < 0) await expect.poll(async () => tree.evaluate((node) => node.scrollTop)).toBe(0);
|
||||
}
|
||||
async function measureLong(page: Page, tree: Locator) {
|
||||
await tree.getByRole("treeitem", { name: "src", exact: true }).click();
|
||||
await wheel(page, tree, 0, 10000);
|
||||
await expect(tree.getByRole("treeitem", { name: /^z_long/ })).toBeVisible();
|
||||
await page.mouse.wheel(200, 0);
|
||||
await expect.poll(async () => (await metrics(tree)).left).toBe(200);
|
||||
return metrics(tree);
|
||||
}
|
||||
|
||||
test("keeps offscreen width when an unrelated directory expands, without transient clamping", async ({ page }) => {
|
||||
const tree = await open(page);
|
||||
const before = await measureLong(page, tree);
|
||||
await wheel(page, tree, 0, -10000);
|
||||
await expect(tree.getByRole("treeitem", { name: /^z_long/ })).toHaveCount(0);
|
||||
expect(await metrics(tree)).toEqual(before);
|
||||
await tree.evaluate((node) => {
|
||||
const samples: number[] = [];
|
||||
Object.assign(window, { widthSamples: samples });
|
||||
let frames = 0;
|
||||
const sample = () => {
|
||||
samples.push(node.scrollLeft);
|
||||
if (++frames < 30) requestAnimationFrame(sample);
|
||||
};
|
||||
requestAnimationFrame(sample);
|
||||
});
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(tree.getByRole("treeitem", { name: "src", exact: true })).toHaveAttribute("aria-expanded", "true");
|
||||
await expect
|
||||
.poll(async () => page.evaluate(() => (window as unknown as { widthSamples: number[] }).widthSamples.length))
|
||||
.toBe(30);
|
||||
const after = await metrics(tree);
|
||||
expect(after).toEqual(before);
|
||||
expect(await page.evaluate(() => Math.min(...(window as unknown as { widthSamples: number[] }).widthSamples))).toBe(
|
||||
200,
|
||||
);
|
||||
});
|
||||
|
||||
test("deleting, collapsing and filtering the widest row allow shrinkage", async ({ page }) => {
|
||||
let tree = await open(page);
|
||||
await measureLong(page, tree);
|
||||
await wheel(page, tree, 0, -10000);
|
||||
await page.getByRole("button", { name: "Delete widest" }).click();
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBe(240);
|
||||
tree = await open(page);
|
||||
await measureLong(page, tree);
|
||||
await wheel(page, tree, 0, -10000);
|
||||
await page.getByRole("button", { name: "Nest rows" }).click();
|
||||
await tree.getByRole("treeitem", { name: "folder", exact: true }).click();
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBe(240);
|
||||
tree = await open(page);
|
||||
await measureLong(page, tree);
|
||||
await page.keyboard.type("src");
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBe(240);
|
||||
});
|
||||
|
||||
test("same-key content, depth, font and indent are remeasured", async ({ page }) => {
|
||||
const tree = await open(page);
|
||||
const initial = await measureLong(page, tree);
|
||||
// An external style/font update need not cause a React render.
|
||||
const fontStyle = await page.addStyleTag({ content: '[role="tree"] { font-size: 20px; }' });
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBeGreaterThan(initial.width);
|
||||
await fontStyle.evaluate((node) => node.parentNode!.removeChild(node));
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBe(initial.width);
|
||||
await page.getByRole("button", { name: "Change font" }).click();
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBeGreaterThan(initial.width);
|
||||
await page.getByRole("button", { name: "Change font" }).click();
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBe(initial.width);
|
||||
await page.getByRole("button", { name: "Nest rows" }).click();
|
||||
await tree.focus();
|
||||
await page.keyboard.press("End");
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBe(initial.width + 16);
|
||||
await page.getByRole("button", { name: "Change indent" }).click();
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBe(initial.width + 40);
|
||||
await page.getByRole("button", { name: "Shorten same key" }).click();
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBe(240);
|
||||
});
|
||||
|
||||
test("panel resizing does not cache the viewport floor, and horizontal mode can be disabled", async ({ page }) => {
|
||||
const tree = await open(page);
|
||||
await page.getByRole("button", { name: "Resize panel" }).click();
|
||||
await expect.poll(async () => (await metrics(tree)).viewport).toBe(2400);
|
||||
await wheel(page, tree, 0, 10000);
|
||||
await wheel(page, tree, 0, -10000);
|
||||
await page.getByRole("button", { name: "Resize panel" }).click();
|
||||
await expect.poll(async () => (await metrics(tree)).viewport).toBe(240);
|
||||
expect((await metrics(tree)).width).toBeLessThan(2400);
|
||||
expect((await metrics(tree)).width).toBeGreaterThan(240);
|
||||
await page.getByRole("button", { name: "Toggle horizontal" }).click();
|
||||
await expect(tree.locator("[data-content-width]")).toHaveCount(0);
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBe(240);
|
||||
await wheel(page, tree, 0, 10000);
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBe(240);
|
||||
await page.getByRole("button", { name: "Shorten same key" }).click();
|
||||
await page.getByRole("button", { name: "Toggle horizontal" }).click();
|
||||
await expect(tree.locator("[data-content-width]")).toHaveCount(1);
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBe(240);
|
||||
});
|
||||
|
||||
test("offscreen same-key updates remain estimates until the row is mounted again", async ({ page }) => {
|
||||
const tree = await open(page);
|
||||
const before = await measureLong(page, tree);
|
||||
await wheel(page, tree, 0, -10000);
|
||||
await page.getByRole("button", { name: "Shorten same key" }).click();
|
||||
expect(await metrics(tree)).toEqual(before);
|
||||
await wheel(page, tree, 0, 10000);
|
||||
await expect(tree.getByRole("treeitem", { name: "short.ts", exact: true })).toBeVisible();
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBe(240);
|
||||
await wheel(page, tree, 0, -10000);
|
||||
await page.getByRole("button", { name: "Resize panel" }).click();
|
||||
await wheel(page, tree, 0, 10000);
|
||||
await page.getByRole("button", { name: "Resize panel" }).click();
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBe(240);
|
||||
});
|
||||
|
||||
test("hidden trees keep their widths and reconcile pending removals when shown", async ({ page }) => {
|
||||
await open(page);
|
||||
const tree = page.getByRole("tree", { name: "Width fixture", includeHidden: true });
|
||||
const before = await measureLong(page, tree);
|
||||
const spacer = tree.locator("[data-content-width]");
|
||||
const stored = await spacer.evaluate((node) => (node as HTMLElement).style.width);
|
||||
await page.getByRole("button", { name: "Toggle visibility" }).click();
|
||||
await expect(tree).toBeHidden();
|
||||
// Give ResizeObserver deliveries a chance to run while there is no layout.
|
||||
await page.evaluate(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
|
||||
}),
|
||||
);
|
||||
expect(await spacer.evaluate((node) => (node as HTMLElement).style.width)).toBe(stored);
|
||||
await page.getByRole("button", { name: "Toggle visibility" }).click();
|
||||
await expect(tree).toBeVisible();
|
||||
await expect.poll(() => metrics(tree)).toEqual(before);
|
||||
await page.getByRole("button", { name: "Toggle visibility" }).click();
|
||||
await page.getByRole("button", { name: "Delete widest" }).click();
|
||||
await page.getByRole("button", { name: "Change indent" }).click();
|
||||
await page.getByRole("button", { name: "Toggle visibility" }).click();
|
||||
await expect.poll(async () => (await metrics(tree)).width).toBe(240);
|
||||
});
|
||||
@@ -11,6 +11,8 @@ name = "fsautocomplete"
|
||||
command = "fsautocomplete"
|
||||
root-markers = ["*.sln", "*.fsproj", "global.json"]
|
||||
install-hint = "dotnet tool install --global fsautocomplete"
|
||||
# Otherwise it waits for the client to load the project through `fsharp/workspaceLoad`.
|
||||
initialization-options = { AutomaticWorkspaceInit = true }
|
||||
|
||||
[debugger]
|
||||
adapter = "netcoredbg"
|
||||
|
||||
@@ -10,6 +10,7 @@ tree-sitter = "javascript"
|
||||
|
||||
[[language-servers]]
|
||||
name = "vtsls"
|
||||
tsserver-project = true
|
||||
command = "vtsls"
|
||||
args = ["--stdio"]
|
||||
root-markers = ["jsconfig.json", "tsconfig.json", "package.json"]
|
||||
@@ -17,6 +18,7 @@ install-hint = "npm i -g @vtsls/language-server"
|
||||
|
||||
[[language-servers]]
|
||||
name = "typescript-language-server"
|
||||
tsserver-project = true
|
||||
# Alternative: used only when the server above is not installed.
|
||||
fallback = true
|
||||
command = "typescript-language-server"
|
||||
|
||||
@@ -9,6 +9,7 @@ tree-sitter = "javascript"
|
||||
|
||||
[[language-servers]]
|
||||
name = "vtsls"
|
||||
tsserver-project = true
|
||||
command = "vtsls"
|
||||
args = ["--stdio"]
|
||||
root-markers = ["jsconfig.json", "tsconfig.json", "package.json"]
|
||||
@@ -16,6 +17,7 @@ install-hint = "npm i -g @vtsls/language-server"
|
||||
|
||||
[[language-servers]]
|
||||
name = "typescript-language-server"
|
||||
tsserver-project = true
|
||||
# Alternative: used only when the server above is not installed.
|
||||
fallback = true
|
||||
command = "typescript-language-server"
|
||||
|
||||
@@ -9,6 +9,7 @@ tree-sitter = "typescript"
|
||||
|
||||
[[language-servers]]
|
||||
name = "vtsls"
|
||||
tsserver-project = true
|
||||
command = "vtsls"
|
||||
args = ["--stdio"]
|
||||
root-markers = ["tsconfig.json", "jsconfig.json", "package.json"]
|
||||
@@ -16,6 +17,7 @@ install-hint = "npm i -g @vtsls/language-server"
|
||||
|
||||
[[language-servers]]
|
||||
name = "typescript-language-server"
|
||||
tsserver-project = true
|
||||
# Alternative: used only when the server above is not installed.
|
||||
fallback = true
|
||||
command = "typescript-language-server"
|
||||
|
||||
@@ -9,6 +9,7 @@ tree-sitter = "tsx"
|
||||
|
||||
[[language-servers]]
|
||||
name = "vtsls"
|
||||
tsserver-project = true
|
||||
command = "vtsls"
|
||||
args = ["--stdio"]
|
||||
root-markers = ["tsconfig.json", "jsconfig.json", "package.json"]
|
||||
@@ -16,6 +17,7 @@ install-hint = "npm i -g @vtsls/language-server"
|
||||
|
||||
[[language-servers]]
|
||||
name = "typescript-language-server"
|
||||
tsserver-project = true
|
||||
# Alternative: used only when the server above is not installed.
|
||||
fallback = true
|
||||
command = "typescript-language-server"
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.28",
|
||||
"version": "0.1.29",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -19,6 +19,12 @@ pub fn fs_create_file(window: Window, state: State<'_, AppState>, path: PathBuf)
|
||||
fs::create_file(&state.host, window.label(), path)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn fs_create_file_bytes(state: State<'_, AppState>, path: PathBuf, data: Vec<u8>) -> IdeResult<()> {
|
||||
fs::create_file_bytes(&state.host, path, data).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn fs_create_dir(path: PathBuf) -> IdeResult<()> {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use crate::state::AppState;
|
||||
use ide_core::{IdeError, IdeResult, RequestId};
|
||||
use ide_github::{
|
||||
CreatePullRequest, GhAvailability, PrDiffRevisions, PrListQuery, PrReviewComment, PullRequestDetails,
|
||||
CreatePullRequest, GhApiRequest, GhAvailability, PrDiffRevisions, PrListQuery, PrReviewComment, PullRequestDetails,
|
||||
PullRequestSummary, ReviewEvent,
|
||||
};
|
||||
use std::path::PathBuf;
|
||||
@@ -128,6 +128,14 @@ pub async fn gh_pr_comment(window: Window, state: State<'_, AppState>, number: u
|
||||
blocking(move || ide_github::add_comment(&root, number, &body)).await
|
||||
}
|
||||
|
||||
/// A GitHub GraphQL / REST call through `gh api`; returns the response body.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn gh_api(window: Window, state: State<'_, AppState>, request: GhApiRequest) -> IdeResult<String> {
|
||||
let root = root(&window, &state)?;
|
||||
blocking(move || ide_github::api(&root, &request)).await
|
||||
}
|
||||
|
||||
/// Fetches what is missing to diff a pull request locally; returns the revisions to compare.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
|
||||
@@ -126,6 +126,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
bytes::fs_read_range,
|
||||
bytes::fs_read_image,
|
||||
fs::fs_create_file,
|
||||
fs::fs_create_file_bytes,
|
||||
fs::fs_create_dir,
|
||||
fs::fs_rename,
|
||||
fs::fs_set_writable,
|
||||
@@ -265,6 +266,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
vcs::vcs_remove_worktree,
|
||||
vcs::vcs_diff_with_worktree,
|
||||
vcs::vcs_diff_revisions,
|
||||
vcs::vcs_merge_base,
|
||||
vcs::vcs_create_patch,
|
||||
vcs::vcs_patch_preview,
|
||||
vcs::vcs_apply_patch,
|
||||
@@ -340,6 +342,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
sdk::sdk_python_pip,
|
||||
window::window_open_project,
|
||||
window::window_open_files,
|
||||
window::window_open_file_in_new_window,
|
||||
window::window_open_remote,
|
||||
window::window_new,
|
||||
window::window_open_settings,
|
||||
@@ -414,6 +417,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
docker::docker_registry_login,
|
||||
docker::docker_run_env,
|
||||
github::gh_availability,
|
||||
github::gh_api,
|
||||
github::gh_pr_list,
|
||||
github::gh_pr_view,
|
||||
github::gh_pr_review_comments,
|
||||
|
||||
@@ -535,6 +535,19 @@ pub async fn vcs_diff_revisions(
|
||||
ide_host::ops::vcs::vcs_diff_revisions(&state.host, window.label(), repo, from, to).await
|
||||
}
|
||||
|
||||
/// The best common ancestor of `a` and `b` (`git merge-base`), if any.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_merge_base(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
repo: Option<PathBuf>,
|
||||
a: String,
|
||||
b: String,
|
||||
) -> IdeResult<Option<String>> {
|
||||
ide_host::ops::vcs::vcs_merge_base(&state.host, window.label(), repo, a, b).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn vcs_create_patch(
|
||||
|
||||
@@ -39,6 +39,19 @@ pub async fn window_open_files(
|
||||
Ok(windows::open_files_window(&app, window.label(), files))
|
||||
}
|
||||
|
||||
/// Detaches an editor tab: opens `file` in a forced new window (`project`, None
|
||||
/// for LightEdit, decided by the caller), bypassing the focus-an-existing-window
|
||||
/// routing of [`window_open_project`] / [`window_open_files`].
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn window_open_file_in_new_window(
|
||||
app: AppHandle,
|
||||
project: Option<PathBuf>,
|
||||
file: PathBuf,
|
||||
) -> IdeResult<OpenOutcome> {
|
||||
windows::open_file_in_new_window(&app, project, file)
|
||||
}
|
||||
|
||||
/// [`window_open_project`] for folder `path` on the host of SSH configuration
|
||||
/// `ssh_config` (Remote Development); a new window connects itself.
|
||||
#[tauri::command]
|
||||
|
||||
@@ -411,6 +411,16 @@ pub fn open_project_window(
|
||||
Ok(OpenOutcome::Opened { label: window.label().to_owned() })
|
||||
}
|
||||
|
||||
/// Opens `file` in a forced new window: `project` (None: LightEdit) plus the
|
||||
/// single file, always creating a window even when the project is already open
|
||||
/// in another one (unlike [`open_project_window`], which focuses it). Used to
|
||||
/// detach an editor tab out of its window.
|
||||
pub fn open_file_in_new_window(app: &AppHandle, project: Option<PathBuf>, file: PathBuf) -> IdeResult<OpenOutcome> {
|
||||
tracing::info!("open_file_in_new_window {} project={:?}", file.display(), project);
|
||||
let window = create_window_with(app, project, vec![file])?;
|
||||
Ok(OpenOutcome::Opened { label: window.label().to_owned() })
|
||||
}
|
||||
|
||||
/// Loose local `files` asked for by window `caller` (File | Open File, a drop on the Welcome
|
||||
/// screen), routed like [`open_paths`]; returns the files `caller` opens itself.
|
||||
pub fn open_files_window(app: &AppHandle, caller: &str, files: Vec<PathBuf>) -> Vec<ide_core::IpcPath> {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.28",
|
||||
"version": "0.1.29",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
@@ -30,7 +30,7 @@
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src 'self'; img-src 'self' asset: data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src ipc: http://ipc.localhost; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:; frame-src http://127.0.0.1:*"
|
||||
"csp": "default-src 'self'; img-src 'self' asset: data: blob: https://avatars.githubusercontent.com; style-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src ipc: http://ipc.localhost; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:; frame-src http://127.0.0.1:*"
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
|
||||
@@ -151,6 +151,7 @@ export const commands = {
|
||||
* `charset` (writes the BOM for `utf-8-bom` / UTF-16).
|
||||
*/
|
||||
fsCreateFile: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_file", { path })),
|
||||
fsCreateFileBytes: (path: string, data: number[]) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_file_bytes", { path, data })),
|
||||
fsCreateDir: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_dir", { path })),
|
||||
fsRename: (from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_rename", { from, to })),
|
||||
/**
|
||||
@@ -503,6 +504,8 @@ export const commands = {
|
||||
vcsDiffWithWorktree: (repo: string | null, rev: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_diff_with_worktree", { repo, rev })),
|
||||
/** Files that differ between two revisions (the "N files updated" of Update Project). */
|
||||
vcsDiffRevisions: (repo: string | null, from: string, to: string) => typedError<ChangedFile[], IdeError>(__TAURI_INVOKE("vcs_diff_revisions", { repo, from, to })),
|
||||
/** The best common ancestor of `a` and `b` (`git merge-base`), if any. */
|
||||
vcsMergeBase: (repo: string | null, a: string, b: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("vcs_merge_base", { repo, a, b })),
|
||||
vcsCreatePatch: (repo: string | null, source: PatchSource) => typedError<string, IdeError>(__TAURI_INVOKE("vcs_create_patch", { repo, source })),
|
||||
vcsPatchPreview: (repo: string | null, patch: string) => typedError<PatchFile[], IdeError>(__TAURI_INVOKE("vcs_patch_preview", { repo, patch })),
|
||||
vcsApplyPatch: (repo: string | null, patch: string) => typedError<ApplyOutcome, IdeError>(__TAURI_INVOKE("vcs_apply_patch", { repo, patch })),
|
||||
@@ -686,6 +689,12 @@ export const commands = {
|
||||
* itself, in LightEdit.
|
||||
*/
|
||||
windowOpenFiles: (files: string[]) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("window_open_files", { files })),
|
||||
/**
|
||||
* Detaches an editor tab: opens `file` in a forced new window (`project`, None
|
||||
* for LightEdit, decided by the caller), bypassing the focus-an-existing-window
|
||||
* routing of [`window_open_project`] / [`window_open_files`].
|
||||
*/
|
||||
windowOpenFileInNewWindow: (project: string | null, file: string) => typedError<OpenOutcome, IdeError>(__TAURI_INVOKE("window_open_file_in_new_window", { project, file })),
|
||||
/**
|
||||
* [`window_open_project`] for folder `path` on the host of SSH configuration
|
||||
* `ssh_config` (Remote Development); a new window connects itself.
|
||||
@@ -891,6 +900,8 @@ export const commands = {
|
||||
*/
|
||||
dockerRunEnv: (endpoint: DockerEndpoint) => typedError<{ [key in string]: string }, IdeError>(__TAURI_INVOKE("docker_run_env", { endpoint })),
|
||||
ghAvailability: () => typedError<GhAvailability, IdeError>(__TAURI_INVOKE("gh_availability")),
|
||||
/** A GitHub GraphQL / REST call through `gh api`; returns the response body. */
|
||||
ghApi: (request: GhApiRequest) => typedError<string, IdeError>(__TAURI_INVOKE("gh_api", { request })),
|
||||
ghPrList: (query: PrListQuery) => typedError<PullRequestSummary[], IdeError>(__TAURI_INVOKE("gh_pr_list", { query })),
|
||||
ghPrView: (number: number) => typedError<PullRequestDetails, IdeError>(__TAURI_INVOKE("gh_pr_view", { number })),
|
||||
ghPrReviewComments: (number: number) => typedError<PrReviewComment[], IdeError>(__TAURI_INVOKE("gh_pr_review_comments", { number })),
|
||||
@@ -2690,6 +2701,8 @@ export type EditorConfigProps = {
|
||||
export type EditorGeneralSettings = {
|
||||
/** Change font size with ⌘ + mouse wheel. */
|
||||
wheelZoom?: boolean,
|
||||
markdownImageFolder?: string,
|
||||
markdownImageNamePattern?: string,
|
||||
/** Drag-and-drop of selected text inside the editor. */
|
||||
dragAndDrop?: boolean,
|
||||
/** When the caret moves out of view: `minimize` scrolling | `center` the caret line. */
|
||||
@@ -3115,6 +3128,21 @@ export type GeneralSettings = {
|
||||
projectName?: string,
|
||||
};
|
||||
|
||||
/**
|
||||
* A GitHub API call through `gh api`: GraphQL (`endpoint` `graphql`, `body`
|
||||
* `{"query", "variables"}`) or REST (`repos/{owner}/{repo}/…`, gh fills in the
|
||||
* placeholders from the project's remote).
|
||||
*/
|
||||
export type GhApiRequest = {
|
||||
/** `GET`, `POST`, `PATCH`, `PUT`, `DELETE`. */
|
||||
method: string,
|
||||
endpoint: string,
|
||||
/** JSON request body, sent on stdin. */
|
||||
body: string | null,
|
||||
/** Follow REST `Link` pages; the result is the array of all pages (`--slurp`). */
|
||||
paginate: boolean,
|
||||
};
|
||||
|
||||
/** Whether pull requests can be shown for the project, and why not. */
|
||||
export type GhAvailability = { kind: "ready"; repo: GhRepo;
|
||||
/** The signed-in user. */
|
||||
@@ -3131,6 +3159,12 @@ export type GhRepo = {
|
||||
nameWithOwner: string,
|
||||
url: string,
|
||||
defaultBranch: string | null,
|
||||
/** Merge methods the repository allows (all of them when gh does not say). */
|
||||
mergeCommitAllowed: boolean,
|
||||
squashMergeAllowed: boolean,
|
||||
rebaseMergeAllowed: boolean,
|
||||
/** The signed-in user's permission: `ADMIN`, `MAINTAIN`, `WRITE`, `TRIAGE`, `READ`; empty when unknown. */
|
||||
viewerPermission: string,
|
||||
};
|
||||
|
||||
export type GitExecutableInfo = {
|
||||
@@ -3373,6 +3407,8 @@ export type IdeEvent =
|
||||
{ type: "windowGroupsChanged" } |
|
||||
/** Files or directories changed on disk (after debouncing, ignore rules applied). */
|
||||
{ type: "fsChanged"; created: IpcPath[]; modified: IpcPath[]; removed: IpcPath[] } |
|
||||
/** Excluded or ignored folders whose contents changed; they stay out of `FsChanged`. */
|
||||
{ type: "excludedDirsChanged"; dirs: IpcPath[] } |
|
||||
/**
|
||||
* The backend changed a document (reload from disk, formatting, refactoring).
|
||||
* The UI applies `changes` on top of `base_version`, yielding `version`.
|
||||
@@ -4737,6 +4773,8 @@ export type PullRequestDetails = {
|
||||
baseOid: string,
|
||||
/** `MERGEABLE`, `CONFLICTING`, `UNKNOWN`. */
|
||||
mergeable: string,
|
||||
/** GitHub's merge box state: `CLEAN`, `UNSTABLE`, `HAS_HOOKS`, `BLOCKED`, `BEHIND`, `DIRTY`, `DRAFT`, `UNKNOWN`. */
|
||||
mergeStateStatus: string,
|
||||
isCrossRepository: boolean,
|
||||
mergedAt: string | null,
|
||||
closedAt: string | null,
|
||||
@@ -5070,6 +5108,8 @@ export type RunConfig_Serialize = {
|
||||
export type RunExtras = RunExtras_Serialize | RunExtras_Deserialize;
|
||||
|
||||
export type RunExtras_Deserialize = {
|
||||
/** Module supplying a JVM application's classpath; empty means the project root. */
|
||||
module?: string | null,
|
||||
/** Values of the configuration type's own form fields (the command line derives from them). */
|
||||
params?: { [key in string]: string },
|
||||
/** Folder in the Run/Debug Configurations tree. */
|
||||
@@ -5107,6 +5147,8 @@ export type RunExtras_Deserialize = {
|
||||
};
|
||||
|
||||
export type RunExtras_Serialize = {
|
||||
/** Module supplying a JVM application's classpath; empty means the project root. */
|
||||
module?: string | null,
|
||||
/** Values of the configuration type's own form fields (the command line derives from them). */
|
||||
params?: { [key in string]: string },
|
||||
/** Folder in the Run/Debug Configurations tree. */
|
||||
|
||||
@@ -276,6 +276,33 @@ export class LaneMarker extends GutterMarker {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The floating row at the editor's top-right (IDEA's inspection widget area): widgets
|
||||
* append their element to it (CSS `order` sorts them; lower first) and remove it when
|
||||
* done. The inspection widget sits there; code review adds its Review Mode group.
|
||||
*
|
||||
* const el = document.createElement("div");
|
||||
* el.style.order = "-1";
|
||||
* editorCorner(view).appendChild(el);
|
||||
*/
|
||||
export function editorCorner(view: EditorView): HTMLElement {
|
||||
const found = view.dom.querySelector<HTMLElement>(":scope > .cm-openidea-corner");
|
||||
if (found) return found;
|
||||
const el = document.createElement("div");
|
||||
el.className = "cm-openidea-corner";
|
||||
Object.assign(el.style, {
|
||||
position: "absolute",
|
||||
top: "4px",
|
||||
right: "16px",
|
||||
zIndex: "5",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "4px",
|
||||
});
|
||||
view.dom.appendChild(el);
|
||||
return el;
|
||||
}
|
||||
|
||||
// --- language support without a language server ----------------------------------
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
// Keep binary conversion off the editor thread, including for large clipboard images.
|
||||
self.onmessage = async (event: MessageEvent<Blob | string>) => {
|
||||
try {
|
||||
const source = event.data;
|
||||
const data =
|
||||
typeof source === "string"
|
||||
? Array.from(atob(source.slice(source.indexOf(",") + 1)), (byte) => byte.charCodeAt(0))
|
||||
: Array.from(new Uint8Array(await source.arrayBuffer()));
|
||||
self.postMessage({ data });
|
||||
} catch (error) {
|
||||
self.postMessage({ error: String(error) });
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,132 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { history, undo } from "@codemirror/commands";
|
||||
import { IpcError, commands } from "@/platform/ipc";
|
||||
import { imageName, imageTarget, markdownImages, relativeImagePath, saveImage } from "./markdownImages";
|
||||
|
||||
const views: EditorView[] = [];
|
||||
afterEach(() => {
|
||||
views.splice(0).forEach((view) => view.destroy());
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
function view(path = "/project/docs/readme.md") {
|
||||
const editor = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "before after",
|
||||
selection: { anchor: 7 },
|
||||
extensions: [history(), markdownImages({ path, folder: "assets", pattern: "image-{timestamp}" })],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(editor);
|
||||
return editor;
|
||||
}
|
||||
function paste(editor: EditorView, files: File[]) {
|
||||
const event = new Event("paste", { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(event, "clipboardData", { value: { files, getData: () => "plain text" } });
|
||||
editor.contentDOM.dispatchEvent(event);
|
||||
return event;
|
||||
}
|
||||
|
||||
describe("Markdown images", () => {
|
||||
it("retries exclusive name collisions without overwriting", async () => {
|
||||
const create = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new IpcError({ kind: "alreadyExists", message: "exists" }))
|
||||
.mockRejectedValueOnce(new IpcError({ kind: "alreadyExists", message: "exists" }))
|
||||
.mockResolvedValue(null);
|
||||
expect(await saveImage("/p/docs/readme.md", "assets", "photo.png", [0, 255], create)).toBe(
|
||||
"",
|
||||
);
|
||||
expect(create.mock.calls.map(([path]) => path)).toEqual([
|
||||
"/p/docs/assets/photo.png",
|
||||
"/p/docs/assets/photo-1.png",
|
||||
"/p/docs/assets/photo-2.png",
|
||||
]);
|
||||
});
|
||||
it("does not retry permission failures", async () => {
|
||||
const create = vi.fn().mockRejectedValue(new IpcError({ kind: "permissionDenied", message: "denied" }));
|
||||
await expect(saveImage("/p/a.md", "assets", "a.png", [], create)).rejects.toThrow("denied");
|
||||
expect(create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("computes nested paths and encodes spaces and Markdown delimiters", () => {
|
||||
const target = imageTarget("/p/docs/nested/read me.md", "../../my assets", "a (1)#图.png");
|
||||
expect(target).toBe("/p/my assets/a (1)#图.png");
|
||||
expect(relativeImagePath("/p/docs/nested/read me.md", target)).toBe(
|
||||
"../../my%20assets/a%20%281%29%23%E5%9B%BE.png",
|
||||
);
|
||||
expect(relativeImagePath("C:\\p\\docs\\readme.md", "C:\\p\\docs\\assets\\a b.png")).toBe("assets/a%20b.png");
|
||||
expect(imageTarget("/p/a.md", "assets", "a.png")).toBe("/p/assets/a.png");
|
||||
expect(() => imageTarget("/p/a.md", "/absolute", "a.png")).toThrow();
|
||||
});
|
||||
it("uses timestamps for clipboard images and preserves source names", () => {
|
||||
expect(imageName("", "image/png", "image-{timestamp}", new Date(2026, 9, 31, 0, 15))).toBe(
|
||||
"image-20261031-001500.png",
|
||||
);
|
||||
expect(imageName("photo.jpg", "image/jpeg", "anything")).toBe("photo.jpg");
|
||||
});
|
||||
it("leaves non-Markdown image paste and text paste untouched", () => {
|
||||
expect(markdownImages({ path: "/p/code.ts", folder: "assets", pattern: "image" })).toEqual([]);
|
||||
const editor = view();
|
||||
const create = vi.spyOn(commands, "fsCreateFileBytes");
|
||||
paste(editor, []);
|
||||
expect(editor.state.doc.toString()).toBe("before plain textafter");
|
||||
paste(view("/p/code.ts"), [new File(["png"], "a.png", { type: "image/png" })]);
|
||||
expect(create).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([true, false])("distinguishes a source image.png from raw clipboard data (file: %s)", async (hasFile) => {
|
||||
vi.stubGlobal("__TAURI_INTERNALS__", {});
|
||||
vi.stubGlobal(
|
||||
"Worker",
|
||||
class {
|
||||
onmessage?: (e: { data: { data: number[] } }) => void;
|
||||
terminate() {}
|
||||
postMessage() {
|
||||
queueMicrotask(() => this.onmessage?.({ data: { data: [137, 80, 78, 71] } }));
|
||||
}
|
||||
},
|
||||
);
|
||||
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({
|
||||
status: "ok",
|
||||
data: hasFile ? ["/source/image.png"] : [],
|
||||
});
|
||||
const create = vi.spyOn(commands, "fsCreateFileBytes").mockResolvedValue({ status: "ok", data: null });
|
||||
const editor = view();
|
||||
paste(editor, [new File(["png"], "image.png", { type: "image/png" })]);
|
||||
await vi.waitFor(() => expect(create).toHaveBeenCalledTimes(1));
|
||||
expect(create.mock.calls[0]![0]).toMatch(hasFile ? /assets\/image\.png$/ : /assets\/image-\d{8}-\d{6}\.png$/);
|
||||
});
|
||||
|
||||
it("inserts a paste as one isolated undo step and tracks edits during saving", async () => {
|
||||
vi.stubGlobal(
|
||||
"Worker",
|
||||
class {
|
||||
onmessage?: (e: { data: { data: number[] } }) => void;
|
||||
terminate() {}
|
||||
postMessage() {
|
||||
queueMicrotask(() => this.onmessage?.({ data: { data: [137, 80, 78, 71] } }));
|
||||
}
|
||||
},
|
||||
);
|
||||
let finish!: (value: { status: "ok"; data: null }) => void;
|
||||
vi.spyOn(commands, "fsCreateFileBytes").mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
}),
|
||||
);
|
||||
const editor = view();
|
||||
expect(paste(editor, [new File(["png"], "a b.png", { type: "image/png" })]).defaultPrevented).toBe(true);
|
||||
await vi.waitFor(() => expect(finish).toBeDefined());
|
||||
editor.dispatch({ changes: { from: 0, insert: "X" }, userEvent: "input.type" });
|
||||
finish({ status: "ok", data: null });
|
||||
await vi.waitFor(() => expect(editor.state.doc.toString()).toBe("Xbefore after"));
|
||||
expect(undo(editor)).toBe(true);
|
||||
expect(editor.state.doc.toString()).toBe("Xbefore after");
|
||||
expect(undo(editor)).toBe(true);
|
||||
expect(editor.state.doc.toString()).toBe("before after");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,227 @@
|
||||
import { EditorSelection, EditorState, type Extension } from "@codemirror/state";
|
||||
import { isolateHistory } from "@codemirror/commands";
|
||||
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
import { call, commands, IpcError, isTauri } from "@/platform/ipc";
|
||||
import { invokeLocal } from "@/platform/tauriCore";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { registerFileDropHandler } from "@/workbench/fileDrop";
|
||||
|
||||
const IMAGE_FILE = /\.(png|jpe?g|gif|webp|avif|bmp|svg|ico|tiff?)$/i;
|
||||
const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
|
||||
|
||||
export function isMarkdown(path: string): boolean {
|
||||
return /\.(md|markdown|mdown|mkd|mkdn|mdwn|mdx|ronn|workbook)$/i.test(path);
|
||||
}
|
||||
|
||||
function normalize(path: string): string {
|
||||
const parts: string[] = [];
|
||||
for (const part of path.replace(/\\/g, "/").split("/")) {
|
||||
if (part === ".." && parts.length && parts.at(-1) !== "..") parts.pop();
|
||||
else if (part && part !== ".") parts.push(part);
|
||||
}
|
||||
return (path.startsWith("/") ? "/" : "") + parts.join("/");
|
||||
}
|
||||
|
||||
export function imageTarget(markdown: string, folder: string, name: string): string {
|
||||
const path = ipcPath(markdown);
|
||||
const relative = folder.trim().replace(/\\/g, "/") || "assets";
|
||||
if (relative.startsWith("/") || /^[a-z]:/i.test(relative)) throw new Error(tx("Image folder must be relative."));
|
||||
return normalize(`${path.slice(0, path.lastIndexOf("/"))}/${relative}/${name}`);
|
||||
}
|
||||
|
||||
export function relativeImagePath(markdown: string, target: string): string {
|
||||
const from = normalize(ipcPath(markdown)).split("/").slice(0, -1);
|
||||
const to = normalize(ipcPath(target)).split("/");
|
||||
while (from.length && to.length && from[0] === to[0]) {
|
||||
from.shift();
|
||||
to.shift();
|
||||
}
|
||||
return [...from.map(() => ".."), ...to]
|
||||
.map((part) =>
|
||||
encodeURIComponent(part).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`),
|
||||
)
|
||||
.join("/");
|
||||
}
|
||||
|
||||
export function imageName(source: string, mime: string, pattern: string, now = new Date()): string {
|
||||
if (source) return source.replace(/^.*[\\/]/, "");
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
const timestamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
|
||||
const stem = (pattern.trim() || "image-{timestamp}")
|
||||
.replaceAll("{timestamp}", timestamp)
|
||||
// Filenames cannot contain control characters.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
.replace(/[<>:"/\\|?*\x00-\x1f]/g, "-");
|
||||
const ext =
|
||||
({ "image/jpeg": "jpg", "image/svg+xml": "svg", "image/x-icon": "ico" } as Record<string, string>)[mime] ||
|
||||
mime.split("/")[1]?.replace(/[^a-z0-9]/gi, "") ||
|
||||
"png";
|
||||
return `${stem}.${ext}`;
|
||||
}
|
||||
|
||||
export async function saveImage(
|
||||
markdown: string,
|
||||
folder: string,
|
||||
name: string,
|
||||
data: number[],
|
||||
create = (path: string, bytes: number[]) => call(commands.fsCreateFileBytes(path, bytes)),
|
||||
): Promise<string> {
|
||||
const dot = name.lastIndexOf(".");
|
||||
const stem = dot > 0 ? name.slice(0, dot) : name;
|
||||
const ext = dot > 0 ? name.slice(dot) : "";
|
||||
for (let n = 0; ; n++) {
|
||||
const target = imageTarget(markdown, folder, `${stem}${n ? `-${n}` : ""}${ext}`);
|
||||
try {
|
||||
await create(target, data);
|
||||
return `})`;
|
||||
} catch (error) {
|
||||
if (!(error instanceof IpcError) || error.kind !== "alreadyExists") throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function imageBytes(blob: Blob | string): Promise<number[]> {
|
||||
if ((typeof blob === "string" ? blob.length * 0.75 : blob.size) > MAX_IMAGE_BYTES)
|
||||
return Promise.reject(new Error(tx("Image exceeds 16 MB.")));
|
||||
return new Promise((resolve, reject) => {
|
||||
const worker = new Worker(new URL("./imageBytes.worker.ts", import.meta.url), { type: "module" });
|
||||
worker.onmessage = (event: MessageEvent<{ data: number[]; error?: string }>) => {
|
||||
worker.terminate();
|
||||
if (event.data.error) reject(new Error(event.data.error));
|
||||
else resolve(event.data.data);
|
||||
};
|
||||
worker.onerror = (event) => {
|
||||
worker.terminate();
|
||||
reject(new Error(event.message));
|
||||
};
|
||||
worker.postMessage(blob);
|
||||
});
|
||||
}
|
||||
|
||||
interface ImageOptions {
|
||||
path: string;
|
||||
folder: string;
|
||||
pattern: string;
|
||||
}
|
||||
|
||||
export function markdownImages(options: ImageOptions): Extension {
|
||||
if (!isMarkdown(options.path)) return [];
|
||||
return ViewPlugin.fromClass(
|
||||
class {
|
||||
alive = true;
|
||||
pending = new Set<{ from: number; to: number }>();
|
||||
unregister: () => void;
|
||||
constructor(readonly view: EditorView) {
|
||||
this.unregister = registerFileDropHandler((paths, x, y) => {
|
||||
const rect = view.dom.getBoundingClientRect();
|
||||
if (
|
||||
x < rect.left ||
|
||||
x > rect.right ||
|
||||
y < rect.top ||
|
||||
y > rect.bottom ||
|
||||
!paths.every((p) => IMAGE_FILE.test(p)) ||
|
||||
view.state.readOnly
|
||||
)
|
||||
return false;
|
||||
this.insert(
|
||||
paths.map((path) => async () => {
|
||||
// OS paths belong to this client even in a remote project.
|
||||
const url = await invokeLocal<string>("fs_read_image", { path });
|
||||
return { blob: url, name: path.replace(/^.*[\\/]/, "") };
|
||||
}),
|
||||
view.posAtCoords({ x, y }) ?? view.state.selection.main.head,
|
||||
);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
update(update: ViewUpdate) {
|
||||
for (const range of this.pending) {
|
||||
range.from = update.changes.mapPos(range.from, 1);
|
||||
range.to = update.changes.mapPos(range.to, 1);
|
||||
}
|
||||
}
|
||||
destroy() {
|
||||
this.alive = false;
|
||||
this.unregister();
|
||||
}
|
||||
insert(sources: Array<() => Promise<{ blob: Blob | string; name: string }>>, position?: number) {
|
||||
const selection = this.view.state.selection.main;
|
||||
const range = { from: position ?? selection.from, to: position ?? selection.to };
|
||||
this.pending.add(range);
|
||||
void (async () => {
|
||||
const links: string[] = [];
|
||||
try {
|
||||
for (const source of sources) {
|
||||
const { blob, name } = await source();
|
||||
if (!this.alive) return;
|
||||
const bytes = await imageBytes(blob);
|
||||
if (!this.alive) return;
|
||||
links.push(
|
||||
await saveImage(
|
||||
options.path,
|
||||
options.folder,
|
||||
imageName(name, typeof blob === "string" ? "image/png" : blob.type, options.pattern),
|
||||
bytes,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (this.alive && !this.view.state.readOnly) {
|
||||
const text = links.join("\n");
|
||||
this.view.dispatch({
|
||||
changes: { from: range.from, to: range.to, insert: text },
|
||||
selection: EditorSelection.cursor(range.from + text.length),
|
||||
annotations: isolateHistory.of("full"),
|
||||
userEvent: "input.paste.image",
|
||||
filter: false,
|
||||
scrollIntoView: true,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
notifications().notify({ level: "error", title: tx("Cannot insert image"), body: String(error) });
|
||||
} finally {
|
||||
this.pending.delete(range);
|
||||
}
|
||||
})();
|
||||
}
|
||||
files(event: ClipboardEvent | DragEvent): boolean {
|
||||
if (this.view.state.facet(EditorState.readOnly)) return false;
|
||||
const transfer = "clipboardData" in event ? event.clipboardData : event.dataTransfer;
|
||||
const files = Array.from(transfer?.files ?? []).filter((f) => f.type.startsWith("image/"));
|
||||
if (!files.length) return false;
|
||||
event.preventDefault();
|
||||
// WebKit names raw clipboard images "image.png", which can also be a real filename.
|
||||
const copiedPaths =
|
||||
event.type === "paste" && files.some((file) => file.name === "image.png") && isTauri()
|
||||
? call(commands.clipboardFileList()).catch(() => [])
|
||||
: Promise.resolve([] as string[]);
|
||||
this.insert(
|
||||
files.map((file) => async () => ({
|
||||
blob: file,
|
||||
name:
|
||||
file.name === "image.png" &&
|
||||
event.type === "paste" &&
|
||||
!(await copiedPaths).some((path) => path.replace(/^.*[\\/]/, "") === file.name)
|
||||
? ""
|
||||
: file.name,
|
||||
})),
|
||||
event.type === "drop"
|
||||
? (this.view.posAtCoords({ x: (event as DragEvent).clientX, y: (event as DragEvent).clientY }) ?? undefined)
|
||||
: undefined,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
},
|
||||
{
|
||||
eventHandlers: {
|
||||
paste(event) {
|
||||
return this.files(event);
|
||||
},
|
||||
drop(event) {
|
||||
return this.files(event);
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
insertNewlineKeepIndent,
|
||||
selectLineStart,
|
||||
} from "@codemirror/commands";
|
||||
import { markdownImages } from "./markdownImages";
|
||||
import type { EditorExtras } from "@/platform/editorSettings";
|
||||
import { openideaHighlightStyle } from "./highlight";
|
||||
import {
|
||||
@@ -511,6 +512,8 @@ export function prefsExtension(o: PrefsOptions): Extension {
|
||||
const g = prefs.general;
|
||||
const k = prefs.smartKeys;
|
||||
const out: Extension[] = [];
|
||||
if (!o.readOnly)
|
||||
out.push(markdownImages({ path: o.path, folder: g.markdownImageFolder, pattern: g.markdownImageNamePattern }));
|
||||
if (g.scrollPastEnd) out.push(scrollPastEnd());
|
||||
if ((o.wrapOverride ?? softWrapActive(o.softWrap, prefs, o.path)) && g.softWrapIndent) out.push(wrapIndent);
|
||||
if (o.showWhitespace) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import { EditorSelection } from "@codemirror/state";
|
||||
import { create } from "zustand";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
import { basename, useProject } from "@/platform/project";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import {
|
||||
@@ -31,6 +32,8 @@ import {
|
||||
import { useDistractionFree } from "@/workbench/distractionFree";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { t } from "@/platform/i18n";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { isRemoteWindow } from "@/platform/remote";
|
||||
import { fileIconName, showContextMenu, type MenuItem } from "@/ui";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import {
|
||||
@@ -1059,7 +1062,7 @@ export class EditorController implements SlotHost {
|
||||
/** Close exactly the originally selected tabs, evaluating references after every await. */
|
||||
private removeGuarded(
|
||||
select: (s: TabsState) => TabsState,
|
||||
options: { protect?: (tab: Tab) => boolean; clearHistory?: boolean } = {},
|
||||
options: { protect?: (tab: Tab) => boolean; clearHistory?: boolean; beforeRemove?: () => Promise<boolean> } = {},
|
||||
): Promise<boolean> {
|
||||
const generation = this.projectGeneration;
|
||||
const initial = useTabs.getState();
|
||||
@@ -1129,6 +1132,7 @@ export class EditorController implements SlotHost {
|
||||
}
|
||||
authorized.add(d.input.key);
|
||||
}
|
||||
if (options.beforeRemove && !(await options.beforeRemove())) return false;
|
||||
// Commit only the original target ids against the latest tab state.
|
||||
if (generation !== this.projectGeneration) return false;
|
||||
const before = useTabs.getState();
|
||||
@@ -1303,6 +1307,46 @@ export class EditorController implements SlotHost {
|
||||
changeSplitOrientation(paneId: string) {
|
||||
this.apply((s) => changeSplitOrientation(s, paneId));
|
||||
}
|
||||
/** Save or resolve the dirty guard, open the window, then remove the original tab. */
|
||||
async detachTab(paneId: string, tabId: string): Promise<boolean> {
|
||||
const tab = useTabs.getState().panes[paneId]?.tabs.find((t) => t.id === tabId);
|
||||
const path = tab?.input.path;
|
||||
if (
|
||||
!tab ||
|
||||
!path ||
|
||||
(tab.input.kind !== "file" && !documentLifecycle(tab.input, useContributions.getState().editorKinds))
|
||||
)
|
||||
return false;
|
||||
if (isRemoteWindow()) {
|
||||
notifications().notify({ level: "warning", title: t("app.window.desktopOnly") });
|
||||
return false;
|
||||
}
|
||||
const project = useProject.getState().project;
|
||||
const inProject =
|
||||
!!project && (project.workspace?.projects ?? [project.root]).some((root) => isSameOrInside(path, root));
|
||||
return this.removeGuarded((s) => (s.panes[paneId] ? closeTab(s, paneId, tabId) : s), {
|
||||
beforeRemove: async () => {
|
||||
if (!useTabs.getState().panes[paneId]?.tabs.some((t) => t.id === tabId)) return false;
|
||||
if (isTextTab(tab)) {
|
||||
const slot = await this.ensureSlot(tabId);
|
||||
if (!slot) return false;
|
||||
await slot.model.save("explicit");
|
||||
}
|
||||
try {
|
||||
await call(commands.windowOpenFileInNewWindow(inProject ? project.root : null, path));
|
||||
return true;
|
||||
} catch (e) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: t("app.window.openFailed", { name: basename(path) }),
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
key: `app.open:${path}`,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
/** IDEA "Open in Opposite Group": the tab stays and a copy opens next door (or in a new split). */
|
||||
openInOpposite(paneId: string, tabId: string) {
|
||||
const s = useTabs.getState();
|
||||
@@ -1603,6 +1647,10 @@ export class EditorController implements SlotHost {
|
||||
{ label: "Unsplit All", run: () => void this.unsplitAll(paneId) },
|
||||
] as MenuItem[])
|
||||
: []),
|
||||
...(tab.input.path &&
|
||||
(tab.input.kind === "file" || documentLifecycle(tab.input, useContributions.getState().editorKinds))
|
||||
? ([{ label: "Open in New Window", run: () => void this.detachTab(paneId, tab.id) }] as MenuItem[])
|
||||
: []),
|
||||
{ kind: "separator" },
|
||||
...(path
|
||||
? ([
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorController, useTabs } from "./controller";
|
||||
import { createMemoryBackend } from "./backend";
|
||||
import { initialTabsState } from "./model/tabs";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { commands } from "@/platform/ipc";
|
||||
import * as contributions from "@/workbench/contributions";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import type * as Messages from "@/workbench/messages";
|
||||
import { registerEditorKind, type EditorDocumentLifecycle } from "@/workbench/contributions";
|
||||
|
||||
vi.mock("@/workbench/messages", async (original) => ({
|
||||
...(await original<typeof Messages>()),
|
||||
ask: vi.fn(),
|
||||
}));
|
||||
|
||||
const notify = vi.fn();
|
||||
let ctrl: EditorController;
|
||||
let unregister: (() => void) | undefined;
|
||||
const path = "/p/a.ts";
|
||||
const current = () => {
|
||||
const s = useTabs.getState();
|
||||
return [s.activePane, s.panes[s.activePane]!.active!] as const;
|
||||
};
|
||||
const hasTab = (id: string) => Object.values(useTabs.getState().panes).some((p) => p.tabs.some((t) => t.id === id));
|
||||
|
||||
beforeEach(() => {
|
||||
notify.mockReset();
|
||||
vi.spyOn(contributions, "notifications").mockReturnValue({ notify });
|
||||
useTabs.setState(initialTabsState(), true);
|
||||
useProject.setState({ project: null, settings: { files: { autoSave: false } } as never });
|
||||
vi.spyOn(commands, "windowOpenFileInNewWindow").mockResolvedValue({
|
||||
status: "ok",
|
||||
data: { kind: "opened", label: "second" },
|
||||
});
|
||||
});
|
||||
afterEach(() => {
|
||||
ctrl?.stop();
|
||||
unregister?.();
|
||||
unregister = undefined;
|
||||
vi.restoreAllMocks();
|
||||
vi.mocked(ask).mockReset();
|
||||
useProject.setState({ project: null, settings: null });
|
||||
});
|
||||
|
||||
describe("detachTab", () => {
|
||||
it.each([false, true])("waits for text save before opening and closing, autosave=%s", async (autoSave) => {
|
||||
useProject.setState({ settings: { files: { autoSave } } as never });
|
||||
const backend = createMemoryBackend({ [path]: "original\n" });
|
||||
ctrl = new EditorController(backend);
|
||||
ctrl.start();
|
||||
await ctrl.openFile(path, { focus: false });
|
||||
const [pane, id] = current();
|
||||
ctrl.slotFor(id)!.dispatchLocal({ changes: { from: 0, to: 8, insert: "edited" } });
|
||||
let finish!: () => void;
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
const originalSave = backend.save;
|
||||
const save = vi.spyOn(backend, "save").mockImplementation(async (doc) => {
|
||||
await gate;
|
||||
await originalSave(doc);
|
||||
});
|
||||
vi.mocked(commands.windowOpenFileInNewWindow).mockImplementation(async () => {
|
||||
expect(hasTab(id)).toBe(true);
|
||||
expect((await backend.snapshot(ctrl.slotFor(id)!.model.doc)).text).toBe("edited\n");
|
||||
return { status: "ok", data: { kind: "opened", label: "second" } };
|
||||
});
|
||||
const result = ctrl.detachTab(pane, id);
|
||||
await vi.waitFor(() => expect(save).toHaveBeenCalled());
|
||||
expect(commands.windowOpenFileInNewWindow).not.toHaveBeenCalled();
|
||||
expect(hasTab(id)).toBe(true);
|
||||
finish();
|
||||
expect(await result).toBe(true);
|
||||
expect(hasTab(id)).toBe(false);
|
||||
expect(ask).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the tab and opens no window when text saving fails", async () => {
|
||||
const backend = createMemoryBackend({ [path]: "original\n" });
|
||||
ctrl = new EditorController(backend);
|
||||
ctrl.start();
|
||||
await ctrl.openFile(path, { focus: false });
|
||||
const [pane, id] = current();
|
||||
vi.spyOn(backend, "save").mockRejectedValue(new Error("save failed"));
|
||||
expect(await ctrl.detachTab(pane, id)).toBe(false);
|
||||
expect(hasTab(id)).toBe(true);
|
||||
expect(commands.windowOpenFileInNewWindow).not.toHaveBeenCalled();
|
||||
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ level: "error", body: "save failed" }));
|
||||
});
|
||||
|
||||
it("keeps a pinned text tab if window creation fails", async () => {
|
||||
ctrl = new EditorController(createMemoryBackend({ [path]: "original\n" }));
|
||||
ctrl.start();
|
||||
await ctrl.openFile(path, { focus: false });
|
||||
const [pane, id] = current();
|
||||
ctrl.togglePin(pane, id);
|
||||
vi.mocked(commands.windowOpenFileInNewWindow).mockRejectedValue(new Error("window failed"));
|
||||
expect(await ctrl.detachTab(pane, id)).toBe(false);
|
||||
expect(useTabs.getState().panes[pane]!.tabs.find((t) => t.id === id)?.pinned).toBe(true);
|
||||
});
|
||||
|
||||
it.each(["save", "discard", "cancel", "save failure", "window failure"])(
|
||||
"runs the custom document guard once: %s",
|
||||
async (decision) => {
|
||||
const events: string[] = [];
|
||||
const lifecycle: EditorDocumentLifecycle = {
|
||||
isDirty: () => true,
|
||||
flush: async () => {},
|
||||
prepareClose: async () => {
|
||||
events.push("prepare");
|
||||
},
|
||||
cancelClose: () => {
|
||||
events.push("cancelClose");
|
||||
},
|
||||
save: async () => {
|
||||
events.push("save");
|
||||
if (decision === "save failure") throw new Error("save failed");
|
||||
},
|
||||
discard: async () => {
|
||||
events.push("discard");
|
||||
},
|
||||
close: async () => {
|
||||
events.push("close");
|
||||
},
|
||||
};
|
||||
unregister = registerEditorKind({
|
||||
kind: "detach-test",
|
||||
title: () => "test",
|
||||
component: () => null,
|
||||
document: lifecycle,
|
||||
});
|
||||
ctrl = new EditorController(createMemoryBackend());
|
||||
ctrl.start();
|
||||
await ctrl.openInput({ kind: "detach-test", key: "custom", path: "/p/a.ipynb" }, { focus: false });
|
||||
const [pane, id] = current();
|
||||
vi.mocked(ask).mockImplementation(async () => {
|
||||
events.push("ask");
|
||||
expect(commands.windowOpenFileInNewWindow).not.toHaveBeenCalled();
|
||||
return {
|
||||
button: decision === "save failure" || decision === "window failure" ? "save" : decision,
|
||||
checked: false,
|
||||
};
|
||||
});
|
||||
vi.mocked(commands.windowOpenFileInNewWindow).mockImplementation(async () => {
|
||||
events.push("open");
|
||||
expect(hasTab(id)).toBe(true);
|
||||
if (decision === "window failure") throw new Error("window failed");
|
||||
return { status: "ok", data: { kind: "opened", label: "second" } };
|
||||
});
|
||||
const success = decision === "save" || decision === "discard";
|
||||
expect(await ctrl.detachTab(pane, id)).toBe(success);
|
||||
expect(hasTab(id)).toBe(!success);
|
||||
expect(ask).toHaveBeenCalledOnce();
|
||||
expect(events).toEqual(
|
||||
success
|
||||
? ["prepare", "ask", decision, "open", "close"]
|
||||
: decision === "cancel"
|
||||
? ["prepare", "ask", "cancelClose"]
|
||||
: decision === "save failure"
|
||||
? ["prepare", "ask", "save", "cancelClose"]
|
||||
: ["prepare", "ask", "save", "open", "cancelClose"],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["C:\\project\\a.ts", ["C:/project"], "C:/project"],
|
||||
["C:\\other\\a.ts", ["C:/project", "C:/other"], "C:/project"],
|
||||
["C:\\project-other\\a.ts", ["C:/project"], null],
|
||||
])("routes %s by workspace containment", async (file, projects, expected) => {
|
||||
useProject.setState({ project: { root: "C:/project", workspace: { projects } } as never });
|
||||
ctrl = new EditorController(createMemoryBackend({ [file]: "text\n" }));
|
||||
ctrl.start();
|
||||
await ctrl.openFile(file, { focus: false });
|
||||
expect(await ctrl.detachTab(...current())).toBe(true);
|
||||
expect(commands.windowOpenFileInNewWindow).toHaveBeenCalledWith(expected, file);
|
||||
});
|
||||
});
|
||||
@@ -198,6 +198,11 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
const pinnedRow =
|
||||
tabPrefs.pinnedSeparateRow && (vertical || !tabPrefs.multipleRows) && pinnedCount > 0 && pinnedCount < tabs.length;
|
||||
const dnd = useMemo(() => {
|
||||
// A tab released outside the window detaches into a forced new window.
|
||||
const dropOutside = (raw: string) => {
|
||||
const p = parseTabPayload(raw);
|
||||
if (p) void ctrl.detachTab(p.paneId, p.tabId);
|
||||
};
|
||||
const strip = (offset: number): TabsDnd => ({
|
||||
type: EDITOR_TAB_MIME,
|
||||
payload: (tabId) => JSON.stringify({ paneId, tabId }),
|
||||
@@ -205,6 +210,7 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
const p = parseTabPayload(raw);
|
||||
if (p) ctrl.moveTab(p.paneId, p.tabId, paneId, index + offset);
|
||||
},
|
||||
onDropOutside: dropOutside,
|
||||
});
|
||||
return { all: strip(0), rest: strip(pinnedCount) };
|
||||
}, [ctrl, paneId, pinnedCount]);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
import { forEachDiagnostic } from "@codemirror/lint";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { editorCorner } from "@/editor/api";
|
||||
import { toolWindowService } from "@/workbench/contributions";
|
||||
import { gotoDiagnostic } from "./diagnostics";
|
||||
import { iconNode } from "./iconMarkup";
|
||||
@@ -50,7 +51,7 @@ class InspectionWidget {
|
||||
this.dom.className = "cm-openidea-inspection";
|
||||
this.dom.setAttribute("role", "toolbar");
|
||||
this.dom.setAttribute("aria-label", "Inspections");
|
||||
view.dom.appendChild(this.dom);
|
||||
editorCorner(view).appendChild(this.dom);
|
||||
this.render();
|
||||
}
|
||||
|
||||
@@ -123,10 +124,6 @@ const inspectionPlugin = ViewPlugin.fromClass(InspectionWidget);
|
||||
|
||||
const inspectionTheme = EditorView.theme({
|
||||
".cm-openidea-inspection": {
|
||||
position: "absolute",
|
||||
top: "4px",
|
||||
right: "16px",
|
||||
zIndex: "5",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "1px",
|
||||
|
||||
@@ -1,7 +1,52 @@
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { AgentConfigOption } from "@/bindings";
|
||||
import { ConfigPickers } from "./ConfigPickers";
|
||||
import { ConfigPickers, configPickerOptions } from "./ConfigPickers";
|
||||
|
||||
const config = (values: AgentConfigOption["values"], category = "model"): AgentConfigOption => ({
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category,
|
||||
description: null,
|
||||
current: null,
|
||||
via: "option",
|
||||
values,
|
||||
});
|
||||
const value = (id: string, name = id, description: string | null = null) => ({ value: id, name, description });
|
||||
|
||||
describe("configPickerOptions", () => {
|
||||
it("groups nested paths by their first provider and preserves the full value and description", () => {
|
||||
expect(configPickerOptions(config([value("9router/cmc/Beam", "Beam display", "Fast")]))).toEqual([
|
||||
{ value: "9router", label: "9router", section: true },
|
||||
{ value: "9router/cmc/Beam", label: "Beam", detail: "cmc/Beam · Fast", keywords: "9router" },
|
||||
]);
|
||||
});
|
||||
it("keeps plain ids ungrouped even when the display name contains a slash", () => {
|
||||
expect(configPickerOptions(config([value("plain", "Local / Beam", "Offline")]))).toEqual([
|
||||
{ value: "plain", label: "Local / Beam", detail: "Offline", keywords: "" },
|
||||
]);
|
||||
});
|
||||
it("collects several providers in encounter order and preserves order inside each group", () => {
|
||||
const options = configPickerOptions(
|
||||
config([value("a/One"), value("b/Two"), value("a/Three"), value("plain"), value("__section__:a")]),
|
||||
);
|
||||
expect(options.map((o) => [o.value, !!o.section])).toEqual([
|
||||
["plain", false],
|
||||
["__section__:a", false],
|
||||
["a", true],
|
||||
["a/One", false],
|
||||
["a/Three", false],
|
||||
["b", true],
|
||||
["b/Two", false],
|
||||
]);
|
||||
expect(options[3]?.detail).toBe("One");
|
||||
});
|
||||
it("leaves non-model option labels and descriptions intact", () => {
|
||||
expect(configPickerOptions(config([value("a/One", "Custom", "Description")], "mode"))).toEqual([
|
||||
{ value: "a/One", label: "Custom", detail: "Description" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it("shows Cursor approvals separately from its execution mode and sends the choice", () => {
|
||||
const option = (id: string, category: string, values: string[]): AgentConfigOption => ({
|
||||
@@ -32,3 +77,11 @@ it("shows Cursor approvals separately from its execution mode and sends the choi
|
||||
fireEvent.click(screen.getByRole("option", { name: "Bypass approvals" }));
|
||||
expect(onChange).toHaveBeenCalledWith("openidea.cursor.approval", "bypass");
|
||||
});
|
||||
|
||||
it("sends the complete nested model id through ConfigPickers", () => {
|
||||
const onChange = vi.fn();
|
||||
render(<ConfigPickers config={[config([value("9router/cmc/Beam")])]} onChange={onChange} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Model" }));
|
||||
fireEvent.click(screen.getByRole("option", { name: "Beamcmc/Beam" }));
|
||||
expect(onChange).toHaveBeenCalledExactlyOnceWith("model", "9router/cmc/Beam");
|
||||
});
|
||||
@@ -5,9 +5,33 @@
|
||||
import type { AgentConfigOption } from "@/bindings";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { Select } from "@/ui";
|
||||
import type { SelectOption } from "@/ui/Select";
|
||||
import { mainOptions, modeIcon } from "./composerModel";
|
||||
import styles from "./Composer.module.css";
|
||||
|
||||
export function configPickerOptions(option: AgentConfigOption): SelectOption[] {
|
||||
if (option.category !== "model") {
|
||||
return option.values.map((v) => ({ value: v.value, label: v.name, detail: v.description ?? undefined }));
|
||||
}
|
||||
const groups = new Map<string, SelectOption[]>();
|
||||
for (const v of option.values) {
|
||||
const slash = v.value.indexOf("/");
|
||||
const provider = slash >= 0 ? v.value.slice(0, slash) : "";
|
||||
const path = slash >= 0 ? v.value.slice(slash + 1) : "";
|
||||
const label = path ? path.slice(path.lastIndexOf("/") + 1) : v.name || v.value;
|
||||
const detail = path ? [path, v.description].filter(Boolean).join(" · ") : (v.description ?? undefined);
|
||||
const bucket = groups.get(provider) ?? [];
|
||||
bucket.push({ value: v.value, label, detail, keywords: provider });
|
||||
groups.set(provider, bucket);
|
||||
}
|
||||
const plain = groups.get("") ?? [];
|
||||
groups.delete("");
|
||||
return [
|
||||
...plain,
|
||||
...[...groups].flatMap(([provider, items]) => [{ value: provider, label: provider, section: true }, ...items]),
|
||||
];
|
||||
}
|
||||
|
||||
export function ConfigPickers({
|
||||
config,
|
||||
values,
|
||||
@@ -24,6 +48,8 @@ export function ConfigPickers({
|
||||
{mainOptions(config).map((o) => {
|
||||
const isMode = o.category === "mode";
|
||||
const value = values?.[o.id] ?? o.current ?? null;
|
||||
const options = configPickerOptions(o);
|
||||
|
||||
return (
|
||||
<Select
|
||||
key={o.id}
|
||||
@@ -31,18 +57,16 @@ export function ConfigPickers({
|
||||
aria-label={o.name}
|
||||
value={value}
|
||||
placeholder={tx(o.name)}
|
||||
options={o.values.map((v) => ({
|
||||
value: v.value,
|
||||
label: v.name,
|
||||
options={options.map((opt) => ({
|
||||
...opt,
|
||||
icon:
|
||||
o.category === "approval"
|
||||
? v.value === "bypass"
|
||||
? opt.value === "bypass"
|
||||
? "unlock"
|
||||
: "lock"
|
||||
: isMode
|
||||
? modeIcon(v.value)
|
||||
? modeIcon(opt.value)
|
||||
: undefined,
|
||||
detail: v.description ?? undefined,
|
||||
}))}
|
||||
searchable={o.category === "model"}
|
||||
onChange={(v) => onChange(o.id, v)}
|
||||
|
||||
@@ -21,7 +21,7 @@ export function providerOptions(
|
||||
const missing = providers.filter((p) => !p.installed);
|
||||
return [
|
||||
...installed.map((p) => ({ value: p.id, label: p.name, icon: icon(p.id), detail: version(p) })),
|
||||
...(missing.length ? [{ value: "__missing__", label: tx("Not installed"), disabled: true }] : []),
|
||||
...(missing.length ? [{ value: "__missing__", label: tx("Not installed"), section: true }] : []),
|
||||
...missing.map((p) => ({ value: p.id, label: p.name, icon: icon(p.id), detail: p.command })),
|
||||
{ value: ADD_AGENT, label: tx("More agents…") },
|
||||
];
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { getAction, isActionEnabled } from "@/platform/actions";
|
||||
import { executeAction, getAction, isActionEnabled } from "@/platform/actions";
|
||||
import { getContext, setContext } from "@/platform/context";
|
||||
import { bindingsFor } from "@/platform/keymap";
|
||||
import { IpcError, type BuildEvent, type BuildMessage, type BuildResult } from "@/platform/ipc";
|
||||
@@ -173,7 +173,7 @@ describe("build feature", () => {
|
||||
await act(async () => {});
|
||||
expect(getContext()["build.running"]).toBe(true);
|
||||
expect(isActionEnabled(getAction("build.buildProject")!)).toBe(false);
|
||||
expect(show).not.toHaveBeenCalled();
|
||||
expect(show).toHaveBeenCalledWith("build", false);
|
||||
expect(useTasks.getState().tasks.some((t) => t.id === BUILD_TASK_ID && !t.done)).toBe(true);
|
||||
const messages = [err("/p/src/A.java", 11), warn("/p/src/B.java", 2)];
|
||||
await act(async () => {
|
||||
@@ -213,9 +213,67 @@ describe("build feature", () => {
|
||||
await second;
|
||||
});
|
||||
expect(notes.at(-1)).toMatchObject({ level: "info", title: "Build completed successfully in 3 s" });
|
||||
expect(show).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["build.buildProject", undefined],
|
||||
["build.buildModule", "/p/core/src/A.java"],
|
||||
["build.rebuildProject", undefined],
|
||||
])("opens the Build window without focus when %s starts", async (id, arg) => {
|
||||
const run = executeAction(id!, arg);
|
||||
await act(async () => {});
|
||||
expect(useBuildRun.getState().status).toBe("running");
|
||||
expect(show).toHaveBeenCalledExactlyOnceWith("build", false);
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
await act(async () => {
|
||||
fake.resolve(result([], true));
|
||||
await run;
|
||||
});
|
||||
expect(show).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("keeps before-launch builds hidden until a failure", async () => {
|
||||
const run = executeAction("build.buildProject", { activate: false });
|
||||
await act(async () => {});
|
||||
expect(useBuildRun.getState().status).toBe("running");
|
||||
expect(show).not.toHaveBeenCalled();
|
||||
await act(async () => {
|
||||
fake.resolve(result([], true));
|
||||
await run;
|
||||
});
|
||||
expect(show).not.toHaveBeenCalled();
|
||||
|
||||
const failed = executeAction("build.buildProject", { activate: false });
|
||||
await act(async () => {});
|
||||
expect(show).not.toHaveBeenCalled();
|
||||
const messages = [err("/p/src/A.java", 11)];
|
||||
await act(async () => {
|
||||
fake.resolve(result(messages, false));
|
||||
await failed;
|
||||
});
|
||||
expect(show).toHaveBeenCalledExactlyOnceWith("build", false);
|
||||
expect(useBuildRun.getState().selected).toBe(firstError(messages)!.key);
|
||||
expect(openFile).toHaveBeenCalledWith(
|
||||
"/p/src/A.java",
|
||||
expect.objectContaining({ focus: true, selection: { line: 11, col: 4 } }),
|
||||
);
|
||||
});
|
||||
|
||||
it("starts a build without a workbench", async () => {
|
||||
show.mockImplementation(() => {
|
||||
throw new Error("No workbench");
|
||||
});
|
||||
const run = startBuild("build");
|
||||
await act(async () => {});
|
||||
expect(fake.calls).toHaveLength(1);
|
||||
await act(async () => {
|
||||
fake.resolve(result([], true));
|
||||
await run;
|
||||
});
|
||||
expect(useBuildRun.getState().status).toBe("success");
|
||||
});
|
||||
|
||||
it("shows a message on single click and navigates on F4", async () => {
|
||||
const messages = [err("/p/src/A.java", 11, "first problem"), warn("/p/src/B.java", 2)];
|
||||
const run = startBuild("build");
|
||||
|
||||
@@ -59,7 +59,10 @@ export function activate(): () => void {
|
||||
when: WHEN,
|
||||
keywords: ["compile", "make", "mvn", "gradle", "cargo", "tsc", "go build"],
|
||||
// Awaitable: Run's "Build" before launch task waits for the result.
|
||||
run: async () => void (await startBuild("build")),
|
||||
run: async ({ arg }) => {
|
||||
const activate = !(typeof arg === "object" && arg !== null && "activate" in arg && arg.activate === false);
|
||||
await startBuild("build", null, activate);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "build.buildModule",
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
* Compiler messages reach the Problems view and editors as `build`
|
||||
* diagnostics, published (and cleared on the next build) by the backend.
|
||||
*
|
||||
* Like IDEA, the tool window is not shown when a build starts; a failed build
|
||||
* shows it, selects the first error and opens its location in the editor.
|
||||
* Explicit builds show the tool window without taking focus. A failed build
|
||||
* also selects the first error and opens its location in the editor.
|
||||
*/
|
||||
import { create } from "zustand";
|
||||
import { Channel } from "@tauri-apps/api/core";
|
||||
@@ -123,7 +123,11 @@ export function isBuilding(): boolean {
|
||||
* Builds the project (`file` null) or the module containing `file`. Saves all
|
||||
* documents first; a second build while one runs is ignored (IDEA disables the actions).
|
||||
*/
|
||||
export async function startBuild(kind: BuildKind, file: string | null = null): Promise<BuildResult | null> {
|
||||
export async function startBuild(
|
||||
kind: BuildKind,
|
||||
file: string | null = null,
|
||||
activate = true,
|
||||
): Promise<BuildResult | null> {
|
||||
if (isBuilding() || !useProject.getState().project) return null;
|
||||
const request = nextRequestId();
|
||||
const taskTitle = TITLES[kind];
|
||||
@@ -131,6 +135,13 @@ export async function startBuild(kind: BuildKind, file: string | null = null): P
|
||||
const previous = useBuildRun.getState().files;
|
||||
useBuildRun.setState({ ...INITIAL, request, kind, file, title: taskTitle, status: "running", files: previous });
|
||||
setContext(BUILD_RUNNING, true);
|
||||
if (activate) {
|
||||
try {
|
||||
toolWindowService().show("build", false);
|
||||
} catch {
|
||||
// No workbench (tests / settings window).
|
||||
}
|
||||
}
|
||||
upsertTask({ id: BUILD_TASK_ID, title: taskTitle, message: null, fraction: null, done: false, cancel });
|
||||
await maybeEditorService()
|
||||
?.saveAll()
|
||||
|
||||
@@ -11,6 +11,14 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
findFiles: (name: string) =>
|
||||
ok(
|
||||
name === "Main.java"
|
||||
? [{ path: "/p/api/src/main/java/a/Main.java", relPath: "api/src/main/java/a/Main.java" }]
|
||||
: [],
|
||||
),
|
||||
fsReadText: () => ok("package a;\npublic class Main {}"),
|
||||
runConfigs: () => ok([]),
|
||||
fsReadDir: (path: string) =>
|
||||
ok(
|
||||
kotlinFiles && path.endsWith("/src")
|
||||
@@ -49,6 +57,7 @@ const app: RunConfig = {
|
||||
command: "java",
|
||||
args: ["-Xmx1g", "-cp", "${classpath}", "a.Main", "--port", "8081 x"],
|
||||
cwd: "api",
|
||||
module: "api",
|
||||
env: { A: "1" },
|
||||
detected: true,
|
||||
isTest: false,
|
||||
@@ -144,3 +153,14 @@ describe("Java debugging (java-debug through jdtls)", () => {
|
||||
expect(JSON.parse(l.extraJson!)).toMatchObject({ debugServer: 41234, hostName: "127.0.0.1", port: 5005 });
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["sibling", "/outside/modules"])("debugs from %s with the main class module", async (cwd) => {
|
||||
kotlinFiles = false;
|
||||
for (const module of ["api", undefined]) {
|
||||
invoked.length = 0;
|
||||
const launch = await javaLaunchConfig({ ...app, module, cwd }, "/p");
|
||||
expect(invoked).toContainEqual(["javaResolveLaunch", ["api", false, true, expect.any(Number)]]);
|
||||
expect(invoked).toContainEqual(["javaDebugServer", ["api"]]);
|
||||
expect(launch.cwd).toBe(cwd.startsWith("/") ? cwd : `/p/${cwd}`);
|
||||
}
|
||||
});
|
||||
@@ -26,6 +26,7 @@ const config: RunConfig = {
|
||||
command: "java",
|
||||
args: ["-cp", "${classpath}", "Main"],
|
||||
cwd: null,
|
||||
module: "",
|
||||
env: {},
|
||||
detected: true,
|
||||
isTest: false,
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
joinJavaArgs,
|
||||
parseJavaArgs,
|
||||
resolveJavaCommand,
|
||||
resolveJavaModule,
|
||||
} from "@/platform/javaLaunch";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
|
||||
@@ -85,11 +86,12 @@ export async function javaLaunchConfig(
|
||||
root: string,
|
||||
preparation?: { request: RequestId; signal: AbortSignal },
|
||||
): Promise<LaunchConfig> {
|
||||
const module = rc.cwd ?? "";
|
||||
const cwd = rc.cwd ? join(root, rc.cwd) : root;
|
||||
const parsed = parseJavaArgs(rc.args);
|
||||
if (!parsed.mainClass) throw new Error(`No main class in '${rc.name}'`);
|
||||
preparation?.signal.throwIfAborted();
|
||||
const module = await resolveJavaModule(rc);
|
||||
preparation?.signal.throwIfAborted();
|
||||
const info = await call(
|
||||
commands.javaResolveLaunch(module, parsed.classpath === "test", true, preparation?.request ?? nextRequestId()),
|
||||
);
|
||||
@@ -103,7 +105,7 @@ export async function javaLaunchConfig(
|
||||
body: formatCompileErrors(info).trimEnd(),
|
||||
});
|
||||
const resolved = resolveJavaCommand(rc, info);
|
||||
const kotlin = rc.debugAdapter === KOTLIN_ADAPTER || (await moduleHasKotlinSources(cwd));
|
||||
const kotlin = rc.debugAdapter === KOTLIN_ADAPTER || (await moduleHasKotlinSources(join(root, module)));
|
||||
preparation?.signal.throwIfAborted();
|
||||
const classPaths = parsed.explicitClasspath ? parsed.explicitClasspath.split(/[:;]/) : info.classPaths;
|
||||
if (kotlin) {
|
||||
@@ -116,7 +118,7 @@ export async function javaLaunchConfig(
|
||||
cwd,
|
||||
env: { ...rc.env },
|
||||
extraJson: JSON.stringify({
|
||||
projectRoot: cwd,
|
||||
projectRoot: join(root, module),
|
||||
mainClass: parsed.mainClass,
|
||||
classPaths,
|
||||
modulePaths: info.modulePaths,
|
||||
|
||||
@@ -1,371 +0,0 @@
|
||||
.view {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
.split {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
.flex {
|
||||
flex: 1;
|
||||
}
|
||||
.dim {
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.hint {
|
||||
margin-top: 6px;
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.error {
|
||||
padding: 10px 12px;
|
||||
color: var(--danger);
|
||||
}
|
||||
.loading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 12px;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.ellipsis {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.repo {
|
||||
min-width: 0;
|
||||
margin-left: 8px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.banner {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-height: 28px;
|
||||
padding: 2px 6px 2px 10px;
|
||||
font-size: var(--fs-small);
|
||||
color: var(--fg-secondary);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.bannerText {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
/* List pane */
|
||||
.listPane {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
.filters {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.search {
|
||||
width: 100%;
|
||||
}
|
||||
.filterRow {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px 10px;
|
||||
min-height: var(--h-control);
|
||||
}
|
||||
.filterRow > :not(.flex) {
|
||||
flex: none;
|
||||
}
|
||||
.list {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
.listRow {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
padding: 0 4px;
|
||||
}
|
||||
.listTitle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.listMeta {
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Details pane */
|
||||
.details {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
.header {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 10px 12px 8px;
|
||||
}
|
||||
.titleRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.title {
|
||||
margin: 0;
|
||||
font-size: var(--fs-input-large);
|
||||
font-weight: 600;
|
||||
color: var(--fg-strong);
|
||||
-webkit-user-select: text;
|
||||
user-select: text;
|
||||
}
|
||||
.metaRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
color: var(--fg-secondary);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.conflict {
|
||||
color: var(--danger);
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.actions > :not(.flex) {
|
||||
flex: none;
|
||||
}
|
||||
.scroll {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
padding: 10px 12px;
|
||||
-webkit-user-select: text;
|
||||
user-select: text;
|
||||
}
|
||||
.section {
|
||||
margin-top: 14px;
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.sectionTitle {
|
||||
margin: 0 0 6px;
|
||||
font-size: var(--fs-small);
|
||||
font-weight: 600;
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
.checkRow,
|
||||
.commitRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: var(--h-row);
|
||||
}
|
||||
.check-success,
|
||||
.review-APPROVED {
|
||||
color: var(--success);
|
||||
}
|
||||
.check-failure,
|
||||
.review-CHANGES_REQUESTED {
|
||||
color: var(--danger);
|
||||
}
|
||||
.check-pending,
|
||||
.review-REQUESTED {
|
||||
color: var(--warning);
|
||||
}
|
||||
.check-skipped,
|
||||
.check-cancelled,
|
||||
.check-neutral,
|
||||
.review-COMMENTED,
|
||||
.review-DISMISSED {
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.labels {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.label {
|
||||
padding: 0 6px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-small);
|
||||
font-size: var(--fs-small);
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
.link {
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--link);
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.link:hover {
|
||||
color: var(--link-hover);
|
||||
text-decoration: underline;
|
||||
}
|
||||
.fileRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
width: 100%;
|
||||
min-height: var(--h-row);
|
||||
padding: 0 4px;
|
||||
border: none;
|
||||
border-radius: var(--radius-row);
|
||||
background: none;
|
||||
color: var(--fg);
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
}
|
||||
.fileRow:hover {
|
||||
background: var(--bg-tree-hover);
|
||||
}
|
||||
.fileName {
|
||||
flex: none;
|
||||
}
|
||||
.change-ADDED {
|
||||
color: var(--vcs-added);
|
||||
}
|
||||
.change-DELETED {
|
||||
color: var(--vcs-deleted);
|
||||
}
|
||||
.change-MODIFIED,
|
||||
.change-CHANGED,
|
||||
.change-RENAMED,
|
||||
.change-COPIED {
|
||||
color: var(--vcs-modified);
|
||||
}
|
||||
.added {
|
||||
color: var(--vcs-added);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.deleted {
|
||||
color: var(--vcs-deleted);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.oid {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-small);
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.comment {
|
||||
margin-bottom: 10px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-control);
|
||||
}
|
||||
.commentHead {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: var(--fs-small);
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
.threadItem {
|
||||
margin-top: 8px;
|
||||
}
|
||||
.threadItem + .threadItem {
|
||||
padding-top: 8px;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.newComment {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.markdown {
|
||||
color: var(--fg);
|
||||
line-height: 1.5;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.markdown :global(pre) {
|
||||
padding: 6px 8px;
|
||||
overflow: auto;
|
||||
background: var(--bg-editor);
|
||||
border-radius: var(--radius-small);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-code);
|
||||
}
|
||||
.markdown :global(code) {
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
.markdown :global(a) {
|
||||
color: var(--link);
|
||||
}
|
||||
.markdown :global(img) {
|
||||
max-width: 100%;
|
||||
}
|
||||
.markdown :global(h1),
|
||||
.markdown :global(h2),
|
||||
.markdown :global(h3) {
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
|
||||
/* Dialogs */
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 14px;
|
||||
}
|
||||
.formRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.fieldLabel {
|
||||
color: var(--fg-secondary);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.textarea {
|
||||
resize: vertical;
|
||||
min-height: 48px;
|
||||
padding: 4px 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-small);
|
||||
background: var(--bg-input);
|
||||
color: var(--fg);
|
||||
font: inherit;
|
||||
}
|
||||
.textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--focus-ring);
|
||||
}
|
||||
@@ -1,609 +0,0 @@
|
||||
/** The Pull Requests tool window: filterable list on the left, the selected pull request on the right. */
|
||||
import { useEffect, useMemo, useState, type MouseEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { GhAvailability, PrCheck, PrStateFilter, PullRequestDetails, PullRequestSummary } from "@/platform/ipc";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useMarkupHtml } from "@/editor/lsp/markdown";
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Checkbox,
|
||||
EmptyState,
|
||||
Icon,
|
||||
IconButton,
|
||||
List,
|
||||
SearchField,
|
||||
Select,
|
||||
SplitGroup,
|
||||
SplitHandle,
|
||||
SplitPanel,
|
||||
Spinner,
|
||||
Tabs,
|
||||
showContextMenu,
|
||||
type MenuItem,
|
||||
T,
|
||||
} from "@/ui";
|
||||
import {
|
||||
checksSummary,
|
||||
checksText,
|
||||
relativeTime,
|
||||
reviewDecisionLabel,
|
||||
reviewStateLabel,
|
||||
reviewThreads,
|
||||
stateLabel,
|
||||
} from "./model";
|
||||
import { addComment, checkoutPullRequest, openCommentLocation, openFileDiff, openUrl, submitReview } from "./ops";
|
||||
import { cancelBusy, loadDetails, refreshAll, select, setQuery, useGithub, type DetailTab } from "./store";
|
||||
import styles from "./Github.module.css";
|
||||
import { t, tx } from "@/platform/i18n";
|
||||
|
||||
const STATES: PrStateFilter[] = ["open", "merged", "closed", "all"];
|
||||
|
||||
function Unavailable({ availability }: { availability: GhAvailability }) {
|
||||
const retry = (
|
||||
<Button size="small" onClick={() => void refreshAll()}>
|
||||
<T>Retry</T>
|
||||
</Button>
|
||||
);
|
||||
switch (availability.kind) {
|
||||
case "notInstalled":
|
||||
return (
|
||||
<EmptyState
|
||||
title="GitHub CLI is not installed"
|
||||
actions={
|
||||
<>
|
||||
<Button size="small" onClick={() => void openUrl("https://cli.github.com")}>
|
||||
<T>Install gh…</T>
|
||||
</Button>
|
||||
{retry}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<T>Pull requests use the</T> <code>gh</code> <T>command line tool. Install it, then run</T>{" "}
|
||||
<code>gh auth login</code>.
|
||||
</EmptyState>
|
||||
);
|
||||
case "notLoggedIn":
|
||||
return (
|
||||
<EmptyState
|
||||
title="Not logged in to GitHub"
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
size="small"
|
||||
variant="primary"
|
||||
onClick={() =>
|
||||
void executeAction("terminal.runCommand", {
|
||||
program: "gh",
|
||||
args: ["auth", "login"],
|
||||
name: "gh auth login",
|
||||
})
|
||||
}
|
||||
>
|
||||
<T>Run gh auth login</T>
|
||||
</Button>
|
||||
{retry}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<T>Run</T> <code>gh auth login</code> <T>in a terminal, then retry.</T>
|
||||
</EmptyState>
|
||||
);
|
||||
case "notGitHub":
|
||||
return (
|
||||
<EmptyState title="No GitHub repository" actions={retry}>
|
||||
<div>
|
||||
<T>This project has no remote on GitHub.</T>
|
||||
</div>
|
||||
<div className={styles.hint}>{availability.message}</div>
|
||||
</EmptyState>
|
||||
);
|
||||
case "error":
|
||||
return (
|
||||
<EmptyState title="Could not reach GitHub" actions={retry}>
|
||||
{availability.message}
|
||||
</EmptyState>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function StateBadge({ pr }: { pr: PullRequestSummary }) {
|
||||
const tone = pr.state === "merged" ? "accent" : pr.state === "closed" ? "danger" : pr.isDraft ? "neutral" : "success";
|
||||
return <Badge tone={tone}>{stateLabel(pr)}</Badge>;
|
||||
}
|
||||
|
||||
function Filters() {
|
||||
const query = useGithub((s) => s.query);
|
||||
const loading = useGithub((s) => s.listLoading);
|
||||
const [search, setSearch] = useState(query.search);
|
||||
useEffect(() => {
|
||||
if (search === useGithub.getState().query.search) return;
|
||||
const t = setTimeout(() => setQuery({ search }), 400);
|
||||
return () => clearTimeout(t);
|
||||
}, [search]);
|
||||
return (
|
||||
<div className={styles.filters}>
|
||||
<SearchField
|
||||
value={search}
|
||||
onChange={setSearch}
|
||||
placeholder="Search (GitHub syntax)"
|
||||
aria-label="Search pull requests"
|
||||
className={styles.search}
|
||||
/>
|
||||
<div className={styles.filterRow}>
|
||||
<Select
|
||||
value={query.state}
|
||||
options={STATES.map((value) => ({ value, label: t(`github.prState.${value}`) }))}
|
||||
onChange={(state) => setQuery({ state })}
|
||||
aria-label="State"
|
||||
/>
|
||||
<Checkbox checked={query.authorMe} onChange={(authorMe) => setQuery({ authorMe })} label="Mine" />
|
||||
<Checkbox
|
||||
checked={query.reviewRequested}
|
||||
onChange={(reviewRequested) => setQuery({ reviewRequested })}
|
||||
label="Review requested"
|
||||
/>
|
||||
<span className={styles.flex} />
|
||||
{loading ? <Spinner size={14} /> : <IconButton icon="refresh" size="small" action="github.refresh" />}
|
||||
<IconButton icon="plus" size="small" action="github.createPullRequest" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ListRow({ pr }: { pr: PullRequestSummary }) {
|
||||
const decision = reviewDecisionLabel(pr.reviewDecision);
|
||||
return (
|
||||
<div className={styles.listRow}>
|
||||
<div className={styles.listTitle}>
|
||||
<span className={styles.ellipsis}>{pr.title}</span>
|
||||
<StateBadge pr={pr} />
|
||||
</div>
|
||||
<div className={styles.listMeta}>
|
||||
#{pr.number} {tx`by ${pr.author}`} · {relativeTime(pr.updatedAt)}
|
||||
{decision ? ` · ${decision}` : ""}
|
||||
{pr.labels.length ? ` · ${pr.labels.map((l) => l.name).join(", ")}` : ""}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PullRequestList() {
|
||||
const list = useGithub((s) => s.list);
|
||||
const error = useGithub((s) => s.listError);
|
||||
const loading = useGithub((s) => s.listLoading);
|
||||
const selected = useGithub((s) => s.selected);
|
||||
const index = list.findIndex((p) => p.number === selected);
|
||||
const menu = (pr: PullRequestSummary, e: MouseEvent) => {
|
||||
e.preventDefault();
|
||||
const items: MenuItem[] = [
|
||||
{ label: "Checkout", icon: "branch", run: () => void checkoutPullRequest(pr.number) },
|
||||
{ label: "Open in Browser", icon: "external-link", run: () => void openUrl(pr.url) },
|
||||
{ label: "Copy URL", icon: "copy", run: () => void navigator.clipboard?.writeText(pr.url) },
|
||||
];
|
||||
showContextMenu({ x: e.clientX, y: e.clientY }, items);
|
||||
};
|
||||
return (
|
||||
<div className={styles.listPane}>
|
||||
<Filters />
|
||||
{error ? (
|
||||
<div className={styles.error}>{error}</div>
|
||||
) : (
|
||||
<List<PullRequestSummary>
|
||||
items={list}
|
||||
getKey={(p) => String(p.number)}
|
||||
rowHeight={46}
|
||||
activeIndex={index}
|
||||
onActiveChange={(i) => list[i] && select(list[i]!.number)}
|
||||
onActivate={(p) => select(p.number)}
|
||||
onContextMenu={(p, _i, e) => menu(p, e)}
|
||||
renderItem={(p) => <ListRow pr={p} />}
|
||||
empty={<EmptyState title={loading ? "Loading pull requests…" : "No pull requests"} />}
|
||||
aria-label="Pull requests"
|
||||
className={styles.list}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Markdown({ text }: { text: string }) {
|
||||
const html = useMarkupHtml({ kind: "markdown", value: text });
|
||||
if (!text.trim())
|
||||
return (
|
||||
<div className={styles.dim}>
|
||||
<T>No description provided.</T>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div
|
||||
className={styles.markdown}
|
||||
onClick={(e) => {
|
||||
const a = (e.target as HTMLElement).closest("a");
|
||||
if (a?.href && /^https?:/.test(a.href)) {
|
||||
e.preventDefault();
|
||||
void openUrl(a.href);
|
||||
}
|
||||
}}
|
||||
dangerouslySetInnerHTML={{ __html: html }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const CHECK_ICON: Record<PrCheck["status"], string> = {
|
||||
success: "success",
|
||||
failure: "error",
|
||||
pending: "clock",
|
||||
cancelled: "stop",
|
||||
skipped: "minus",
|
||||
neutral: "info",
|
||||
};
|
||||
|
||||
function Overview({ pr }: { pr: PullRequestDetails }) {
|
||||
const summary = checksSummary(pr.checks);
|
||||
return (
|
||||
<div className={styles.scroll}>
|
||||
<Markdown text={pr.body} />
|
||||
<section className={styles.section}>
|
||||
<h3 className={styles.sectionTitle}>{tx`Checks · ${checksText(summary)}`}</h3>
|
||||
{pr.checks.map((c, i) => (
|
||||
<div key={i} className={styles.checkRow}>
|
||||
<Icon name={CHECK_ICON[c.status]} size={14} className={styles[`check-${c.status}`]} />
|
||||
<span className={styles.ellipsis}>
|
||||
{c.workflow ? `${c.workflow} / ` : ""}
|
||||
{c.name}
|
||||
</span>
|
||||
{c.url && (
|
||||
<button type="button" className={styles.link} onClick={() => void openUrl(c.url!)}>
|
||||
<T>Details</T>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
<section className={styles.section}>
|
||||
<h3 className={styles.sectionTitle}>
|
||||
<T>Reviewers</T>
|
||||
</h3>
|
||||
{pr.reviewers.length === 0 && (
|
||||
<div className={styles.dim}>
|
||||
<T>No reviews</T>
|
||||
</div>
|
||||
)}
|
||||
{pr.reviewers.map((r) => (
|
||||
<div key={r.login} className={styles.checkRow}>
|
||||
<Icon
|
||||
name={
|
||||
r.state === "APPROVED"
|
||||
? "success"
|
||||
: r.state === "CHANGES_REQUESTED"
|
||||
? "error"
|
||||
: r.state === "REQUESTED"
|
||||
? "clock"
|
||||
: "info"
|
||||
}
|
||||
size={14}
|
||||
className={styles[`review-${r.state}`]}
|
||||
/>
|
||||
<span>{r.login}</span>
|
||||
<span className={styles.dim}>{reviewStateLabel(r.state)}</span>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
{(pr.summary.labels.length > 0 || pr.assignees.length > 0) && (
|
||||
<section className={styles.section}>
|
||||
{pr.summary.labels.length > 0 && (
|
||||
<div className={styles.labels}>
|
||||
{pr.summary.labels.map((l) => (
|
||||
<span key={l.name} className={styles.label}>
|
||||
{l.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{pr.assignees.length > 0 && <div className={styles.dim}>{tx`Assignees: ${pr.assignees.join(", ")}`}</div>}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Files({ pr }: { pr: PullRequestDetails }) {
|
||||
const comments = useGithub((s) => s.reviewComments);
|
||||
const counts = useMemo(() => {
|
||||
const m = new Map<string, number>();
|
||||
for (const c of comments) m.set(c.path, (m.get(c.path) ?? 0) + 1);
|
||||
return m;
|
||||
}, [comments]);
|
||||
return (
|
||||
<div className={styles.scroll} role="list" aria-label={tx("Changed files")}>
|
||||
{pr.files.map((f) => {
|
||||
const slash = f.path.lastIndexOf("/");
|
||||
return (
|
||||
<button
|
||||
key={f.path}
|
||||
type="button"
|
||||
role="listitem"
|
||||
className={styles.fileRow}
|
||||
onClick={(e) => e.detail <= 1 && void openFileDiff(pr, f)}
|
||||
title={f.path}
|
||||
>
|
||||
<Icon name="diff" size={14} className={styles[`change-${f.changeType}`]} />
|
||||
<span className={clsx(styles.fileName, styles[`change-${f.changeType}`])}>{f.path.slice(slash + 1)}</span>
|
||||
<span className={clsx(styles.dim, styles.ellipsis)}>{slash > 0 ? f.path.slice(0, slash) : ""}</span>
|
||||
<span className={styles.flex} />
|
||||
{counts.get(f.path) ? <span className={styles.dim}>{tx`${counts.get(f.path)} comments`}</span> : null}
|
||||
<span className={styles.added}>+{f.additions}</span>
|
||||
<span className={styles.deleted}>−{f.deletions}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Commits({ pr }: { pr: PullRequestDetails }) {
|
||||
return (
|
||||
<div className={styles.scroll} role="list" aria-label={tx("Commits")}>
|
||||
{pr.commits.map((c) => (
|
||||
<div
|
||||
key={c.oid}
|
||||
role="listitem"
|
||||
className={styles.commitRow}
|
||||
title={c.body || c.headline}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
showContextMenu({ x: e.clientX, y: e.clientY }, [
|
||||
{ label: "Copy Revision Number", icon: "copy", run: () => void navigator.clipboard?.writeText(c.oid) },
|
||||
{
|
||||
label: "Open in Browser",
|
||||
icon: "external-link",
|
||||
run: () => void openUrl(`${pr.summary.url}/commits/${c.oid}`),
|
||||
},
|
||||
]);
|
||||
}}
|
||||
>
|
||||
<span className={styles.ellipsis}>{c.headline}</span>
|
||||
<span className={styles.flex} />
|
||||
<span className={styles.dim}>{c.author}</span>
|
||||
<span className={styles.dim}>{relativeTime(c.date)}</span>
|
||||
<code className={styles.oid}>{c.oid.slice(0, 8)}</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Conversation({ pr }: { pr: PullRequestDetails }) {
|
||||
const comments = useGithub((s) => s.reviewComments);
|
||||
const threads = useMemo(() => reviewThreads(comments), [comments]);
|
||||
const [draft, setDraft] = useState("");
|
||||
const [posting, setPosting] = useState(false);
|
||||
return (
|
||||
<div className={styles.scroll}>
|
||||
{pr.timeline.map((t, i) => (
|
||||
<article key={i} className={styles.comment}>
|
||||
<header className={styles.commentHead}>
|
||||
<strong>{t.author}</strong>
|
||||
{t.reviewState && (
|
||||
<span className={styles[`review-${t.reviewState}`]}>{reviewStateLabel(t.reviewState)}</span>
|
||||
)}
|
||||
<span className={styles.dim}>{relativeTime(t.createdAt)}</span>
|
||||
</header>
|
||||
{t.body.trim() && <Markdown text={t.body} />}
|
||||
</article>
|
||||
))}
|
||||
{threads.length > 0 && (
|
||||
<h3 className={styles.sectionTitle}>
|
||||
<T>Review comments</T>
|
||||
</h3>
|
||||
)}
|
||||
{threads.map((t) => (
|
||||
<article key={t.root.id} className={styles.comment}>
|
||||
<header className={styles.commentHead}>
|
||||
<button type="button" className={styles.link} onClick={() => void openCommentLocation(pr, t.root.path)}>
|
||||
{t.root.path}:{t.root.line ?? t.root.originalLine ?? "?"}
|
||||
</button>
|
||||
{t.root.line == null && (
|
||||
<span className={styles.dim}>
|
||||
<T>outdated</T>
|
||||
</span>
|
||||
)}
|
||||
</header>
|
||||
{[t.root, ...t.replies].map((c) => (
|
||||
<div key={c.id} className={styles.threadItem}>
|
||||
<div className={styles.commentHead}>
|
||||
<strong>{c.author}</strong>
|
||||
<span className={styles.dim}>{relativeTime(c.createdAt)}</span>
|
||||
</div>
|
||||
<Markdown text={c.body} />
|
||||
</div>
|
||||
))}
|
||||
</article>
|
||||
))}
|
||||
<div className={styles.newComment}>
|
||||
<textarea
|
||||
aria-label={tx("New comment")}
|
||||
placeholder={tx("Add a comment (Markdown)")}
|
||||
className={styles.textarea}
|
||||
rows={4}
|
||||
value={draft}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
/>
|
||||
<div className={styles.filterRow}>
|
||||
<span className={styles.flex} />
|
||||
<Button
|
||||
size="small"
|
||||
variant="primary"
|
||||
disabled={!draft.trim() || posting}
|
||||
onClick={async () => {
|
||||
setPosting(true);
|
||||
if (await addComment(pr.summary.number, draft)) setDraft("");
|
||||
setPosting(false);
|
||||
}}
|
||||
>
|
||||
<T>Comment</T>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Details() {
|
||||
const pr = useGithub((s) => s.details);
|
||||
const loading = useGithub((s) => s.detailsLoading);
|
||||
const error = useGithub((s) => s.detailsError);
|
||||
const selected = useGithub((s) => s.selected);
|
||||
const tab = useGithub((s) => s.tab);
|
||||
const comments = useGithub((s) => s.reviewComments);
|
||||
if (!pr || pr.summary.number !== selected) {
|
||||
if (error) return <EmptyState title="Could not load the pull request">{error}</EmptyState>;
|
||||
return loading ? (
|
||||
<div className={styles.loading}>
|
||||
<Spinner size={14} /> <T>Loading…</T>
|
||||
</div>
|
||||
) : (
|
||||
<EmptyState title="Select a pull request" />
|
||||
);
|
||||
}
|
||||
const s = pr.summary;
|
||||
const reviewMenu = (e: MouseEvent<HTMLButtonElement>) => {
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
showContextMenu({ x: r.left, y: r.bottom + 2 }, [
|
||||
{ label: "Approve…", icon: "success", run: () => void submitReview(s.number, "approve") },
|
||||
{ label: "Request Changes…", icon: "error", run: () => void submitReview(s.number, "requestChanges") },
|
||||
{ label: "Comment…", icon: "edit", run: () => void submitReview(s.number, "comment") },
|
||||
]);
|
||||
};
|
||||
return (
|
||||
<div className={styles.details}>
|
||||
<header className={styles.header}>
|
||||
<div className={styles.titleRow}>
|
||||
<h2 className={styles.title}>{s.title}</h2>
|
||||
{loading && <Spinner size={12} />}
|
||||
</div>
|
||||
<div className={styles.metaRow}>
|
||||
<StateBadge pr={s} />
|
||||
<span>
|
||||
#{s.number} {tx`by ${s.author}`} · {s.baseRef} ← {s.headRef}
|
||||
</span>
|
||||
{reviewDecisionLabel(s.reviewDecision) && (
|
||||
<span className={styles.dim}>· {reviewDecisionLabel(s.reviewDecision)}</span>
|
||||
)}
|
||||
{pr.mergeable === "CONFLICTING" && (
|
||||
<span className={styles.conflict}>
|
||||
<T>· Conflicts</T>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.actions}>
|
||||
<Button size="small" icon="branch" onClick={() => void checkoutPullRequest(s.number)}>
|
||||
<T>Checkout</T>
|
||||
</Button>
|
||||
<Button size="small" icon="edit" onClick={reviewMenu}>
|
||||
<T>Review ▾</T>
|
||||
</Button>
|
||||
<Button size="small" icon="external-link" onClick={() => void openUrl(s.url)}>
|
||||
<T>Open in Browser</T>
|
||||
</Button>
|
||||
<span className={styles.flex} />
|
||||
<IconButton icon="refresh" size="small" title="Reload" onClick={() => void loadDetails(s.number)} />
|
||||
</div>
|
||||
</header>
|
||||
<Tabs
|
||||
variant="compact"
|
||||
activeId={tab}
|
||||
onSelect={(id) => useGithub.setState({ tab: id as DetailTab })}
|
||||
aria-label="Pull request"
|
||||
items={[
|
||||
{ id: "overview", label: "Overview" },
|
||||
{ id: "files", label: tx`Files ${pr.files.length}` },
|
||||
{ id: "commits", label: tx`Commits ${pr.commits.length}` },
|
||||
{ id: "conversation", label: tx`Conversation ${pr.timeline.length + comments.length}` },
|
||||
]}
|
||||
/>
|
||||
{tab === "overview" && <Overview pr={pr} />}
|
||||
{tab === "files" && <Files pr={pr} />}
|
||||
{tab === "commits" && <Commits pr={pr} />}
|
||||
{tab === "conversation" && <Conversation pr={pr} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BusyBanner() {
|
||||
const busy = useGithub((s) => s.busy);
|
||||
if (!busy) return null;
|
||||
return (
|
||||
<div className={styles.banner} role="status">
|
||||
<Spinner size={12} />
|
||||
<span>{busy.title}</span>
|
||||
<span className={styles.bannerText}>{busy.line}</span>
|
||||
<IconButton icon="close" size="small" title="Cancel" onClick={cancelBusy} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Below this width the list sits above the details instead of beside them. */
|
||||
const SIDE_BY_SIDE_MIN = 560;
|
||||
|
||||
function useNarrow(el: HTMLElement | null): boolean {
|
||||
const [narrow, setNarrow] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!el || typeof ResizeObserver === "undefined") return;
|
||||
const ro = new ResizeObserver(([e]) => setNarrow((e?.contentRect.width ?? Infinity) < SIDE_BY_SIDE_MIN));
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, [el]);
|
||||
return narrow;
|
||||
}
|
||||
|
||||
export function PullRequestsView() {
|
||||
const availability = useGithub((s) => s.availability);
|
||||
const checking = useGithub((s) => s.checking);
|
||||
const [root, setRoot] = useState<HTMLDivElement | null>(null);
|
||||
const narrow = useNarrow(root);
|
||||
useEffect(() => {
|
||||
if (!useGithub.getState().availability) void refreshAll();
|
||||
}, []);
|
||||
if (!availability)
|
||||
return (
|
||||
<div className={styles.loading}>
|
||||
{checking && <Spinner size={14} />} {tx("Connecting to GitHub…")}
|
||||
</div>
|
||||
);
|
||||
if (availability.kind !== "ready")
|
||||
return (
|
||||
<div className={styles.view}>
|
||||
<Unavailable availability={availability} />
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className={styles.view} ref={setRoot}>
|
||||
<BusyBanner />
|
||||
<SplitGroup key={narrow ? "v" : "h"} orientation={narrow ? "vertical" : "horizontal"} className={styles.split}>
|
||||
<SplitPanel defaultSize={narrow ? "40%" : "38%"} minSize={narrow ? "120px" : "220px"}>
|
||||
<PullRequestList />
|
||||
</SplitPanel>
|
||||
<SplitHandle />
|
||||
<SplitPanel minSize={narrow ? "160px" : "280px"}>
|
||||
<Details />
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Header content: the repository the list is for. */
|
||||
export function PullRequestsHeader() {
|
||||
const availability = useGithub((s) => s.availability);
|
||||
if (availability?.kind !== "ready") return null;
|
||||
const name = availability.repo.nameWithOwner;
|
||||
return (
|
||||
<span className={styles.repo} title={name}>
|
||||
{name}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { fragmentsOf, withFragments } from "./document";
|
||||
import { FRAGMENTS } from "./fragments";
|
||||
import * as Q from "./queries";
|
||||
import { GHGraphQLError, graphqlData, parseRest } from "./client";
|
||||
import { timelineItems } from "./requests";
|
||||
|
||||
const definitions = (text: string) => [...text.matchAll(/^\s*fragment\s+(\S+)\s+on\s/gm)].map((m) => m[1]!);
|
||||
const spreads = (text: string) => new Set([...text.matchAll(/^\s*\.\.\.([A-Za-z_]\w*)/gm)].map((m) => m[1]!));
|
||||
|
||||
describe("GraphQL documents", () => {
|
||||
it("ports every IntelliJ fragment and query", () => {
|
||||
expect(Object.keys(FRAGMENTS)).toHaveLength(39);
|
||||
expect(Object.keys(Q)).toHaveLength(40);
|
||||
for (const [name, text] of Object.entries(FRAGMENTS)) expect(definitions(text), name).toEqual([name]);
|
||||
});
|
||||
|
||||
it.each(Object.entries(Q))("sends %s with every fragment it needs, once", (_name, doc) => {
|
||||
const text = withFragments(doc);
|
||||
const defined = definitions(text);
|
||||
expect(new Set(defined).size).toBe(defined.length);
|
||||
for (const s of spreads(text)) expect(defined, s).toContain(s);
|
||||
// Only fragments that are spread somewhere are added.
|
||||
for (const d of fragmentsOf(doc)) expect(spreads(text).has(d), d).toBe(true);
|
||||
});
|
||||
|
||||
it("resolves fragments transitively, like GHGQLQueryLoader", () => {
|
||||
const names = fragmentsOf(Q.issueSearch);
|
||||
expect(names).toEqual(
|
||||
expect.arrayContaining([
|
||||
"pageInfo",
|
||||
"pullRequestInfoShort",
|
||||
"rates",
|
||||
"nodeInfo",
|
||||
"actor",
|
||||
"actorInfo",
|
||||
"userInfo",
|
||||
"user",
|
||||
"labelInfo",
|
||||
"pullRequestReviewer",
|
||||
"teamInfo",
|
||||
"pullRequestReview",
|
||||
"reactions",
|
||||
"reaction",
|
||||
"enterpriseUserAccountInfo",
|
||||
"organizationInfo",
|
||||
]),
|
||||
);
|
||||
expect(names).not.toContain("repository");
|
||||
// Fragments go first, the operation last.
|
||||
expect(withFragments(Q.issueSearch).trim()).toMatch(/^fragment[\s\S]*\nquery issueSearch[\s\S]*\}$/);
|
||||
});
|
||||
|
||||
it("does not add fragments a document defines itself", () => {
|
||||
const text = withFragments(Q.pullRequestTimeline);
|
||||
expect(definitions(text).filter((d) => d === "gitRefName")).toHaveLength(1);
|
||||
expect(fragmentsOf(Q.pullRequestTimeline)).not.toContain("gitRefName");
|
||||
expect(fragmentsOf(Q.pullRequestTimeline)).not.toContain("issueCommentInfo");
|
||||
});
|
||||
|
||||
it("treats inline fragments as selections, not spreads", () => {
|
||||
expect(fragmentsOf(Q.findPendingReview)).toEqual(expect.arrayContaining(["pullRequestPendingReview", "nodeInfo"]));
|
||||
expect(fragmentsOf(`query { node(id: "x") { ... on User { id } } }`)).toEqual([]);
|
||||
});
|
||||
|
||||
it("fails on an unknown fragment", () => {
|
||||
expect(() => withFragments(`query {\n viewer {\n ...nope\n }\n}`)).toThrow(/nope/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("client", () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it("returns data and throws GraphQL errors", () => {
|
||||
expect(graphqlData<{ a: number }>('{"data":{"a":1}}')).toEqual({ a: 1 });
|
||||
expect(() => graphqlData('{"errors":[{"message":"bad"},{"message":"worse"}]}')).toThrow(GHGraphQLError);
|
||||
expect(() => graphqlData('{"errors":[{"message":"bad"}]}')).toThrow("bad");
|
||||
});
|
||||
|
||||
it("flattens slurped REST pages and maps empty bodies to null", () => {
|
||||
expect(parseRest("[[1,2],[3]]", true)).toEqual([1, 2, 3]);
|
||||
expect(parseRest('[{"a":1}]', false)).toEqual([{ a: 1 }]);
|
||||
expect(parseRest(" ", false)).toBeNull();
|
||||
});
|
||||
|
||||
it("sends documents with their fragments through gh", async () => {
|
||||
const ipc = await import("@/platform/ipc");
|
||||
const ghApi = vi
|
||||
.spyOn(ipc.commands, "ghApi")
|
||||
.mockResolvedValue({ status: "ok", data: '{"data":{"repository":null}}' } as never);
|
||||
const { graphql } = await import("./client");
|
||||
await graphql(Q.findRepository, { repoOwner: "o", repoName: "r", cursor: undefined });
|
||||
const req = ghApi.mock.calls[0]![0];
|
||||
expect(req).toMatchObject({ method: "POST", endpoint: "graphql", paginate: false });
|
||||
const body = JSON.parse(req.body!) as { query: string; variables: Record<string, unknown> };
|
||||
expect(body.variables).toEqual({ repoOwner: "o", repoName: "r" });
|
||||
expect(definitions(body.query)).toEqual(expect.arrayContaining(["repository", "repositoryOwnerName", "rates"]));
|
||||
});
|
||||
});
|
||||
|
||||
describe("timeline items", () => {
|
||||
it("drops IntelliJ's ignored types and marks unknown ones", () => {
|
||||
const items = timelineItems([
|
||||
{ __typename: "IssueComment" },
|
||||
{ __typename: "MentionedEvent" },
|
||||
{ __typename: "SubscribedEvent" },
|
||||
{ __typename: "AutoMergeEnabledEvent" },
|
||||
]);
|
||||
expect(items.map((i) => i.__typename)).toEqual(["IssueComment", "Unknown"]);
|
||||
expect(items[1]).toEqual({ __typename: "Unknown", type: "AutoMergeEnabledEvent" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* GitHub API access through gh (`commands.ghApi`, which runs `gh api` in the project root
|
||||
* with gh's authentication), like IntelliJ's `GithubApiRequestExecutor`:
|
||||
*
|
||||
* const data = await graphql<{ repository: … }>(findRepository, { repoOwner, repoName });
|
||||
* const page = await rest<GHLabelDto[]>("GET", `${repoPath()}/labels?per_page=100`);
|
||||
*
|
||||
* Documents are sent with the fragments they spread (`withFragments`). Requests address
|
||||
* the connected repository explicitly (`repoPath()`, `repoVariables()`), not gh's
|
||||
* `{owner}/{repo}` placeholders, since a project can have several GitHub remotes.
|
||||
*/
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { withFragments } from "./document";
|
||||
import type { GHRepositoryCoordinates } from "./types";
|
||||
|
||||
export type GHApiMethod = "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
|
||||
|
||||
/** A GraphQL response with `errors` (IntelliJ's `GithubConfusingException`). */
|
||||
export class GHGraphQLError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly errors: ReadonlyArray<{ message: string; type?: string; path?: unknown[] }>,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "GHGraphQLError";
|
||||
}
|
||||
}
|
||||
|
||||
export const errorMessage = (e: unknown) => (e instanceof Error ? e.message : String(e));
|
||||
|
||||
/** `data` of a GraphQL response body; throws on `errors` (gh usually fails the call first). */
|
||||
export function graphqlData<T>(text: string): T {
|
||||
const json = JSON.parse(text) as { data?: T; errors?: Array<{ message: string; type?: string; path?: unknown[] }> };
|
||||
if (json.errors?.length) throw new GHGraphQLError(json.errors.map((e) => e.message).join("\n"), json.errors);
|
||||
if (json.data === undefined) throw new GHGraphQLError("GitHub returned no data", []);
|
||||
return json.data;
|
||||
}
|
||||
|
||||
/** Runs a document from `queries.ts` with `variables` (undefined values are dropped). */
|
||||
export async function graphql<T>(doc: string, variables: Record<string, unknown> = {}): Promise<T> {
|
||||
const body = JSON.stringify({ query: withFragments(doc), variables: definedOnly(variables) });
|
||||
const text = await call(commands.ghApi({ method: "POST", endpoint: "graphql", body, paginate: false }));
|
||||
return graphqlData<T>(text);
|
||||
}
|
||||
|
||||
function definedOnly(v: Record<string, unknown>): Record<string, unknown> {
|
||||
return Object.fromEntries(Object.entries(v).filter(([, x]) => x !== undefined));
|
||||
}
|
||||
|
||||
/**
|
||||
* A REST call (`endpoint` relative to the API root, e.g. `repos/o/r/pulls/1/files`).
|
||||
* `paginate` follows every `Link` page and concatenates array pages. Empty bodies
|
||||
* (`204 No Content`) come back as `null`.
|
||||
*/
|
||||
export async function rest<T>(
|
||||
method: GHApiMethod,
|
||||
endpoint: string,
|
||||
body?: unknown,
|
||||
opts: { paginate?: boolean } = {},
|
||||
): Promise<T> {
|
||||
const text = await call(
|
||||
commands.ghApi({
|
||||
method,
|
||||
endpoint,
|
||||
body: body === undefined ? null : JSON.stringify(body),
|
||||
paginate: opts.paginate ?? false,
|
||||
}),
|
||||
);
|
||||
return parseRest<T>(text, opts.paginate ?? false);
|
||||
}
|
||||
|
||||
/** Parses a REST body; `--slurp` pages (an array of pages) are flattened when they are arrays. */
|
||||
export function parseRest<T>(text: string, paginated: boolean): T {
|
||||
if (!text.trim()) return null as T;
|
||||
const json = JSON.parse(text) as unknown;
|
||||
if (paginated && Array.isArray(json) && json.every(Array.isArray)) return (json as unknown[][]).flat() as T;
|
||||
return json as T;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The connected repository
|
||||
|
||||
let current: (GHRepositoryCoordinates & { id: string | null }) | null = null;
|
||||
|
||||
/** Set by `data/repository.ts` when the tool window connects (null: disconnected). */
|
||||
export function setCurrentRepository(repo: (GHRepositoryCoordinates & { id: string | null }) | null) {
|
||||
current = repo;
|
||||
}
|
||||
|
||||
/** The connected repository: `owner`, `name` and its GraphQL node `id` (once loaded). */
|
||||
export function currentRepository(): GHRepositoryCoordinates & { id: string | null } {
|
||||
if (!current) throw new Error("Not connected to a GitHub repository");
|
||||
return current;
|
||||
}
|
||||
|
||||
/** `repos/owner/name`, the prefix of the connected repository's REST endpoints. */
|
||||
export function repoPath(repo: GHRepositoryCoordinates = currentRepository()): string {
|
||||
return `repos/${repo.owner}/${repo.name}`;
|
||||
}
|
||||
|
||||
/** The `$repoOwner` / `$repoName` variables of the repository documents. */
|
||||
export function repoVariables(repo: GHRepositoryCoordinates = currentRepository()) {
|
||||
return { repoOwner: repo.owner, repoName: repo.name };
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* GraphQL document assembly, like IntelliJ's `CachingGraphQLQueryLoader`: a document is
|
||||
* sent with every fragment it spreads (`...name`, where the fragment is named after its
|
||||
* file), transitively. Fragments the document defines itself are not added again.
|
||||
*/
|
||||
import { FRAGMENTS } from "./fragments";
|
||||
|
||||
interface Block {
|
||||
body: string;
|
||||
/** Fragments spread in the block and not defined in it. */
|
||||
dependencies: Set<string>;
|
||||
/** Fragments the block defines itself. */
|
||||
defines: Set<string>;
|
||||
}
|
||||
|
||||
const FRAGMENT_DEFINITION = /^fragment\s+(\S+)\s+on\s+.*\{$/;
|
||||
const SPREAD = /^\.\.\.([A-Za-z_]\w*)/;
|
||||
|
||||
function readBlock(text: string): Block {
|
||||
const dependencies = new Set<string>();
|
||||
const defines = new Set<string>();
|
||||
const lines: string[] = [];
|
||||
for (const raw of text.split("\n")) {
|
||||
const line = raw.trim();
|
||||
lines.push(line);
|
||||
const def = FRAGMENT_DEFINITION.exec(line);
|
||||
if (def) defines.add(def[1]!);
|
||||
// `... on User {` is an inline fragment, not a spread.
|
||||
const spread = SPREAD.exec(line);
|
||||
if (spread) dependencies.add(spread[1]!);
|
||||
}
|
||||
for (const d of defines) dependencies.delete(d);
|
||||
return { body: lines.join("\n").trim(), dependencies, defines };
|
||||
}
|
||||
|
||||
const fragmentBlocks = new Map<string, Block>();
|
||||
const documents = new Map<string, { text: string; fragments: string[] }>();
|
||||
|
||||
function fragmentBlock(name: string): Block {
|
||||
let block = fragmentBlocks.get(name);
|
||||
if (!block) {
|
||||
const text = FRAGMENTS[name];
|
||||
if (text === undefined) throw new Error(`Couldn't find file for fragment ${name}`);
|
||||
block = readBlock(text);
|
||||
fragmentBlocks.set(name, block);
|
||||
}
|
||||
return block;
|
||||
}
|
||||
|
||||
function resolve(doc: string): { text: string; fragments: string[] } {
|
||||
const cached = documents.get(doc);
|
||||
if (cached) return cached;
|
||||
const { body, dependencies, defines } = readBlock(doc);
|
||||
const found = new Map<string, Block>();
|
||||
const visit = (names: Iterable<string>) => {
|
||||
for (const name of names) {
|
||||
if (found.has(name) || defines.has(name)) continue;
|
||||
const block = fragmentBlock(name);
|
||||
found.set(name, block);
|
||||
visit(block.dependencies);
|
||||
}
|
||||
};
|
||||
visit(dependencies);
|
||||
const blocks = [...found.values()].reverse();
|
||||
const resolved = { text: [...blocks.map((f) => f.body), body].join("\n"), fragments: [...found.keys()] };
|
||||
documents.set(doc, resolved);
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/** `doc` preceded by the fragments it needs, ready to send (cached per document). */
|
||||
export function withFragments(doc: string): string {
|
||||
return resolve(doc).text;
|
||||
}
|
||||
|
||||
/** Names of the fragments `withFragments(doc)` adds, in discovery order. */
|
||||
export function fragmentsOf(doc: string): string[] {
|
||||
return resolve(doc).fragments;
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
/**
|
||||
* GraphQL fragments of IntelliJ's GitHub plugin (`resources/graphql/fragment`, plus
|
||||
* collaboration-tools' `pageInfo`), verbatim. Each one is named after its file, the
|
||||
* name it is spread with (`...name`); `withFragments` adds the ones a document needs.
|
||||
*/
|
||||
export const FRAGMENTS: Readonly<Record<string, string>> = {
|
||||
actor: `
|
||||
fragment actor on Actor {
|
||||
...actorInfo
|
||||
|
||||
... on User {
|
||||
...userInfo
|
||||
}
|
||||
... on EnterpriseUserAccount {
|
||||
...enterpriseUserAccountInfo
|
||||
}
|
||||
... on Organization {
|
||||
...organizationInfo
|
||||
}
|
||||
}
|
||||
`,
|
||||
actorInfo: `
|
||||
# Just the data that should be present for any type of Actor.
|
||||
fragment actorInfo on Actor {
|
||||
__typename
|
||||
...nodeInfo
|
||||
login
|
||||
url
|
||||
avatarUrl
|
||||
}
|
||||
`,
|
||||
checkRun: `
|
||||
fragment checkRun on CheckRun {
|
||||
name
|
||||
conclusion
|
||||
isRequired(pullRequestNumber: $number) # See: findPullRequestMergeability
|
||||
detailsUrl
|
||||
url
|
||||
}
|
||||
`,
|
||||
checkSuite: `
|
||||
fragment checkSuite on CheckSuite {
|
||||
checkRuns(first: 100) {
|
||||
pageInfo {
|
||||
...pageInfo
|
||||
}
|
||||
nodes {
|
||||
...checkRun
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
comment: `
|
||||
fragment comment on Comment {
|
||||
...nodeInfo
|
||||
author {
|
||||
...actor
|
||||
}
|
||||
body
|
||||
createdAt
|
||||
...reactions
|
||||
}
|
||||
`,
|
||||
commit: `
|
||||
fragment commit on Commit {
|
||||
...commitShort
|
||||
committer {
|
||||
...gitActorInfo
|
||||
}
|
||||
messageBody
|
||||
committedDate
|
||||
parents(first: 100) {
|
||||
nodes {
|
||||
...commitHash
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
commitHash: `
|
||||
fragment commitHash on Commit {
|
||||
...nodeInfo
|
||||
oid
|
||||
abbreviatedOid
|
||||
}
|
||||
`,
|
||||
commitShort: `
|
||||
fragment commitShort on Commit {
|
||||
...commitHash
|
||||
url
|
||||
messageHeadline
|
||||
author {
|
||||
...gitActorInfo
|
||||
}
|
||||
}
|
||||
`,
|
||||
commitStatusContext: `
|
||||
fragment commitStatusContext on StatusContext {
|
||||
context
|
||||
state
|
||||
isRequired(pullRequestNumber: $number) # See: findPullRequestMergeability
|
||||
targetUrl
|
||||
}
|
||||
`,
|
||||
commitStatusRollup: `
|
||||
fragment commitStatusRollup on StatusCheckRollup {
|
||||
contexts(first: $pageSize, after: $cursor) {
|
||||
pageInfo {
|
||||
...pageInfo
|
||||
}
|
||||
nodes {
|
||||
__typename
|
||||
... on CheckRun {
|
||||
checkSuite {
|
||||
workflowRun {
|
||||
workflow {
|
||||
name
|
||||
}
|
||||
}
|
||||
}
|
||||
name
|
||||
title
|
||||
status
|
||||
conclusion
|
||||
url
|
||||
}
|
||||
... on StatusContext {
|
||||
context
|
||||
description
|
||||
state
|
||||
targetUrl
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
commitStatusRollupShort: `
|
||||
fragment commitStatusRollupShort on StatusCheckRollup {
|
||||
state
|
||||
}
|
||||
`,
|
||||
commitWithCheckStatuses: `
|
||||
fragment commitWithCheckStatuses on Commit {
|
||||
...commitHash
|
||||
status {
|
||||
contexts {
|
||||
...commitStatusContext
|
||||
}
|
||||
}
|
||||
|
||||
checkSuites(first: 100) {
|
||||
pageInfo {
|
||||
...pageInfo
|
||||
}
|
||||
nodes {
|
||||
...checkSuite
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
enterpriseUserAccountInfo: `
|
||||
fragment enterpriseUserAccountInfo on EnterpriseUserAccount {
|
||||
name
|
||||
}
|
||||
`,
|
||||
gitActorInfo: `
|
||||
fragment gitActorInfo on GitActor {
|
||||
name
|
||||
email
|
||||
avatarUrl
|
||||
date
|
||||
user {
|
||||
...user
|
||||
}
|
||||
}
|
||||
`,
|
||||
gitRefName: `
|
||||
fragment gitRefName on Ref {
|
||||
name
|
||||
}
|
||||
`,
|
||||
labelInfo: `
|
||||
fragment labelInfo on Label {
|
||||
...nodeInfo
|
||||
url
|
||||
name
|
||||
color
|
||||
}
|
||||
`,
|
||||
nodeInfo: `
|
||||
fragment nodeInfo on Node {
|
||||
id
|
||||
}
|
||||
`,
|
||||
organizationInfo: `
|
||||
fragment organizationInfo on Organization {
|
||||
name
|
||||
}
|
||||
`,
|
||||
pageInfo: `
|
||||
fragment pageInfo on PageInfo {
|
||||
startCursor
|
||||
hasPreviousPage
|
||||
endCursor
|
||||
hasNextPage
|
||||
}
|
||||
`,
|
||||
pullRequestBranchMatch: `
|
||||
fragment pullRequestBranchMatch on PullRequest {
|
||||
...nodeInfo
|
||||
number
|
||||
title
|
||||
headRefName
|
||||
}
|
||||
`,
|
||||
pullRequestCommitWithCheckStatuses: `
|
||||
fragment pullRequestCommitWithCheckStatuses on PullRequestCommit {
|
||||
...nodeInfo
|
||||
commit {
|
||||
...commitWithCheckStatuses
|
||||
}
|
||||
}
|
||||
`,
|
||||
pullRequestInfo: `
|
||||
fragment pullRequestInfo on PullRequest {
|
||||
...pullRequestInfoShort
|
||||
|
||||
body
|
||||
|
||||
author {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
|
||||
reviewDecision
|
||||
|
||||
baseRefName
|
||||
baseRefOid
|
||||
baseRepository {
|
||||
...repository
|
||||
}
|
||||
|
||||
headRef {
|
||||
id
|
||||
}
|
||||
headRefName
|
||||
headRefOid
|
||||
headRepository {
|
||||
...repository
|
||||
}
|
||||
|
||||
viewerCanDeleteHeadRef
|
||||
}
|
||||
`,
|
||||
pullRequestInfoShort: `
|
||||
fragment pullRequestInfoShort on PullRequest {
|
||||
...nodeInfo
|
||||
url
|
||||
number
|
||||
|
||||
title
|
||||
state
|
||||
isDraft
|
||||
|
||||
author {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
updatedAt
|
||||
|
||||
isReadByViewer
|
||||
|
||||
assignees(first: 100) {
|
||||
nodes {
|
||||
...user
|
||||
}
|
||||
}
|
||||
labels(first: 100) {
|
||||
nodes {
|
||||
...labelInfo
|
||||
}
|
||||
}
|
||||
reviewRequests(first: 100) {
|
||||
nodes {
|
||||
... on ReviewRequest {
|
||||
requestedReviewer {
|
||||
...pullRequestReviewer
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
reviewThreads(last: 100) {
|
||||
nodes {
|
||||
isResolved
|
||||
isOutdated
|
||||
}
|
||||
}
|
||||
reviews(last: 100) {
|
||||
nodes {
|
||||
...pullRequestReview
|
||||
}
|
||||
}
|
||||
...reactions
|
||||
|
||||
mergeable
|
||||
|
||||
viewerCanUpdate
|
||||
viewerCanReact
|
||||
viewerDidAuthor
|
||||
}
|
||||
`,
|
||||
pullRequestMergeability: `
|
||||
fragment pullRequestMergeability on PullRequest {
|
||||
mergeable
|
||||
canBeRebased
|
||||
mergeStateStatus
|
||||
baseRef {
|
||||
refUpdateRule {
|
||||
...refUpdateRule
|
||||
}
|
||||
}
|
||||
|
||||
commits(last: 1) {
|
||||
pageInfo {
|
||||
...pageInfo
|
||||
}
|
||||
nodes {
|
||||
...pullRequestCommitWithCheckStatuses
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
pullRequestPendingReview: `
|
||||
fragment pullRequestPendingReview on PullRequestReview {
|
||||
...nodeInfo
|
||||
state
|
||||
comments(first: 0) {
|
||||
totalCount
|
||||
}
|
||||
}
|
||||
`,
|
||||
pullRequestReview: `
|
||||
fragment pullRequestReview on PullRequestReview {
|
||||
__typename
|
||||
...nodeInfo
|
||||
url
|
||||
author {
|
||||
...actor
|
||||
}
|
||||
body
|
||||
state
|
||||
createdAt
|
||||
viewerCanUpdate
|
||||
}
|
||||
`,
|
||||
pullRequestReviewComment: `
|
||||
fragment pullRequestReviewComment on PullRequestReviewComment {
|
||||
...comment
|
||||
url
|
||||
state
|
||||
commit {
|
||||
...commitHash
|
||||
}
|
||||
originalCommit {
|
||||
...commitHash
|
||||
}
|
||||
diffHunk
|
||||
pullRequestReview {
|
||||
...nodeInfo
|
||||
}
|
||||
viewerCanDelete
|
||||
viewerCanUpdate
|
||||
viewerCanReact
|
||||
}
|
||||
`,
|
||||
pullRequestReviewer: `
|
||||
fragment pullRequestReviewer on RequestedReviewer {
|
||||
... on Actor {
|
||||
...actorInfo
|
||||
}
|
||||
... on User {
|
||||
...userInfo
|
||||
}
|
||||
... on Team {
|
||||
...teamInfo
|
||||
}
|
||||
|
||||
# For future enthusiasts: be careful with adding ... on Bot, as it's been added only in GHE 3.11
|
||||
}
|
||||
`,
|
||||
pullRequestReviewThread: `
|
||||
fragment pullRequestReviewThread on PullRequestReviewThread {
|
||||
...nodeInfo
|
||||
isResolved
|
||||
isOutdated
|
||||
path
|
||||
subjectType
|
||||
diffSide
|
||||
line
|
||||
originalLine
|
||||
startDiffSide
|
||||
startLine
|
||||
originalStartLine
|
||||
comments(first: 100) {
|
||||
nodes {
|
||||
...pullRequestReviewComment
|
||||
}
|
||||
}
|
||||
viewerCanReply
|
||||
viewerCanResolve
|
||||
viewerCanUnresolve
|
||||
}
|
||||
`,
|
||||
pullRequestTemplate: `
|
||||
fragment pullRequestTemplate on PullRequestTemplate {
|
||||
body
|
||||
}
|
||||
`,
|
||||
rates: `
|
||||
fragment rates on RateLimit {
|
||||
cost
|
||||
}
|
||||
`,
|
||||
reaction: `
|
||||
fragment reaction on Reaction {
|
||||
content
|
||||
user {
|
||||
...user
|
||||
}
|
||||
}
|
||||
`,
|
||||
reactions: `
|
||||
fragment reactions on Reactable {
|
||||
reactions(first: 25) {
|
||||
pageInfo {
|
||||
...pageInfo
|
||||
}
|
||||
nodes {
|
||||
...reaction
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
refUpdateRule: `
|
||||
fragment refUpdateRule on RefUpdateRule {
|
||||
allowsDeletions
|
||||
allowsForcePushes
|
||||
pattern
|
||||
requiredApprovingReviewCount
|
||||
requiredStatusCheckContexts
|
||||
requiresLinearHistory
|
||||
requiresSignatures
|
||||
viewerCanPush
|
||||
}
|
||||
`,
|
||||
repository: `
|
||||
fragment repository on Repository {
|
||||
...nodeInfo
|
||||
owner {
|
||||
...repositoryOwnerName
|
||||
}
|
||||
nameWithOwner
|
||||
viewerPermission
|
||||
|
||||
mergeCommitAllowed
|
||||
squashMergeAllowed
|
||||
rebaseMergeAllowed
|
||||
|
||||
defaultBranchRef {
|
||||
...gitRefName
|
||||
}
|
||||
isFork
|
||||
url
|
||||
sshUrl
|
||||
}
|
||||
`,
|
||||
repositoryOwnerName: `
|
||||
fragment repositoryOwnerName on RepositoryOwner {
|
||||
__typename
|
||||
...nodeInfo
|
||||
login
|
||||
}
|
||||
`,
|
||||
teamInfo: `
|
||||
fragment teamInfo on Team {
|
||||
__typename
|
||||
...nodeInfo
|
||||
slug
|
||||
url
|
||||
teamAvatarUrl: avatarUrl
|
||||
teamName: name
|
||||
combinedSlug
|
||||
}
|
||||
`,
|
||||
user: `
|
||||
fragment user on User {
|
||||
...actorInfo
|
||||
...userInfo
|
||||
}
|
||||
`,
|
||||
userInfo: `
|
||||
fragment userInfo on User {
|
||||
name
|
||||
}
|
||||
`,
|
||||
};
|
||||
@@ -0,0 +1,852 @@
|
||||
/**
|
||||
* GraphQL documents of IntelliJ's GitHub plugin (`resources/graphql/query`), verbatim and
|
||||
* named after their files. They spread fragments from `fragments.ts`, which
|
||||
* `withFragments` (in `document.ts`) appends before a document is sent.
|
||||
*/
|
||||
|
||||
export const addPullRequestReviewThread = `
|
||||
mutation ($body: String!, $line: Int!, $path: String!, $pullRequestReviewId: ID, $side: DiffSide, $startSide: DiffSide, $startLine: Int) {
|
||||
addPullRequestReviewThread(input: {body: $body, line: $line, path: $path, pullRequestReviewId:$pullRequestReviewId, side: $side, startSide: $startSide, startLine: $startLine}) {
|
||||
thread {
|
||||
...pullRequestReviewThread
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const addReaction = `
|
||||
mutation ($id: ID!, $reaction: ReactionContent!) {
|
||||
addReaction(input: {
|
||||
subjectId: $id,
|
||||
content: $reaction
|
||||
}) {
|
||||
reaction {
|
||||
...reaction
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const addReviewComment = `
|
||||
mutation ($reviewId: ID!, $body: String!, $commit: GitObjectID, $file: String, $position: Int, $inReplyTo: ID) {
|
||||
addPullRequestReviewComment(input: {pullRequestReviewId: $reviewId, body: $body, commitOID: $commit, path: $file, position: $position, inReplyTo: $inReplyTo}) {
|
||||
comment {
|
||||
...pullRequestReviewComment
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const createPullRequest = `
|
||||
mutation ($repositoryId: ID!, $baseRefName: String!, $headRefName: String!, $title: String!, $body: String, $draft: Boolean = false) {
|
||||
createPullRequest(input: {
|
||||
repositoryId: $repositoryId,
|
||||
baseRefName: $baseRefName,
|
||||
headRefName: $headRefName,
|
||||
title: $title,
|
||||
body: $body,
|
||||
draft: $draft
|
||||
}) {
|
||||
pullRequest {
|
||||
...pullRequestInfoShort
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const createReview = `
|
||||
mutation ($pullRequestId: ID!, $event: PullRequestReviewEvent, $body: String, $commitOid: GitObjectID, $threads: [DraftPullRequestReviewThread]) {
|
||||
addPullRequestReview(input: {pullRequestId: $pullRequestId, event: $event, body: $body, commitOID: $commitOid, threads: $threads}) {
|
||||
pullRequestReview {
|
||||
...pullRequestPendingReview
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const deleteIssueComment = `
|
||||
mutation ($id: ID!) {
|
||||
deleteIssueComment(input: {id: $id}) {
|
||||
__typename
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const deleteRef = `
|
||||
mutation ($refId: ID!) {
|
||||
deleteRef(input: {refId: $refId}) {
|
||||
clientMutationId
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const deleteReview = `
|
||||
mutation ($reviewId: ID!){
|
||||
deletePullRequestReview(input: {pullRequestReviewId: $reviewId}) {
|
||||
__typename
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const deleteReviewComment = `
|
||||
mutation ($id: ID!) {
|
||||
deletePullRequestReviewComment(input: {id: $id}) {
|
||||
pullRequestReview {
|
||||
...pullRequestPendingReview
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const findMentionableUsers = `
|
||||
query($repoOwner: String!, $repoName: String!, $pageSize: Int = 100, $cursor: String) {
|
||||
repository(owner: $repoOwner, name: $repoName) {
|
||||
mentionableUsers(first: $pageSize, after: $cursor) {
|
||||
pageInfo {
|
||||
...pageInfo
|
||||
}
|
||||
nodes {
|
||||
...user
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const findOrganizationTeams = `
|
||||
query($organization: String!, $pageSize: Int = 100, $cursor: String) {
|
||||
organization(login: $organization) {
|
||||
teams(first: $pageSize, after: $cursor) {
|
||||
pageInfo {
|
||||
...pageInfo
|
||||
}
|
||||
nodes {
|
||||
...teamInfo
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const findPendingReview = `
|
||||
query($pullRequestId: ID!) {
|
||||
node(id: $pullRequestId) {
|
||||
... on PullRequest {
|
||||
reviews(states: [PENDING], first: 1) {
|
||||
nodes {
|
||||
...pullRequestPendingReview
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const findPullRequest = `
|
||||
query($repoOwner: String!, $repoName: String!, $number: Int!) {
|
||||
repository(owner: $repoOwner, name: $repoName) {
|
||||
pullRequest(number: $number) {
|
||||
...pullRequestInfo
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const findPullRequestId = `
|
||||
query($repoOwner: String!, $repoName: String!, $number: Int!) {
|
||||
repository(owner: $repoOwner, name: $repoName) {
|
||||
pullRequest(number: $number) {
|
||||
...nodeInfo
|
||||
number
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const findPullRequestMergeability = `
|
||||
query($repoOwner: String!, $repoName: String!, $number: Int!) {
|
||||
repository(owner: $repoOwner, name: $repoName) {
|
||||
pullRequest(number: $number) {
|
||||
...pullRequestMergeability
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const findPullRequestsByHeadBranch = `
|
||||
query findPullRequestsByHeadBranch($query: String!, $pageSize: Int = 100, $cursor: String) {
|
||||
search(first: $pageSize, after: $cursor, type: ISSUE_ADVANCED, query: $query) {
|
||||
pageInfo {
|
||||
...pageInfo
|
||||
}
|
||||
nodes {
|
||||
...pullRequestBranchMatch
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const findRepository = `
|
||||
query($repoOwner: String!, $repoName: String!) {
|
||||
repository(owner: $repoOwner, name: $repoName) {
|
||||
...repository
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const findUser = `
|
||||
query($login: String!) {
|
||||
user(login: $login) {
|
||||
__typename
|
||||
...user
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const getProtectionRules = `
|
||||
query($repoOwner: String!, $repoName: String!, $pageSize: Int = 100, $cursor: String) {
|
||||
repository(owner: $repoOwner, name: $repoName) {
|
||||
branchProtectionRules(first: $pageSize, after: $cursor) {
|
||||
pageInfo {
|
||||
...pageInfo
|
||||
}
|
||||
nodes {
|
||||
...nodeInfo
|
||||
pattern
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const getPullRequestTemplates = `
|
||||
query($repoOwner: String!, $repoName: String!) {
|
||||
repository(owner: $repoOwner, name: $repoName) {
|
||||
pullRequestTemplates {
|
||||
...pullRequestTemplate
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const getRepositoryCommitStatusContexts = `
|
||||
query($repoOwner: String!, $repoName: String!, $oid: GitObjectID!, $pageSize: Int, $cursor: String) {
|
||||
repository(owner: $repoOwner, name: $repoName) {
|
||||
object(oid: $oid) {
|
||||
... on Commit {
|
||||
statusCheckRollup {
|
||||
...commitStatusRollup
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const getRepositoryCommitStatusShort = `
|
||||
query($repoOwner: String!, $repoName: String!, $oid: GitObjectID!) {
|
||||
repository(owner: $repoOwner, name: $repoName) {
|
||||
object(oid: $oid) {
|
||||
... on Commit {
|
||||
statusCheckRollup {
|
||||
...commitStatusRollupShort
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
// `ISSUE_ADVANCED` rather than IntelliJ's `ISSUE`: only the advanced search understands
|
||||
// `OR`, `AND` and parentheses in the typed query.
|
||||
export const issueSearch = `
|
||||
query issueSearch($query: String!, $pageSize: Int = 100, $cursor: String) {
|
||||
search(first: $pageSize, after: $cursor, type: ISSUE_ADVANCED, query: $query) {
|
||||
pageInfo {
|
||||
...pageInfo
|
||||
}
|
||||
nodes {
|
||||
...pullRequestInfoShort
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const markFileAsViewed = `
|
||||
mutation ($pullRequestId: ID!, $path: String!) {
|
||||
markFileAsViewed(input: { pullRequestId: $pullRequestId, path: $path }) {
|
||||
__typename
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const markPullRequestReadyForReview = `
|
||||
mutation ($pullRequestId: ID!) {
|
||||
markPullRequestReadyForReview(input: {pullRequestId: $pullRequestId}) {
|
||||
__typename
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const metrics = `
|
||||
query metrics(
|
||||
$allPRCountQuery: String!,
|
||||
$openPRCountQuery: String!,
|
||||
$openAuthoredPRCountQuery: String!,
|
||||
$openAssigneePRCountQuery: String!,
|
||||
$openReviewedPRCountQuery: String!,
|
||||
$openReviewAssignedPRCountQuery: String!,
|
||||
) {
|
||||
allPRCount: search(type: ISSUE, query: $allPRCountQuery) {
|
||||
issueCount
|
||||
}
|
||||
|
||||
openPRCount: search(type: ISSUE, query: $openPRCountQuery) {
|
||||
issueCount
|
||||
}
|
||||
|
||||
openAuthoredPRCount: search(type: ISSUE, query: $openAuthoredPRCountQuery) {
|
||||
issueCount
|
||||
}
|
||||
|
||||
openAssigneePRCount: search(type: ISSUE, query: $openAssigneePRCountQuery) {
|
||||
issueCount
|
||||
}
|
||||
|
||||
openReviewedPRCount: search(type: ISSUE, query: $openReviewedPRCountQuery) {
|
||||
issueCount
|
||||
}
|
||||
|
||||
openReviewAssignedPRCount: search(type: ISSUE, query: $openReviewAssignedPRCountQuery) {
|
||||
issueCount
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const pullRequestCommits = `
|
||||
query($repoOwner: String!, $repoName: String!, $number: Int!, $pageSize: Int = 100, $cursor: String) {
|
||||
repository(owner: $repoOwner, name: $repoName) {
|
||||
pullRequest(number: $number) {
|
||||
commits(first: $pageSize, after: $cursor) {
|
||||
pageInfo {
|
||||
...pageInfo
|
||||
}
|
||||
nodes {
|
||||
...nodeInfo
|
||||
commit {
|
||||
...commit
|
||||
}
|
||||
url
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const pullRequestFiles = `
|
||||
query($repoOwner: String!, $repoName: String!, $number: Int!, $pageSize: Int = 100, $cursor: String) {
|
||||
repository(owner: $repoOwner, name: $repoName) {
|
||||
pullRequest(number: $number) {
|
||||
files(first: $pageSize, after: $cursor) {
|
||||
pageInfo {
|
||||
...pageInfo
|
||||
}
|
||||
nodes {
|
||||
path
|
||||
viewerViewedState
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const pullRequestParticipants = `
|
||||
query($repoOwner: String!, $repoName: String!, $number: Int!, $pageSize: Int = 100, $cursor: String) {
|
||||
repository(owner: $repoOwner, name: $repoName) {
|
||||
pullRequest(number: $number) {
|
||||
participants(first: $pageSize, after: $cursor) {
|
||||
pageInfo {
|
||||
...pageInfo
|
||||
}
|
||||
nodes {
|
||||
...user
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const pullRequestReviewThreads = `
|
||||
query($repoOwner: String!, $repoName: String!, $number: Int!, $pageSize: Int = 100, $cursor: String) {
|
||||
repository(owner: $repoOwner, name: $repoName) {
|
||||
pullRequest(number: $number) {
|
||||
reviewThreads(first: $pageSize, after: $cursor) {
|
||||
pageInfo {
|
||||
...pageInfo
|
||||
}
|
||||
nodes {
|
||||
...pullRequestReviewThread
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const pullRequestTimeline = `
|
||||
fragment issueCommentInfo on IssueComment {
|
||||
...comment
|
||||
viewerCanUpdate
|
||||
viewerCanDelete
|
||||
viewerCanReact
|
||||
}
|
||||
|
||||
fragment prCommitInfo on PullRequestCommit {
|
||||
...nodeInfo
|
||||
commit {
|
||||
...commitShort
|
||||
}
|
||||
url
|
||||
}
|
||||
|
||||
fragment reviewDismissedEvent on ReviewDismissedEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
dismissalMessageHTML
|
||||
review {
|
||||
author {
|
||||
...actor
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fragment readyForReviewEvent on ReadyForReviewEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
}
|
||||
|
||||
fragment convertToDraftEvent on ConvertToDraftEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
}
|
||||
|
||||
fragment renamedEvent on RenamedTitleEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
previousTitle
|
||||
currentTitle
|
||||
createdAt
|
||||
}
|
||||
|
||||
fragment closedEvent on ClosedEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
}
|
||||
|
||||
fragment reopenedEvent on ReopenedEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
}
|
||||
|
||||
fragment mergedEvent on MergedEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
mergedEventCommit: commit {
|
||||
...commitShort
|
||||
}
|
||||
mergeRefName
|
||||
}
|
||||
|
||||
fragment assignedEvent on AssignedEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
user {
|
||||
...user
|
||||
}
|
||||
}
|
||||
|
||||
fragment unassignedEvent on UnassignedEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
user {
|
||||
...user
|
||||
}
|
||||
}
|
||||
|
||||
fragment labeledEvent on LabeledEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
label {
|
||||
...labelInfo
|
||||
}
|
||||
}
|
||||
|
||||
fragment unlabeledEvent on UnlabeledEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
label {
|
||||
...labelInfo
|
||||
}
|
||||
}
|
||||
|
||||
fragment reviewRequestedEvent on ReviewRequestedEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
requestedReviewer {
|
||||
...pullRequestReviewer
|
||||
}
|
||||
}
|
||||
|
||||
fragment reviewRequestRemovedEvent on ReviewRequestRemovedEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
requestedReviewer {
|
||||
...pullRequestReviewer
|
||||
}
|
||||
}
|
||||
|
||||
fragment gitRefName on Ref {
|
||||
name
|
||||
}
|
||||
|
||||
fragment baseRefForcePushedEvent on BaseRefForcePushedEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
ref {
|
||||
...gitRefName
|
||||
}
|
||||
}
|
||||
|
||||
fragment headRefForcePushedEvent on HeadRefForcePushedEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
ref {
|
||||
...gitRefName
|
||||
}
|
||||
beforeCommit {
|
||||
...commitHash
|
||||
}
|
||||
afterCommit {
|
||||
...commitHash
|
||||
}
|
||||
}
|
||||
|
||||
fragment headRefDeletedEvent on HeadRefDeletedEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
headRefName
|
||||
}
|
||||
|
||||
fragment headRefRestoredEvent on HeadRefRestoredEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
}
|
||||
|
||||
fragment baseRefChangedEvent on BaseRefChangedEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
}
|
||||
|
||||
fragment referenceSubject on ReferencedSubject {
|
||||
__typename
|
||||
... on PullRequest {
|
||||
title
|
||||
number
|
||||
prState: state
|
||||
isDraft
|
||||
url
|
||||
}
|
||||
... on Issue {
|
||||
title
|
||||
number
|
||||
issueState: state
|
||||
url
|
||||
}
|
||||
}
|
||||
|
||||
fragment crossReferencedEvent on CrossReferencedEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
source {
|
||||
...referenceSubject
|
||||
}
|
||||
}
|
||||
|
||||
fragment connectedEvent on ConnectedEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
subject {
|
||||
...referenceSubject
|
||||
}
|
||||
}
|
||||
|
||||
fragment disconnectedEvent on DisconnectedEvent {
|
||||
actor {
|
||||
...actor
|
||||
}
|
||||
createdAt
|
||||
subject {
|
||||
...referenceSubject
|
||||
}
|
||||
}
|
||||
|
||||
query($repoOwner: String!, $repoName: String!, $number: Int!, $pageSize: Int = 100, $cursor: String, $since: DateTime) {
|
||||
repository(owner: $repoOwner, name: $repoName) {
|
||||
pullRequest(number: $number) {
|
||||
timelineItems(first: $pageSize, after: $cursor, since: $since) {
|
||||
pageInfo {
|
||||
...pageInfo
|
||||
}
|
||||
nodes {
|
||||
__typename
|
||||
...prCommitInfo
|
||||
...pullRequestReview
|
||||
...issueCommentInfo
|
||||
|
||||
...renamedEvent
|
||||
|
||||
...closedEvent
|
||||
...reopenedEvent
|
||||
...mergedEvent
|
||||
|
||||
...assignedEvent
|
||||
...unassignedEvent
|
||||
|
||||
...labeledEvent
|
||||
...unlabeledEvent
|
||||
|
||||
...reviewRequestedEvent
|
||||
...reviewRequestRemovedEvent
|
||||
|
||||
...reviewDismissedEvent
|
||||
|
||||
...readyForReviewEvent
|
||||
...convertToDraftEvent
|
||||
|
||||
...baseRefChangedEvent
|
||||
...baseRefForcePushedEvent
|
||||
|
||||
...headRefForcePushedEvent
|
||||
...headRefDeletedEvent
|
||||
...headRefRestoredEvent
|
||||
|
||||
...crossReferencedEvent
|
||||
...connectedEvent
|
||||
...disconnectedEvent
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rateLimit {
|
||||
...rates
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const removeReaction = `
|
||||
mutation ($id: ID!, $reaction: ReactionContent!) {
|
||||
removeReaction(input: {
|
||||
subjectId: $id,
|
||||
content: $reaction
|
||||
}) {
|
||||
reaction {
|
||||
...reaction
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const resolveReviewThread = `
|
||||
mutation ($threadId: ID!) {
|
||||
resolveReviewThread(input: {threadId: $threadId}) {
|
||||
thread {
|
||||
...pullRequestReviewThread
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const submitReview = `
|
||||
mutation ($reviewId: ID!, $event: PullRequestReviewEvent!, $body: String){
|
||||
submitPullRequestReview(input: {pullRequestReviewId: $reviewId, event: $event, body: $body}) {
|
||||
__typename
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const unmarkFileAsViewed = `
|
||||
mutation ($pullRequestId: ID!, $path: String!) {
|
||||
unmarkFileAsViewed(input: { pullRequestId: $pullRequestId, path: $path }) {
|
||||
__typename
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const unresolveReviewThread = `
|
||||
mutation ($threadId: ID!) {
|
||||
unresolveReviewThread(input: {threadId: $threadId}) {
|
||||
thread {
|
||||
...pullRequestReviewThread
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const updateIssueComment = `
|
||||
mutation ($id: ID!, $body: String!) {
|
||||
updateIssueComment(input: {id: $id, body: $body}) {
|
||||
issueComment {
|
||||
...comment
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const updatePullRequest = `
|
||||
mutation ($pullRequestId: ID!, $title: String, $body: String) {
|
||||
updatePullRequest(input: {pullRequestId: $pullRequestId, title: $title, body: $body}) {
|
||||
pullRequest {
|
||||
...pullRequestInfo
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const updateReview = `
|
||||
mutation ($reviewId: ID!, $body: String!){
|
||||
updatePullRequestReview(input: {pullRequestReviewId: $reviewId, body: $body}) {
|
||||
pullRequestReview {
|
||||
...pullRequestReview
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export const updateReviewComment = `
|
||||
mutation ($id: ID!, $body: String!) {
|
||||
updatePullRequestReviewComment(input: {pullRequestReviewCommentId: $id, body: $body}) {
|
||||
pullRequestReviewComment {
|
||||
...pullRequestReviewComment
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,619 @@
|
||||
/**
|
||||
* Typed GitHub requests, one per IntelliJ `GHGQLRequests` / `GithubApiRequests` call the
|
||||
* plugin makes. Everything addresses the connected repository (`client.ts`) unless a
|
||||
* repository is passed. Mutations only send; `data/operations.ts` refreshes what they
|
||||
* change.
|
||||
*/
|
||||
import { graphql, repoPath, repoVariables, rest } from "./client";
|
||||
import * as Q from "./queries";
|
||||
import type {
|
||||
GHCollaborator,
|
||||
GHCommitFile,
|
||||
GHCommitStatusRollupContext,
|
||||
GHConnection,
|
||||
GHDiffSide,
|
||||
GHComment,
|
||||
GHLabel,
|
||||
GHPRTimelineItem,
|
||||
GHPullRequest,
|
||||
GHPullRequestBranchMatch,
|
||||
GHPullRequestChangedFile,
|
||||
GHPullRequestCommit,
|
||||
GHPullRequestDraftReviewThread,
|
||||
GHPullRequestMergeabilityData,
|
||||
GHPullRequestPendingReview,
|
||||
GHPullRequestReview,
|
||||
GHPullRequestReviewComment,
|
||||
GHPullRequestReviewEvent,
|
||||
GHPullRequestReviewThread,
|
||||
GHPullRequestShort,
|
||||
GHReaction,
|
||||
GHReactionContent,
|
||||
GHRepository,
|
||||
GHRepositoryCoordinates,
|
||||
GHRepositoryPullRequestTemplate,
|
||||
GHTeam,
|
||||
GHUser,
|
||||
} from "./types";
|
||||
|
||||
/** IntelliJ's `PR_PAGE_SIZE`: list rows per `issueSearch` page. */
|
||||
export const PR_PAGE_SIZE = 50;
|
||||
|
||||
type Pr = { repository: { pullRequest: Record<string, unknown> | null } | null };
|
||||
|
||||
/** `repository.pullRequest.<field>` of a pull request document, or null when the PR is gone. */
|
||||
async function prField<T>(doc: string, number: number, field: string, vars: Record<string, unknown> = {}) {
|
||||
const data = await graphql<Pr>(doc, { ...repoVariables(), number, ...vars });
|
||||
return (data.repository?.pullRequest?.[field] as T | undefined) ?? null;
|
||||
}
|
||||
|
||||
/** Every page of a cursor-paged connection, in order. */
|
||||
export async function allPages<T>(page: (cursor: string | null) => Promise<GHConnection<T> | null>): Promise<T[]> {
|
||||
const out: T[] = [];
|
||||
let cursor: string | null = null;
|
||||
for (;;) {
|
||||
const c: GHConnection<T> | null = await page(cursor);
|
||||
if (!c) return out;
|
||||
out.push(...c.nodes);
|
||||
if (!c.pageInfo.hasNextPage || !c.pageInfo.endCursor) return out;
|
||||
cursor = c.pageInfo.endCursor;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Repository and users
|
||||
|
||||
export async function findRepository(repo: GHRepositoryCoordinates): Promise<GHRepository | null> {
|
||||
const data = await graphql<{ repository: GHRepository | null }>(Q.findRepository, repoVariables(repo));
|
||||
return data.repository;
|
||||
}
|
||||
|
||||
/**
|
||||
* A user by login (`findUser`).
|
||||
* @public
|
||||
*/
|
||||
export async function findUser(login: string): Promise<GHUser | null> {
|
||||
return (await graphql<{ user: GHUser | null }>(Q.findUser, { login })).user;
|
||||
}
|
||||
|
||||
interface RestUser {
|
||||
login: string;
|
||||
node_id: string;
|
||||
avatar_url: string;
|
||||
html_url: string;
|
||||
name?: string | null;
|
||||
type?: string;
|
||||
}
|
||||
|
||||
/** A REST user as the GraphQL `user` fragment shape. */
|
||||
export function restUser(u: RestUser): GHUser {
|
||||
return {
|
||||
__typename: "User",
|
||||
id: u.node_id,
|
||||
login: u.login,
|
||||
url: u.html_url,
|
||||
avatarUrl: u.avatar_url,
|
||||
name: u.name ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** The signed-in user (REST `user`, IntelliJ's `CurrentUser.get`). */
|
||||
export async function currentUser(): Promise<GHUser> {
|
||||
return restUser(await rest<RestUser>("GET", "user"));
|
||||
}
|
||||
|
||||
/** Page `page` (1-based) of a REST list; `next` is null on the last page. */
|
||||
async function restPage<T, R>(endpoint: string, page: number, map: (r: R) => T) {
|
||||
const sep = endpoint.includes("?") ? "&" : "?";
|
||||
const items = (await rest<R[] | null>("GET", `${endpoint}${sep}per_page=100&page=${page}`)) ?? [];
|
||||
return { items: items.map(map), next: items.length === 100 ? page + 1 : null };
|
||||
}
|
||||
|
||||
export function collaboratorsPage(page: number) {
|
||||
return restPage<GHCollaborator, RestUser & { permissions?: GHCollaborator["permissions"] }>(
|
||||
`${repoPath()}/collaborators`,
|
||||
page,
|
||||
(u) => ({
|
||||
...restUser(u),
|
||||
permissions: u.permissions ?? { admin: false, maintain: false, push: false, triage: false, pull: true },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function contributorsPage(page: number) {
|
||||
return restPage<GHUser, RestUser>(`${repoPath()}/contributors`, page, restUser);
|
||||
}
|
||||
|
||||
/** Users issues and pull requests can be assigned to. */
|
||||
export function assigneesPage(page: number) {
|
||||
return restPage<GHUser, RestUser>(`${repoPath()}/assignees`, page, restUser);
|
||||
}
|
||||
|
||||
interface RestLabel {
|
||||
node_id: string;
|
||||
url: string;
|
||||
name: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
const restLabel = (l: RestLabel): GHLabel => ({ id: l.node_id, url: l.url, name: l.name, color: l.color });
|
||||
|
||||
export function labelsPage(page: number) {
|
||||
return restPage<GHLabel, RestLabel>(`${repoPath()}/labels`, page, restLabel);
|
||||
}
|
||||
|
||||
export async function mentionableUsersPage(cursor: string | null): Promise<GHConnection<GHUser> | null> {
|
||||
const data = await graphql<{ repository: { mentionableUsers: GHConnection<GHUser> } | null }>(
|
||||
Q.findMentionableUsers,
|
||||
{ ...repoVariables(), cursor },
|
||||
);
|
||||
return data.repository?.mentionableUsers ?? null;
|
||||
}
|
||||
|
||||
export async function organizationTeamsPage(organization: string, cursor: string | null) {
|
||||
const data = await graphql<{ organization: { teams: GHConnection<GHTeam> } | null }>(Q.findOrganizationTeams, {
|
||||
organization,
|
||||
cursor,
|
||||
});
|
||||
return data.organization?.teams ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A page of the branch protection rules (`getProtectionRules`).
|
||||
* @public
|
||||
*/
|
||||
export async function protectionRulesPage(cursor: string | null) {
|
||||
const data = await graphql<{
|
||||
repository: { branchProtectionRules: GHConnection<{ id: string; pattern: string }> } | null;
|
||||
}>(Q.getProtectionRules, { ...repoVariables(), cursor });
|
||||
return data.repository?.branchProtectionRules ?? null;
|
||||
}
|
||||
|
||||
export async function pullRequestTemplates(): Promise<GHRepositoryPullRequestTemplate[]> {
|
||||
const data = await graphql<{ repository: { pullRequestTemplates: GHRepositoryPullRequestTemplate[] | null } | null }>(
|
||||
Q.getPullRequestTemplates,
|
||||
repoVariables(),
|
||||
);
|
||||
return data.repository?.pullRequestTemplates ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* A page of the commit's status check rollup (`getRepositoryCommitStatusContexts`).
|
||||
* @public
|
||||
*/
|
||||
export async function commitStatusContextsPage(oid: string, cursor: string | null, pageSize = 100) {
|
||||
const data = await graphql<{
|
||||
repository: {
|
||||
object: { statusCheckRollup: { contexts: GHConnection<GHCommitStatusRollupContext> } | null } | null;
|
||||
};
|
||||
}>(Q.getRepositoryCommitStatusContexts, { ...repoVariables(), oid, pageSize, cursor });
|
||||
return data.repository.object?.statusCheckRollup?.contexts ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The commit's overall status check state (`getRepositoryCommitStatusShort`).
|
||||
* @public
|
||||
*/
|
||||
export async function commitStatusShort(oid: string): Promise<string | null> {
|
||||
const data = await graphql<{ repository: { object: { statusCheckRollup: { state: string } | null } | null } }>(
|
||||
Q.getRepositoryCommitStatusShort,
|
||||
{ ...repoVariables(), oid },
|
||||
);
|
||||
return data.repository.object?.statusCheckRollup?.state ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The counts of IntelliJ's usage metrics, by query (each a full search string).
|
||||
* @public
|
||||
*/
|
||||
export async function metrics(queries: {
|
||||
allPRCountQuery: string;
|
||||
openPRCountQuery: string;
|
||||
openAuthoredPRCountQuery: string;
|
||||
openAssigneePRCountQuery: string;
|
||||
openReviewedPRCountQuery: string;
|
||||
openReviewAssignedPRCountQuery: string;
|
||||
}): Promise<Record<string, number>> {
|
||||
const data = await graphql<Record<string, { issueCount: number }>>(Q.metrics, queries);
|
||||
return Object.fromEntries(
|
||||
Object.entries(data)
|
||||
.filter(([k]) => k !== "rateLimit")
|
||||
.map(([k, v]) => [k, v.issueCount]),
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pull request queries
|
||||
|
||||
/** One `issueSearch` page: `query` is the full search string (`type:pr repo:o/r …`). */
|
||||
export async function searchPullRequests(query: string, cursor: string | null, pageSize = PR_PAGE_SIZE) {
|
||||
const data = await graphql<{ search: GHConnection<GHPullRequestShort | Record<string, never>> }>(Q.issueSearch, {
|
||||
query,
|
||||
pageSize,
|
||||
cursor,
|
||||
});
|
||||
// `type: ISSUE` may return issues (no fields selected for them: empty objects).
|
||||
const nodes = data.search.nodes.filter((n): n is GHPullRequestShort => "number" in n);
|
||||
return { pageInfo: data.search.pageInfo, nodes };
|
||||
}
|
||||
|
||||
/**
|
||||
* Open pull requests whose head matches the `head:` terms of `query` (`findPullRequestsByHeadBranch`).
|
||||
* @public
|
||||
*/
|
||||
export async function searchPullRequestsByHeadBranches(query: string, pageSize = 100) {
|
||||
const data = await graphql<{ search: GHConnection<GHPullRequestBranchMatch> }>(Q.findPullRequestsByHeadBranch, {
|
||||
query,
|
||||
pageSize,
|
||||
});
|
||||
return data.search.nodes.filter((n) => "number" in n);
|
||||
}
|
||||
|
||||
export async function findPullRequest(number: number): Promise<GHPullRequest | null> {
|
||||
const data = await graphql<{ repository: { pullRequest: GHPullRequest | null } | null }>(Q.findPullRequest, {
|
||||
...repoVariables(),
|
||||
number,
|
||||
});
|
||||
return data.repository?.pullRequest ?? null;
|
||||
}
|
||||
|
||||
export async function findPullRequestId(number: number): Promise<string | null> {
|
||||
return prField<string>(Q.findPullRequestId, number, "id");
|
||||
}
|
||||
|
||||
export async function findPullRequestMergeability(number: number): Promise<GHPullRequestMergeabilityData | null> {
|
||||
const data = await graphql<{ repository: { pullRequest: GHPullRequestMergeabilityData | null } | null }>(
|
||||
Q.findPullRequestMergeability,
|
||||
{ ...repoVariables(), number },
|
||||
);
|
||||
return data.repository?.pullRequest ?? null;
|
||||
}
|
||||
|
||||
export function pullRequestCommitsPage(number: number, cursor: string | null) {
|
||||
return prField<GHConnection<GHPullRequestCommit>>(Q.pullRequestCommits, number, "commits", { cursor });
|
||||
}
|
||||
|
||||
export function pullRequestFilesPage(number: number, cursor: string | null) {
|
||||
return prField<GHConnection<GHPullRequestChangedFile>>(Q.pullRequestFiles, number, "files", { cursor });
|
||||
}
|
||||
|
||||
export function pullRequestParticipantsPage(number: number, cursor: string | null) {
|
||||
return prField<GHConnection<GHUser>>(Q.pullRequestParticipants, number, "participants", { cursor });
|
||||
}
|
||||
|
||||
export function pullRequestReviewThreadsPage(number: number, cursor: string | null) {
|
||||
return prField<GHConnection<GHPullRequestReviewThread>>(Q.pullRequestReviewThreads, number, "reviewThreads", {
|
||||
cursor,
|
||||
});
|
||||
}
|
||||
|
||||
/** Timeline item types IntelliJ drops (`GHPRTimelineItem.IGNORED_TYPES`). */
|
||||
const IGNORED_TIMELINE_TYPES = new Set([
|
||||
"ReferencedEvent",
|
||||
"MentionedEvent",
|
||||
"CommentDeletedEvent",
|
||||
"LockedEvent",
|
||||
"UnlockedEvent",
|
||||
"SubscribedEvent",
|
||||
"UnsubscribedEvent",
|
||||
]);
|
||||
|
||||
/** Item types the timeline document selects fields for. */
|
||||
const TIMELINE_TYPES = new Set([
|
||||
"PullRequestCommit",
|
||||
"PullRequestReview",
|
||||
"IssueComment",
|
||||
"RenamedTitleEvent",
|
||||
"ClosedEvent",
|
||||
"ReopenedEvent",
|
||||
"MergedEvent",
|
||||
"AssignedEvent",
|
||||
"UnassignedEvent",
|
||||
"LabeledEvent",
|
||||
"UnlabeledEvent",
|
||||
"ReviewRequestedEvent",
|
||||
"ReviewRequestRemovedEvent",
|
||||
"ReviewDismissedEvent",
|
||||
"ReadyForReviewEvent",
|
||||
"ConvertToDraftEvent",
|
||||
"BaseRefChangedEvent",
|
||||
"BaseRefForcePushedEvent",
|
||||
"HeadRefForcePushedEvent",
|
||||
"HeadRefDeletedEvent",
|
||||
"HeadRefRestoredEvent",
|
||||
"CrossReferencedEvent",
|
||||
"ConnectedEvent",
|
||||
"DisconnectedEvent",
|
||||
]);
|
||||
|
||||
/** Timeline nodes as items: ignored types dropped, others IntelliJ can't show marked `Unknown`. */
|
||||
export function timelineItems(nodes: ReadonlyArray<{ __typename: string }>): GHPRTimelineItem[] {
|
||||
return nodes.flatMap((n): GHPRTimelineItem[] => {
|
||||
if (IGNORED_TIMELINE_TYPES.has(n.__typename)) return [];
|
||||
if (TIMELINE_TYPES.has(n.__typename)) return [n as GHPRTimelineItem];
|
||||
return [{ __typename: "Unknown", type: n.__typename }];
|
||||
});
|
||||
}
|
||||
|
||||
/** One page (100) of timeline items, after `cursor`. */
|
||||
export async function pullRequestTimelinePage(number: number, cursor: string | null, since?: string) {
|
||||
const c = await prField<GHConnection<{ __typename: string }>>(Q.pullRequestTimeline, number, "timelineItems", {
|
||||
cursor,
|
||||
since,
|
||||
});
|
||||
return c && { pageInfo: c.pageInfo, nodes: timelineItems(c.nodes) };
|
||||
}
|
||||
|
||||
interface PendingReviewNode {
|
||||
id: string;
|
||||
state: GHPullRequestPendingReview["state"];
|
||||
comments: { totalCount: number };
|
||||
}
|
||||
|
||||
const pendingReview = (r: PendingReviewNode): GHPullRequestPendingReview => ({
|
||||
id: r.id,
|
||||
state: r.state,
|
||||
commentsCount: r.comments.totalCount,
|
||||
});
|
||||
|
||||
/** The viewer's pending (not yet submitted) review of the pull request with node id `pullRequestId`. */
|
||||
export async function findPendingReview(pullRequestId: string): Promise<GHPullRequestPendingReview | null> {
|
||||
const data = await graphql<{ node: { reviews?: { nodes: PendingReviewNode[] } } | null }>(Q.findPendingReview, {
|
||||
pullRequestId,
|
||||
});
|
||||
const r = data.node?.reviews?.nodes[0];
|
||||
return r ? pendingReview(r) : null;
|
||||
}
|
||||
|
||||
interface RestCommitFile {
|
||||
sha: string | null;
|
||||
filename: string;
|
||||
status: GHCommitFile["status"];
|
||||
additions: number;
|
||||
deletions: number;
|
||||
changes: number;
|
||||
patch?: string;
|
||||
previous_filename?: string;
|
||||
}
|
||||
|
||||
const commitFile = (f: RestCommitFile): GHCommitFile => ({
|
||||
sha: f.sha,
|
||||
filename: f.filename,
|
||||
status: f.status,
|
||||
additions: f.additions,
|
||||
deletions: f.deletions,
|
||||
changes: f.changes,
|
||||
patch: f.patch ?? null,
|
||||
previousFilename: f.previous_filename ?? null,
|
||||
});
|
||||
|
||||
/** The pull request's changed files (REST `pulls/{n}/files`, every page). */
|
||||
export async function pullRequestChangedFiles(number: number): Promise<GHCommitFile[]> {
|
||||
const files = await rest<RestCommitFile[]>("GET", `${repoPath()}/pulls/${number}/files?per_page=100`, undefined, {
|
||||
paginate: true,
|
||||
});
|
||||
return (files ?? []).map(commitFile);
|
||||
}
|
||||
|
||||
/** The files a commit changes (REST `commits/{sha}`). */
|
||||
export async function commitChangedFiles(sha: string): Promise<GHCommitFile[]> {
|
||||
const commit = await rest<{ files?: RestCommitFile[] }>("GET", `${repoPath()}/commits/${sha}`);
|
||||
return (commit?.files ?? []).map(commitFile);
|
||||
}
|
||||
|
||||
/** The files changed from the merge base of `base` and `head` to `head` (REST `compare/{base}...{head}`). */
|
||||
export async function compareChangedFiles(base: string, head: string): Promise<GHCommitFile[]> {
|
||||
const r = await rest<{ files?: RestCommitFile[] }>("GET", `${repoPath()}/compare/${base}...${head}`);
|
||||
return (r?.files ?? []).map(commitFile);
|
||||
}
|
||||
|
||||
/**
|
||||
* Open pull requests from `head` (`owner:branch`) into `base`, REST `Repos.PullRequests.find`.
|
||||
*/
|
||||
export async function findOpenPullRequestsByHead(
|
||||
head: string,
|
||||
base?: string,
|
||||
): Promise<Array<{ number: number; html_url: string }>> {
|
||||
const q = new URLSearchParams({ state: "open", head, ...(base ? { base } : {}), per_page: "1" });
|
||||
return (await rest<Array<{ number: number; html_url: string }>>("GET", `${repoPath()}/pulls?${q}`)) ?? [];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pull request mutations (GraphQL)
|
||||
|
||||
export async function createPullRequest(input: {
|
||||
repositoryId: string;
|
||||
baseRefName: string;
|
||||
/** `owner:branch` for a branch of a fork. */
|
||||
headRefName: string;
|
||||
title: string;
|
||||
body: string | null;
|
||||
draft: boolean;
|
||||
}): Promise<GHPullRequestShort> {
|
||||
const data = await graphql<{ createPullRequest: { pullRequest: GHPullRequestShort } }>(Q.createPullRequest, input);
|
||||
return data.createPullRequest.pullRequest;
|
||||
}
|
||||
|
||||
export async function updatePullRequest(pullRequestId: string, patch: { title?: string; body?: string }) {
|
||||
const data = await graphql<{ updatePullRequest: { pullRequest: GHPullRequest } }>(Q.updatePullRequest, {
|
||||
pullRequestId,
|
||||
...patch,
|
||||
});
|
||||
return data.updatePullRequest.pullRequest;
|
||||
}
|
||||
|
||||
export async function markPullRequestReadyForReview(pullRequestId: string): Promise<void> {
|
||||
await graphql(Q.markPullRequestReadyForReview, { pullRequestId });
|
||||
}
|
||||
|
||||
export async function markFileAsViewed(pullRequestId: string, path: string): Promise<void> {
|
||||
await graphql(Q.markFileAsViewed, { pullRequestId, path });
|
||||
}
|
||||
|
||||
export async function unmarkFileAsViewed(pullRequestId: string, path: string): Promise<void> {
|
||||
await graphql(Q.unmarkFileAsViewed, { pullRequestId, path });
|
||||
}
|
||||
|
||||
export async function deleteRef(refId: string): Promise<void> {
|
||||
await graphql(Q.deleteRef, { refId });
|
||||
}
|
||||
|
||||
/** `addPullRequestReview`: a pending review without `event`, else a submitted one. */
|
||||
export async function createReview(input: {
|
||||
pullRequestId: string;
|
||||
event?: GHPullRequestReviewEvent | null;
|
||||
body?: string | null;
|
||||
commitOid?: string | null;
|
||||
threads?: GHPullRequestDraftReviewThread[] | null;
|
||||
}): Promise<GHPullRequestPendingReview> {
|
||||
const data = await graphql<{ addPullRequestReview: { pullRequestReview: PendingReviewNode } }>(Q.createReview, input);
|
||||
return pendingReview(data.addPullRequestReview.pullRequestReview);
|
||||
}
|
||||
|
||||
export async function submitReview(reviewId: string, event: GHPullRequestReviewEvent, body?: string | null) {
|
||||
await graphql(Q.submitReview, { reviewId, event, body });
|
||||
}
|
||||
|
||||
export async function deleteReview(reviewId: string): Promise<void> {
|
||||
await graphql(Q.deleteReview, { reviewId });
|
||||
}
|
||||
|
||||
export async function updateReview(reviewId: string, body: string): Promise<GHPullRequestReview> {
|
||||
const data = await graphql<{ updatePullRequestReview: { pullRequestReview: GHPullRequestReview } }>(Q.updateReview, {
|
||||
reviewId,
|
||||
body,
|
||||
});
|
||||
return data.updatePullRequestReview.pullRequestReview;
|
||||
}
|
||||
|
||||
/** `addPullRequestReviewComment`: a reply (`inReplyTo`), or a comment on a commit position. */
|
||||
export async function addReviewComment(input: {
|
||||
reviewId: string;
|
||||
body: string;
|
||||
commit?: string | null;
|
||||
file?: string | null;
|
||||
position?: number | null;
|
||||
inReplyTo?: string | null;
|
||||
}): Promise<GHPullRequestReviewComment> {
|
||||
const data = await graphql<{ addPullRequestReviewComment: { comment: GHPullRequestReviewComment } }>(
|
||||
Q.addReviewComment,
|
||||
input,
|
||||
);
|
||||
return data.addPullRequestReviewComment.comment;
|
||||
}
|
||||
|
||||
export async function updateReviewComment(id: string, body: string): Promise<GHPullRequestReviewComment> {
|
||||
const data = await graphql<{
|
||||
updatePullRequestReviewComment: { pullRequestReviewComment: GHPullRequestReviewComment };
|
||||
}>(Q.updateReviewComment, { id, body });
|
||||
return data.updatePullRequestReviewComment.pullRequestReviewComment;
|
||||
}
|
||||
|
||||
/** Deletes a review comment; returns its (pending) review, when it still exists. */
|
||||
export async function deleteReviewComment(id: string): Promise<GHPullRequestPendingReview | null> {
|
||||
const data = await graphql<{ deletePullRequestReviewComment: { pullRequestReview: PendingReviewNode | null } }>(
|
||||
Q.deleteReviewComment,
|
||||
{ id },
|
||||
);
|
||||
const r = data.deletePullRequestReviewComment.pullRequestReview;
|
||||
return r ? pendingReview(r) : null;
|
||||
}
|
||||
|
||||
export async function addReviewThread(input: {
|
||||
pullRequestReviewId: string;
|
||||
body: string;
|
||||
path: string;
|
||||
line: number;
|
||||
side: GHDiffSide;
|
||||
startLine?: number | null;
|
||||
startSide?: GHDiffSide | null;
|
||||
}): Promise<GHPullRequestReviewThread> {
|
||||
const data = await graphql<{ addPullRequestReviewThread: { thread: GHPullRequestReviewThread } }>(
|
||||
Q.addPullRequestReviewThread,
|
||||
input,
|
||||
);
|
||||
return data.addPullRequestReviewThread.thread;
|
||||
}
|
||||
|
||||
export async function resolveReviewThread(threadId: string): Promise<GHPullRequestReviewThread> {
|
||||
const data = await graphql<{ resolveReviewThread: { thread: GHPullRequestReviewThread } }>(Q.resolveReviewThread, {
|
||||
threadId,
|
||||
});
|
||||
return data.resolveReviewThread.thread;
|
||||
}
|
||||
|
||||
export async function unresolveReviewThread(threadId: string): Promise<GHPullRequestReviewThread> {
|
||||
const data = await graphql<{ unresolveReviewThread: { thread: GHPullRequestReviewThread } }>(
|
||||
Q.unresolveReviewThread,
|
||||
{ threadId },
|
||||
);
|
||||
return data.unresolveReviewThread.thread;
|
||||
}
|
||||
|
||||
export async function updateIssueComment(id: string, body: string): Promise<GHComment> {
|
||||
const data = await graphql<{ updateIssueComment: { issueComment: GHComment } }>(Q.updateIssueComment, { id, body });
|
||||
return data.updateIssueComment.issueComment;
|
||||
}
|
||||
|
||||
export async function deleteIssueComment(id: string): Promise<void> {
|
||||
await graphql(Q.deleteIssueComment, { id });
|
||||
}
|
||||
|
||||
export async function addReaction(id: string, reaction: GHReactionContent): Promise<GHReaction> {
|
||||
const data = await graphql<{ addReaction: { reaction: GHReaction } }>(Q.addReaction, { id, reaction });
|
||||
return data.addReaction.reaction;
|
||||
}
|
||||
|
||||
export async function removeReaction(id: string, reaction: GHReactionContent): Promise<GHReaction> {
|
||||
const data = await graphql<{ removeReaction: { reaction: GHReaction } }>(Q.removeReaction, { id, reaction });
|
||||
return data.removeReaction.reaction;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pull request mutations (REST)
|
||||
|
||||
/** Adds (`POST`) or removes (`DELETE`) requested reviewers: user logins and team slugs. */
|
||||
export async function changeRequestedReviewers(
|
||||
number: number,
|
||||
method: "POST" | "DELETE",
|
||||
reviewers: { logins: string[]; teamSlugs: string[] },
|
||||
): Promise<void> {
|
||||
await rest(method, `${repoPath()}/pulls/${number}/requested_reviewers`, {
|
||||
reviewers: reviewers.logins,
|
||||
team_reviewers: reviewers.teamSlugs,
|
||||
});
|
||||
}
|
||||
|
||||
/** Closes or reopens (`PullRequests.update(state)`). */
|
||||
export async function updatePullRequestState(number: number, state: "open" | "closed"): Promise<void> {
|
||||
await rest("PATCH", `${repoPath()}/pulls/${number}`, { state });
|
||||
}
|
||||
|
||||
/** `PUT pulls/{n}/merge` at head `sha` (rebase takes no message). */
|
||||
export async function mergePullRequest(
|
||||
number: number,
|
||||
method: "merge" | "squash" | "rebase",
|
||||
sha: string,
|
||||
message?: { title: string; body: string },
|
||||
): Promise<void> {
|
||||
await rest("PUT", `${repoPath()}/pulls/${number}/merge`, {
|
||||
merge_method: method,
|
||||
sha,
|
||||
...(message ? { commit_title: message.title, commit_message: message.body } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
/** Adds a conversation comment (`Issues.Comments.create`). */
|
||||
export async function createIssueComment(number: number, body: string): Promise<void> {
|
||||
await rest("POST", `${repoPath()}/issues/${number}/comments`, { body });
|
||||
}
|
||||
|
||||
/** Replaces the assignees (`Issues.updateAssignees`). */
|
||||
export async function updateAssignees(number: number, logins: string[]): Promise<void> {
|
||||
await rest("PATCH", `${repoPath()}/issues/${number}`, { assignees: logins });
|
||||
}
|
||||
|
||||
/** Replaces the labels (`Issues.Labels.replace`). */
|
||||
export async function replaceLabels(number: number, names: string[]): Promise<void> {
|
||||
await rest("PUT", `${repoPath()}/issues/${number}/labels`, { labels: names });
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
/**
|
||||
* Shapes of the GitHub data the documents in `queries.ts` return, named after IntelliJ's
|
||||
* DTOs (`GHPullRequestShort`, `GHPullRequest`, …). GraphQL connections keep their
|
||||
* `nodes`; `data/model.ts` derives what the UI shows (reviewer states, unread, counters).
|
||||
* REST results are mapped to the same shapes (`GHUser`, `GHLabel`) where IntelliJ does.
|
||||
*/
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Common
|
||||
|
||||
/** `pageInfo` fragment. */
|
||||
export interface GHPageInfo {
|
||||
startCursor: string | null;
|
||||
hasPreviousPage: boolean;
|
||||
endCursor: string | null;
|
||||
hasNextPage: boolean;
|
||||
}
|
||||
|
||||
export interface GHConnection<T> {
|
||||
pageInfo: GHPageInfo;
|
||||
nodes: T[];
|
||||
}
|
||||
|
||||
export interface GHNodes<T> {
|
||||
nodes: T[];
|
||||
}
|
||||
|
||||
/** `actorInfo`: what every actor has. `name` comes with users, organizations and enterprise accounts. */
|
||||
export interface GHActor {
|
||||
__typename: "User" | "Bot" | "Organization" | "EnterpriseUserAccount" | "Mannequin" | (string & {});
|
||||
id: string;
|
||||
login: string;
|
||||
url: string;
|
||||
avatarUrl: string;
|
||||
name?: string | null;
|
||||
}
|
||||
|
||||
/** `user` fragment. */
|
||||
export interface GHUser extends GHActor {
|
||||
__typename: "User";
|
||||
name: string | null;
|
||||
}
|
||||
|
||||
/** `teamInfo` fragment (aliased `teamAvatarUrl`, `teamName`). */
|
||||
export interface GHTeam {
|
||||
__typename: "Team";
|
||||
id: string;
|
||||
slug: string;
|
||||
url: string;
|
||||
teamAvatarUrl: string | null;
|
||||
teamName: string;
|
||||
/** `org/slug`. */
|
||||
combinedSlug: string;
|
||||
}
|
||||
|
||||
/** `pullRequestReviewer`: a user, a team or (GitHub Apps) another actor. */
|
||||
export type GHPullRequestRequestedReviewer = GHUser | GHTeam | GHActor;
|
||||
|
||||
/** `labelInfo` fragment. `color` is hex without `#`. */
|
||||
export interface GHLabel {
|
||||
id: string;
|
||||
url: string;
|
||||
name: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
export type GHReactionContent =
|
||||
| "THUMBS_UP"
|
||||
| "THUMBS_DOWN"
|
||||
| "LAUGH"
|
||||
| "HOORAY"
|
||||
| "CONFUSED"
|
||||
| "HEART"
|
||||
| "ROCKET"
|
||||
| "EYES";
|
||||
|
||||
export interface GHReaction {
|
||||
content: GHReactionContent;
|
||||
user: GHUser | null;
|
||||
}
|
||||
|
||||
/** `reactions` fragment (first 25). */
|
||||
export interface GHReactable {
|
||||
reactions: GHConnection<GHReaction>;
|
||||
}
|
||||
|
||||
/** `gitActorInfo`: commit author / committer. */
|
||||
export interface GHGitActor {
|
||||
name: string | null;
|
||||
email: string | null;
|
||||
avatarUrl: string;
|
||||
date: string | null;
|
||||
user: GHUser | null;
|
||||
}
|
||||
|
||||
/** `commitHash` fragment. */
|
||||
export interface GHCommitHash {
|
||||
id: string;
|
||||
oid: string;
|
||||
abbreviatedOid: string;
|
||||
}
|
||||
|
||||
/** `commitShort` fragment. */
|
||||
export interface GHCommitShort extends GHCommitHash {
|
||||
url: string;
|
||||
messageHeadline: string;
|
||||
author: GHGitActor | null;
|
||||
}
|
||||
|
||||
/** `commit` fragment. */
|
||||
export interface GHCommit extends GHCommitShort {
|
||||
committer: GHGitActor | null;
|
||||
messageBody: string;
|
||||
committedDate: string;
|
||||
parents: GHNodes<GHCommitHash>;
|
||||
}
|
||||
|
||||
/** `pullRequestCommits` node. */
|
||||
export interface GHPullRequestCommit {
|
||||
id: string;
|
||||
commit: GHCommit;
|
||||
url: string;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Repository
|
||||
|
||||
export type GHRepositoryPermissionLevel = "READ" | "TRIAGE" | "WRITE" | "MAINTAIN" | "ADMIN";
|
||||
|
||||
/** `repository` fragment. */
|
||||
export interface GHRepository {
|
||||
id: string;
|
||||
owner: { __typename: "User" | "Organization" | (string & {}); id: string; login: string };
|
||||
nameWithOwner: string;
|
||||
viewerPermission: GHRepositoryPermissionLevel | null;
|
||||
mergeCommitAllowed: boolean;
|
||||
squashMergeAllowed: boolean;
|
||||
rebaseMergeAllowed: boolean;
|
||||
defaultBranchRef: { name: string } | null;
|
||||
isFork: boolean;
|
||||
url: string;
|
||||
sshUrl: string;
|
||||
}
|
||||
|
||||
/** Where a request goes: `owner/name` on github.com. */
|
||||
export interface GHRepositoryCoordinates {
|
||||
owner: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/** REST collaborator (`repos/{o}/{r}/collaborators`) mapped to a user, with its permissions. */
|
||||
export interface GHCollaborator extends GHUser {
|
||||
permissions: { admin: boolean; maintain: boolean; push: boolean; triage: boolean; pull: boolean };
|
||||
}
|
||||
|
||||
/** `pullRequestTemplate` fragment. */
|
||||
export interface GHRepositoryPullRequestTemplate {
|
||||
body: string | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pull requests
|
||||
|
||||
export type GHPullRequestState = "OPEN" | "CLOSED" | "MERGED";
|
||||
export type GHPullRequestMergeableState = "MERGEABLE" | "CONFLICTING" | "UNKNOWN";
|
||||
export type GHPullRequestReviewDecision = "APPROVED" | "CHANGES_REQUESTED" | "REVIEW_REQUIRED";
|
||||
export type GHPullRequestReviewState = "PENDING" | "COMMENTED" | "APPROVED" | "CHANGES_REQUESTED" | "DISMISSED";
|
||||
export type GHPullRequestReviewEvent = "COMMENT" | "APPROVE" | "REQUEST_CHANGES" | "DISMISS";
|
||||
export type GHPullRequestMergeStateStatus =
|
||||
| "BEHIND"
|
||||
| "BLOCKED"
|
||||
| "CLEAN"
|
||||
| "DIRTY"
|
||||
| "DRAFT"
|
||||
| "HAS_HOOKS"
|
||||
| "UNKNOWN"
|
||||
| "UNSTABLE";
|
||||
|
||||
/** `pullRequestReview` fragment. */
|
||||
export interface GHPullRequestReview {
|
||||
__typename: "PullRequestReview";
|
||||
id: string;
|
||||
url: string;
|
||||
author: GHActor | null;
|
||||
body: string;
|
||||
state: GHPullRequestReviewState;
|
||||
createdAt: string;
|
||||
viewerCanUpdate: boolean;
|
||||
}
|
||||
|
||||
/** `pullRequestInfoShort` fragment: a list row (`issueSearch`). */
|
||||
export interface GHPullRequestShort extends GHReactable {
|
||||
id: string;
|
||||
url: string;
|
||||
number: number;
|
||||
title: string;
|
||||
state: GHPullRequestState;
|
||||
isDraft: boolean;
|
||||
author: GHActor | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
isReadByViewer: boolean;
|
||||
assignees: GHNodes<GHUser>;
|
||||
labels: GHNodes<GHLabel>;
|
||||
reviewRequests: GHNodes<{ requestedReviewer: GHPullRequestRequestedReviewer | null }>;
|
||||
reviewThreads: GHNodes<{ isResolved: boolean; isOutdated: boolean }>;
|
||||
reviews: GHNodes<GHPullRequestReview>;
|
||||
mergeable: GHPullRequestMergeableState;
|
||||
viewerCanUpdate: boolean;
|
||||
viewerCanReact: boolean;
|
||||
viewerDidAuthor: boolean;
|
||||
}
|
||||
|
||||
/** `pullRequestInfo` fragment: the details (`findPullRequest`). */
|
||||
export interface GHPullRequest extends GHPullRequestShort {
|
||||
body: string;
|
||||
reviewDecision: GHPullRequestReviewDecision | null;
|
||||
baseRefName: string;
|
||||
baseRefOid: string;
|
||||
baseRepository: GHRepository | null;
|
||||
/** Null once the head branch is deleted. */
|
||||
headRef: { id: string } | null;
|
||||
headRefName: string;
|
||||
headRefOid: string;
|
||||
headRepository: GHRepository | null;
|
||||
viewerCanDeleteHeadRef: boolean;
|
||||
}
|
||||
|
||||
/** `pullRequestBranchMatch` fragment. */
|
||||
export interface GHPullRequestBranchMatch {
|
||||
id: string;
|
||||
number: number;
|
||||
title: string;
|
||||
headRefName: string;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mergeability (`findPullRequestMergeability`)
|
||||
|
||||
/** `refUpdateRule` fragment. */
|
||||
export interface GHRefUpdateRule {
|
||||
allowsDeletions: boolean;
|
||||
allowsForcePushes: boolean;
|
||||
pattern: string;
|
||||
requiredApprovingReviewCount: number | null;
|
||||
requiredStatusCheckContexts: Array<string | null>;
|
||||
requiresLinearHistory: boolean;
|
||||
requiresSignatures: boolean;
|
||||
viewerCanPush: boolean;
|
||||
}
|
||||
|
||||
export type GHCommitStatusContextState = "ERROR" | "EXPECTED" | "FAILURE" | "PENDING" | "SUCCESS";
|
||||
export type GHCommitCheckSuiteConclusion =
|
||||
| "ACTION_REQUIRED"
|
||||
| "CANCELLED"
|
||||
| "FAILURE"
|
||||
| "NEUTRAL"
|
||||
| "SKIPPED"
|
||||
| "STALE"
|
||||
| "STARTUP_FAILURE"
|
||||
| "SUCCESS"
|
||||
| "TIMED_OUT";
|
||||
|
||||
/** `commitStatusContext` fragment. */
|
||||
export interface GHCommitStatusContext {
|
||||
context: string;
|
||||
state: GHCommitStatusContextState;
|
||||
isRequired: boolean;
|
||||
targetUrl: string | null;
|
||||
}
|
||||
|
||||
/** `checkRun` fragment. */
|
||||
export interface GHCheckRun {
|
||||
name: string;
|
||||
conclusion: GHCommitCheckSuiteConclusion | null;
|
||||
isRequired: boolean;
|
||||
detailsUrl: string | null;
|
||||
url: string;
|
||||
}
|
||||
|
||||
/** `commitWithCheckStatuses` fragment. */
|
||||
export interface GHCommitWithCheckStatuses extends GHCommitHash {
|
||||
status: { contexts: GHCommitStatusContext[] } | null;
|
||||
checkSuites: GHConnection<{ checkRuns: GHConnection<GHCheckRun> | null }> | null;
|
||||
}
|
||||
|
||||
/** `pullRequestMergeability` fragment. */
|
||||
export interface GHPullRequestMergeabilityData {
|
||||
mergeable: GHPullRequestMergeableState;
|
||||
canBeRebased: boolean;
|
||||
mergeStateStatus: GHPullRequestMergeStateStatus;
|
||||
baseRef: { refUpdateRule: GHRefUpdateRule | null } | null;
|
||||
commits: GHConnection<{ id: string; commit: GHCommitWithCheckStatuses }>;
|
||||
}
|
||||
|
||||
/** `statusCheckRollup` (`getRepositoryCommitStatusContexts`). */
|
||||
export type GHCommitStatusRollupContext =
|
||||
| {
|
||||
__typename: "CheckRun";
|
||||
checkSuite: { workflowRun: { workflow: { name: string } } | null } | null;
|
||||
name: string;
|
||||
title: string | null;
|
||||
status: string;
|
||||
conclusion: GHCommitCheckSuiteConclusion | null;
|
||||
url: string;
|
||||
}
|
||||
| {
|
||||
__typename: "StatusContext";
|
||||
context: string;
|
||||
description: string | null;
|
||||
state: GHCommitStatusContextState;
|
||||
targetUrl: string | null;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Files, reviews, threads
|
||||
|
||||
export type GHPullRequestFileViewedState = "VIEWED" | "UNVIEWED" | "DISMISSED";
|
||||
|
||||
/** `pullRequestFiles` node. */
|
||||
export interface GHPullRequestChangedFile {
|
||||
path: string;
|
||||
viewerViewedState: GHPullRequestFileViewedState;
|
||||
}
|
||||
|
||||
/** REST `pulls/{n}/files` / `commits/{sha}` entry (IntelliJ's `GHCommitFile`), camel-cased. */
|
||||
export interface GHCommitFile {
|
||||
sha: string | null;
|
||||
filename: string;
|
||||
status: "added" | "removed" | "modified" | "renamed" | "copied" | "changed" | "unchanged";
|
||||
additions: number;
|
||||
deletions: number;
|
||||
changes: number;
|
||||
/** Absent for binary and very large files. */
|
||||
patch: string | null;
|
||||
previousFilename: string | null;
|
||||
}
|
||||
|
||||
/** `pullRequestPendingReview` fragment, flattened like IntelliJ's `GHPullRequestPendingReview`. */
|
||||
export interface GHPullRequestPendingReview {
|
||||
id: string;
|
||||
state: GHPullRequestReviewState;
|
||||
commentsCount: number;
|
||||
}
|
||||
|
||||
/** `comment` fragment. */
|
||||
export interface GHComment extends GHReactable {
|
||||
id: string;
|
||||
author: GHActor | null;
|
||||
body: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export type GHPullRequestReviewCommentState = "PENDING" | "SUBMITTED";
|
||||
|
||||
/** `pullRequestReviewComment` fragment. */
|
||||
export interface GHPullRequestReviewComment extends GHComment {
|
||||
url: string;
|
||||
state: GHPullRequestReviewCommentState;
|
||||
commit: GHCommitHash | null;
|
||||
originalCommit: GHCommitHash | null;
|
||||
diffHunk: string;
|
||||
pullRequestReview: { id: string } | null;
|
||||
viewerCanDelete: boolean;
|
||||
viewerCanUpdate: boolean;
|
||||
viewerCanReact: boolean;
|
||||
}
|
||||
|
||||
export type GHDiffSide = "LEFT" | "RIGHT";
|
||||
|
||||
/** `pullRequestReviewThread` fragment. Lines are 1-based; `line` is null when outdated. */
|
||||
export interface GHPullRequestReviewThread {
|
||||
id: string;
|
||||
isResolved: boolean;
|
||||
isOutdated: boolean;
|
||||
path: string;
|
||||
subjectType: "LINE" | "FILE";
|
||||
diffSide: GHDiffSide;
|
||||
line: number | null;
|
||||
originalLine: number | null;
|
||||
startDiffSide: GHDiffSide | null;
|
||||
startLine: number | null;
|
||||
originalStartLine: number | null;
|
||||
comments: GHNodes<GHPullRequestReviewComment>;
|
||||
viewerCanReply: boolean;
|
||||
viewerCanResolve: boolean;
|
||||
viewerCanUnresolve: boolean;
|
||||
}
|
||||
|
||||
/** `DraftPullRequestReviewThread` input of `createReview`. */
|
||||
export interface GHPullRequestDraftReviewThread {
|
||||
body: string;
|
||||
path: string;
|
||||
line: number;
|
||||
side: GHDiffSide;
|
||||
startLine?: number | null;
|
||||
startSide?: GHDiffSide | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Timeline (`pullRequestTimeline`)
|
||||
|
||||
interface GHTimelineEvent {
|
||||
actor: GHActor | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
/** `issueCommentInfo`. */
|
||||
export interface GHIssueComment extends GHComment {
|
||||
__typename: "IssueComment";
|
||||
viewerCanUpdate: boolean;
|
||||
viewerCanDelete: boolean;
|
||||
viewerCanReact: boolean;
|
||||
}
|
||||
|
||||
/** `referenceSubject`. */
|
||||
export type GHReferencedSubject =
|
||||
| {
|
||||
__typename: "PullRequest";
|
||||
title: string;
|
||||
number: number;
|
||||
prState: GHPullRequestState;
|
||||
isDraft: boolean;
|
||||
url: string;
|
||||
}
|
||||
| { __typename: "Issue"; title: string; number: number; issueState: "OPEN" | "CLOSED"; url: string };
|
||||
|
||||
export type GHPRTimelineItem =
|
||||
| { __typename: "PullRequestCommit"; id: string; commit: GHCommitShort; url: string }
|
||||
| GHPullRequestReview
|
||||
| GHIssueComment
|
||||
| ({ __typename: "RenamedTitleEvent"; previousTitle: string; currentTitle: string } & GHTimelineEvent)
|
||||
| ({ __typename: "ClosedEvent" } & GHTimelineEvent)
|
||||
| ({ __typename: "ReopenedEvent" } & GHTimelineEvent)
|
||||
| ({ __typename: "MergedEvent"; mergedEventCommit: GHCommitShort | null; mergeRefName: string } & GHTimelineEvent)
|
||||
| ({ __typename: "AssignedEvent"; user: GHUser | null } & GHTimelineEvent)
|
||||
| ({ __typename: "UnassignedEvent"; user: GHUser | null } & GHTimelineEvent)
|
||||
| ({ __typename: "LabeledEvent"; label: GHLabel } & GHTimelineEvent)
|
||||
| ({ __typename: "UnlabeledEvent"; label: GHLabel } & GHTimelineEvent)
|
||||
| ({ __typename: "ReviewRequestedEvent"; requestedReviewer: GHPullRequestRequestedReviewer | null } & GHTimelineEvent)
|
||||
| ({
|
||||
__typename: "ReviewRequestRemovedEvent";
|
||||
requestedReviewer: GHPullRequestRequestedReviewer | null;
|
||||
} & GHTimelineEvent)
|
||||
| ({
|
||||
__typename: "ReviewDismissedEvent";
|
||||
dismissalMessageHTML: string | null;
|
||||
review: { author: GHActor | null } | null;
|
||||
} & GHTimelineEvent)
|
||||
| ({ __typename: "ReadyForReviewEvent" } & GHTimelineEvent)
|
||||
| ({ __typename: "ConvertToDraftEvent" } & GHTimelineEvent)
|
||||
| ({ __typename: "BaseRefChangedEvent" } & GHTimelineEvent)
|
||||
| ({ __typename: "BaseRefForcePushedEvent"; ref: { name: string } | null } & GHTimelineEvent)
|
||||
| ({
|
||||
__typename: "HeadRefForcePushedEvent";
|
||||
ref: { name: string } | null;
|
||||
beforeCommit: GHCommitHash | null;
|
||||
afterCommit: GHCommitHash | null;
|
||||
} & GHTimelineEvent)
|
||||
| ({ __typename: "HeadRefDeletedEvent"; headRefName: string } & GHTimelineEvent)
|
||||
| ({ __typename: "HeadRefRestoredEvent" } & GHTimelineEvent)
|
||||
| ({ __typename: "CrossReferencedEvent"; source: GHReferencedSubject } & GHTimelineEvent)
|
||||
| ({ __typename: "ConnectedEvent"; subject: GHReferencedSubject } & GHTimelineEvent)
|
||||
| ({ __typename: "DisconnectedEvent"; subject: GHReferencedSubject } & GHTimelineEvent)
|
||||
/** Types the document does not select fields for (ReferencedEvent, MentionedEvent…). */
|
||||
| { __typename: "Unknown"; type: string };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Derived state (`data/model.ts`)
|
||||
|
||||
/** IntelliJ's `GHPRReviewerState`. */
|
||||
export type GHPRReviewerState = "APPROVED" | "CHANGES_REQUESTED" | "COMMENTED" | "NEEDS_REVIEW" | "RE_REQUESTED";
|
||||
|
||||
export type CodeReviewCIJobState = "FAILED" | "PENDING" | "SKIPPED" | "SUCCESS";
|
||||
|
||||
/** IntelliJ's `CodeReviewCIJob`. */
|
||||
export interface CodeReviewCIJob {
|
||||
name: string;
|
||||
status: CodeReviewCIJobState;
|
||||
isRequired: boolean;
|
||||
detailsUrl: string | null;
|
||||
}
|
||||
|
||||
/** IntelliJ's `GHPRMergeabilityState`, plus the raw GitHub values it was built from. */
|
||||
export interface GHPRMergeabilityState {
|
||||
/** Null while GitHub is still checking (mergeable UNKNOWN). */
|
||||
hasConflicts: boolean | null;
|
||||
ciJobs: CodeReviewCIJob[];
|
||||
canBeMerged: boolean;
|
||||
canBeRebased: boolean;
|
||||
/** The viewer may not push to the base branch. */
|
||||
isRestricted: boolean;
|
||||
/** Approvals still required by branch protection (0 when nothing blocks on reviews). */
|
||||
requiredApprovingReviewsCount: number;
|
||||
/** `BLOCKING_BEHIND` / `BLOCKING_FAILING` when the merge box blocks on them, else null. */
|
||||
checksState: "BLOCKING_BEHIND" | "BLOCKING_FAILING" | null;
|
||||
mergeable: GHPullRequestMergeableState;
|
||||
mergeStateStatus: GHPullRequestMergeStateStatus;
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
/**
|
||||
* The commits and changes of the new pull request (`GHPRCreateComponentFactory.changesPanel`):
|
||||
* "Changes" / "Changes from" with the commit chooser ("{n} commits", "All commits (n)"),
|
||||
* the selected commit's details (Show / Hide details) and the changes tree, whose
|
||||
* Show Diff opens the files in the diff viewer as one chain.
|
||||
*/
|
||||
import { useMemo, useRef, useState, type MouseEvent, type ReactNode } from "react";
|
||||
import { buildFileTree, dirKeys, type FileTreeNode } from "@/features/vcs/fileTree";
|
||||
import { openDiff, withChain } from "@/features/vcs/diffInput";
|
||||
import { KIND_COLOR, baseName, fileCount, type EffectiveKind } from "@/features/vcs/model";
|
||||
import type { Commit } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { Icon, IconButton, Spinner, T, Tree, fileIconName, showContextMenu, type MenuItem } from "@/ui";
|
||||
import { ChooserPopup } from "../ui/ChooserPopup";
|
||||
import { prettyDate } from "../ui/prettyDate";
|
||||
import { commitDescription } from "./model";
|
||||
import { selectCommit, useCreatePr, type CreateChange } from "./store";
|
||||
import styles from "./Create.module.css";
|
||||
|
||||
function Centered({ children, error }: { children: ReactNode; error?: boolean }) {
|
||||
return <div className={error ? `${styles.centered} ${styles.errorText}` : styles.centered}>{children}</div>;
|
||||
}
|
||||
|
||||
export function ChangesPanel() {
|
||||
const commits = useCreatePr((s) => s.commits);
|
||||
if (!commits)
|
||||
return (
|
||||
<Centered>
|
||||
<T>Select pull request base and head to view changes</T>
|
||||
</Centered>
|
||||
);
|
||||
if (commits.state === "loading")
|
||||
return (
|
||||
<Centered>
|
||||
<Spinner size={14} />
|
||||
</Centered>
|
||||
);
|
||||
if (commits.state === "error")
|
||||
return (
|
||||
<Centered error>
|
||||
<div>
|
||||
<T>Failed to load commits</T>
|
||||
</div>
|
||||
<div className={styles.errorDetail}>{commits.error}</div>
|
||||
</Centered>
|
||||
);
|
||||
if (!commits.value.length)
|
||||
return (
|
||||
<Centered>
|
||||
<span className={styles.hint}>
|
||||
<T>Pull request does not contain any commits</T>
|
||||
</span>
|
||||
</Centered>
|
||||
);
|
||||
return <CommitsAndChanges commits={commits.value} />;
|
||||
}
|
||||
|
||||
function CommitsAndChanges({ commits }: { commits: Commit[] }) {
|
||||
const selectedId = useCreatePr((s) => s.selectedCommit);
|
||||
const index = commits.findIndex((c) => c.id === selectedId);
|
||||
const selected = index >= 0 ? commits[index]! : null;
|
||||
return (
|
||||
<div className={styles.changes}>
|
||||
<div className={styles.commits}>
|
||||
<div className={styles.commitsHeader}>
|
||||
<span className={styles.commitsTitle}>{commits.length === 1 ? tx("Changes") : tx("Changes from")}</span>
|
||||
<CommitChooser commits={commits} selected={selected} />
|
||||
{commits.length > 1 && selected && (
|
||||
<>
|
||||
<IconButton
|
||||
icon="arrow-down"
|
||||
size="small"
|
||||
title="Next Commit"
|
||||
disabled={index === commits.length - 1}
|
||||
onClick={() => selectCommit(commits[index + 1]!.id)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="arrow-up"
|
||||
size="small"
|
||||
title="Previous Commit"
|
||||
disabled={index === 0}
|
||||
onClick={() => selectCommit(commits[index - 1]!.id)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{selected && <CommitDetails key={selected.id} commit={selected} />}
|
||||
</div>
|
||||
<ChangesTree />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CommitChooser({ commits, selected }: { commits: Commit[]; selected: Commit | null }) {
|
||||
const ref = useRef<HTMLButtonElement>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const items = useMemo<Array<Commit | null>>(() => [null, ...commits], [commits]);
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
ref={ref}
|
||||
type="button"
|
||||
className={styles.link}
|
||||
disabled={commits.length <= 1}
|
||||
onClick={() => setOpen(true)}
|
||||
>
|
||||
<span className={selected ? styles.hash : undefined}>
|
||||
{selected ? selected.shortId : commits.length === 1 ? tx("1 commit") : tx`${commits.length} commits`}
|
||||
</span>
|
||||
{commits.length > 1 && <Icon name="chevron-down" size={12} />}
|
||||
</button>
|
||||
{open && (
|
||||
<ChooserPopup<Commit | null>
|
||||
mode="single"
|
||||
anchor={ref}
|
||||
items={items}
|
||||
getKey={(c) => c?.id ?? "all"}
|
||||
present={(c) =>
|
||||
c
|
||||
? {
|
||||
text: c.summary,
|
||||
detail: `${c.author}, ${c.timeMs ? prettyDate(c.timeMs) : ""}`,
|
||||
icon: selected?.id === c.id ? "check" : "commit",
|
||||
}
|
||||
: { text: tx`All commits (${commits.length})`, icon: selected ? "commit" : "check" }
|
||||
}
|
||||
placeholder="Search commits"
|
||||
aria-label="Commits"
|
||||
width={360}
|
||||
onChoose={(c) => selectCommit(c?.id ?? null)}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** `CodeReviewDetailsCommitInfoComponentFactory`: the subject, and with the details the body, author and date. */
|
||||
function CommitDetails({ commit }: { commit: Commit }) {
|
||||
const [details, setDetails] = useState(false);
|
||||
const description = commitDescription(commit.message);
|
||||
return (
|
||||
<div className={styles.commitInfo}>
|
||||
<div className={styles.commitTop}>
|
||||
<span className={details ? styles.commitSubjectFull : styles.commitSubject}>{commit.summary}</span>
|
||||
<button type="button" className={styles.textLink} onClick={() => setDetails((d) => !d)}>
|
||||
{details ? tx("Hide details") : tx("Show details")}
|
||||
</button>
|
||||
</div>
|
||||
{details && description && <div className={styles.commitBody}>{description}</div>}
|
||||
{details && (
|
||||
<div className={styles.commitMeta}>
|
||||
{commit.author}, {commit.timeMs ? prettyDate(commit.timeMs) : ""}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const kindOf = (c: CreateChange): EffectiveKind => (c.kind === "untracked" ? "added" : c.kind);
|
||||
|
||||
/** Show Diff: `first` with every file of the tree in the chain (F7 moves along). */
|
||||
function showDiff(all: readonly CreateChange[], first: CreateChange) {
|
||||
void openDiff(
|
||||
withChain(
|
||||
all.map((c) => c.diff),
|
||||
Math.max(0, all.indexOf(first)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function ChangesTree() {
|
||||
const changes = useCreatePr((s) => s.changes);
|
||||
const files = changes?.state === "ok" ? changes.value : null;
|
||||
const roots = useMemo(() => (files ? buildFileTree(files, (f) => f.path) : []), [files]);
|
||||
const expanded = useMemo(() => dirKeys(roots), [roots]);
|
||||
const ordered = useMemo(() => {
|
||||
const out: CreateChange[] = [];
|
||||
const walk = (ns: readonly FileTreeNode<CreateChange>[]) =>
|
||||
ns.forEach((n) => (n.file ? out.push(n.file) : walk(n.children)));
|
||||
walk(roots);
|
||||
return out;
|
||||
}, [roots]);
|
||||
const [selection, setSelection] = useState<ReadonlySet<string>>(new Set());
|
||||
if (!changes || changes.state === "loading")
|
||||
return (
|
||||
<Centered>
|
||||
<Spinner size={14} />
|
||||
</Centered>
|
||||
);
|
||||
if (changes.state === "error")
|
||||
return (
|
||||
<Centered error>
|
||||
<div>
|
||||
<T>Failed to load changes</T>
|
||||
</div>
|
||||
<div className={styles.errorDetail}>{changes.error}</div>
|
||||
</Centered>
|
||||
);
|
||||
const selectedFiles = (keys: ReadonlySet<string>) => ordered.filter((f) => keys.has(`f:${f.path}`));
|
||||
const menu = (node: FileTreeNode<CreateChange> | null, keys: Set<string>, e: MouseEvent) => {
|
||||
const picked = selectedFiles(keys);
|
||||
const first = picked[0] ?? node?.file ?? null;
|
||||
const items: MenuItem[] = [
|
||||
{ label: "Show Diff", icon: "diff", disabled: !first, run: () => first && showDiff(ordered, first) },
|
||||
];
|
||||
showContextMenu(e, items);
|
||||
};
|
||||
return (
|
||||
<Tree<FileTreeNode<CreateChange>>
|
||||
key={changes.value.length ? "files" : "empty"}
|
||||
className={styles.tree}
|
||||
roots={roots}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={(n) => n.name}
|
||||
getChildren={(n) => n.children}
|
||||
isExpandable={(n) => !n.file}
|
||||
defaultExpanded={expanded}
|
||||
selected={selection}
|
||||
onSelectionChange={setSelection}
|
||||
multiSelect
|
||||
rowHeight={22}
|
||||
aria-label="Changes"
|
||||
speedSearch
|
||||
onActivate={(n) => n.file && showDiff(ordered, n.file)}
|
||||
onContextMenu={menu}
|
||||
empty={
|
||||
<Centered>
|
||||
<span className={styles.hint}>
|
||||
<T>Commit does not contain any changes</T>
|
||||
</span>
|
||||
</Centered>
|
||||
}
|
||||
renderNode={(n) => <ChangeRow node={n} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ChangeRow({ node }: { node: FileTreeNode<CreateChange> }) {
|
||||
if (!node.file)
|
||||
return (
|
||||
<span className={styles.fileRow}>
|
||||
<Icon name="folder" size={16} />
|
||||
<span className={styles.fileName}>{node.name}</span>
|
||||
<span className={styles.fileDetail}>{fileCount(node.count)}</span>
|
||||
</span>
|
||||
);
|
||||
const f = node.file;
|
||||
return (
|
||||
<span className={styles.fileRow} title={f.oldPath ? `${f.oldPath} → ${f.path}` : f.path}>
|
||||
<Icon name={fileIconName(node.name)} size={16} />
|
||||
<span className={styles.fileName} style={{ color: KIND_COLOR[kindOf(f)] }}>
|
||||
{node.name}
|
||||
</span>
|
||||
{f.oldPath && <span className={styles.fileDetail}>{tx`renamed from ${baseName(f.oldPath)}`}</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
/*
|
||||
* The New Pull Request tab. Gaps are IntelliJ's: 12px sides, 8px between the parts,
|
||||
* 10px around the status line and the button.
|
||||
*/
|
||||
.root {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.top,
|
||||
.bottom {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.centered {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
min-height: 0;
|
||||
padding: 12px;
|
||||
text-align: center;
|
||||
}
|
||||
.hint {
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.errorText {
|
||||
color: var(--danger);
|
||||
}
|
||||
.errorDetail {
|
||||
max-width: 100%;
|
||||
color: var(--fg-secondary);
|
||||
overflow-wrap: anywhere;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
/* Link-style buttons: the direction dropdowns, the commit chooser, Show details, View. */
|
||||
.link,
|
||||
.textLink {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--link);
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.link:hover:not(:disabled) .linkText,
|
||||
.textLink:hover {
|
||||
color: var(--link-hover, var(--link));
|
||||
text-decoration: underline;
|
||||
}
|
||||
.link:disabled {
|
||||
color: var(--fg);
|
||||
cursor: default;
|
||||
}
|
||||
.linkText {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Direction */
|
||||
.direction {
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
padding: 8px 12px;
|
||||
}
|
||||
/* Base and head share the width; each shows its whole text when it fits. */
|
||||
.direction > .link {
|
||||
flex: 0 1 auto;
|
||||
max-width: calc(50% - 12px);
|
||||
}
|
||||
.arrow {
|
||||
flex: none;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.headPopup {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 300px;
|
||||
height: 340px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.headRepo {
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 8px 8px 0;
|
||||
}
|
||||
.headRepo > :last-child {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.headRepoLabel {
|
||||
flex: none;
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
.headSearch {
|
||||
flex: none;
|
||||
padding: 6px 8px 4px;
|
||||
}
|
||||
.headList {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
padding-bottom: 4px;
|
||||
}
|
||||
.headSection {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
padding: 0 10px;
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.headRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 100%;
|
||||
padding: 0 8px;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.headRow[data-active] {
|
||||
background: var(--bg-list-selected);
|
||||
border-radius: var(--radius-selection);
|
||||
}
|
||||
|
||||
/* Commits and changes */
|
||||
.changesBox {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.changes {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
.commits {
|
||||
display: flex;
|
||||
flex: none;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
max-height: 50%;
|
||||
padding: 2px 12px 8px;
|
||||
overflow: auto;
|
||||
}
|
||||
.commitsHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-height: 28px;
|
||||
}
|
||||
.commitsTitle {
|
||||
font-weight: 600;
|
||||
}
|
||||
.hash {
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
.commitInfo {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.commitTop {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
}
|
||||
.commitTop > .textLink {
|
||||
flex: none;
|
||||
margin-left: auto;
|
||||
}
|
||||
.commitSubject {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.commitSubjectFull {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.commitBody {
|
||||
overflow-wrap: anywhere;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
.commitMeta {
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.tree {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.fileRow {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.fileName {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.fileDetail {
|
||||
margin-left: 4px;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
/* Title and description */
|
||||
.text {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
min-height: 60px;
|
||||
}
|
||||
.titleInput {
|
||||
flex: none;
|
||||
margin: 0;
|
||||
border: none !important;
|
||||
border-bottom: 1px solid var(--border) !important;
|
||||
border-radius: 0 !important;
|
||||
background: var(--bg-editor, var(--bg-input)) !important;
|
||||
padding: 8px 12px !important;
|
||||
height: auto !important;
|
||||
box-shadow: none !important;
|
||||
}
|
||||
.descriptionBox {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
.description {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
padding: 8px 12px;
|
||||
border: none;
|
||||
outline: none;
|
||||
background: var(--bg-editor, var(--bg-input));
|
||||
color: var(--fg);
|
||||
font: inherit;
|
||||
resize: none;
|
||||
}
|
||||
.templateSpinner {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 12px;
|
||||
}
|
||||
|
||||
/* Reviewers, assignees, labels */
|
||||
.metadata {
|
||||
display: grid;
|
||||
flex: none;
|
||||
grid-template-columns: max-content minmax(0, 1fr);
|
||||
align-items: start;
|
||||
padding: 8px 12px;
|
||||
border-top: 1px solid var(--border);
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--bg-editor, var(--bg-input));
|
||||
}
|
||||
.metaLabel {
|
||||
padding: 6px 5px 6px 0;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.metaList {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
min-height: 28px;
|
||||
}
|
||||
.metaItem {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 4px 3px;
|
||||
}
|
||||
.userItem {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
/* Status and the option button */
|
||||
.footer {
|
||||
display: flex;
|
||||
flex: none;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 10px;
|
||||
}
|
||||
.status {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
max-width: 100%;
|
||||
}
|
||||
.statusRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.statusText {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
.ellipsis {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.errorPopup {
|
||||
width: 300px;
|
||||
max-height: 400px;
|
||||
padding: 10px 12px;
|
||||
overflow: auto;
|
||||
resize: both;
|
||||
}
|
||||
.errorPopupTitle {
|
||||
margin-bottom: 6px;
|
||||
color: var(--danger);
|
||||
}
|
||||
.errorPopupText {
|
||||
overflow-wrap: anywhere;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
.optionButton {
|
||||
display: inline-flex;
|
||||
align-items: stretch;
|
||||
}
|
||||
.optionButton > :first-child {
|
||||
border-top-right-radius: 0;
|
||||
border-bottom-right-radius: 0;
|
||||
}
|
||||
.optionArrow {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0 4px;
|
||||
border: none;
|
||||
border-left: 1px solid color-mix(in srgb, var(--fg-button-primary) 35%, transparent);
|
||||
border-radius: 0 var(--radius-control, 4px) var(--radius-control, 4px) 0;
|
||||
background: var(--bg-button-primary);
|
||||
color: var(--fg-button-primary);
|
||||
cursor: pointer;
|
||||
}
|
||||
.optionArrow:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* New Remote Branch for Pull Request */
|
||||
.dialogForm {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.dialogLabel {
|
||||
color: var(--fg);
|
||||
}
|
||||
.dialogComment {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
/**
|
||||
* The "New Pull Request at {repo}" tab (IntelliJ's `GHPRCreateComponentFactory`): a
|
||||
* vertical splitter with the merge direction and the commits and changes above, and the
|
||||
* title and description, reviewers / assignees / labels, the status line and the
|
||||
* "Create Pull Request" option button (with "Create Draft Pull Request") below.
|
||||
*
|
||||
* Contract: `CreatePanel()` takes no props and renders inside the New Pull Request tab
|
||||
* while the tool window is connected. Its state (`store.ts`) lives as long as the tab.
|
||||
*/
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useVcs } from "@/features/vcs/store";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import {
|
||||
Button,
|
||||
Icon,
|
||||
IconButton,
|
||||
Input,
|
||||
Menu,
|
||||
Popup,
|
||||
SplitGroup,
|
||||
SplitHandle,
|
||||
SplitPanel,
|
||||
Spinner,
|
||||
T,
|
||||
type MenuItem,
|
||||
} from "@/ui";
|
||||
import { openPullRequest } from "../toolwindow/open";
|
||||
import { ChangesPanel } from "./ChangesPanel";
|
||||
import { DirectionSelector } from "./DirectionSelector";
|
||||
import { MetadataGrid } from "./MetadataGrid";
|
||||
import {
|
||||
canCreate,
|
||||
createFromForm,
|
||||
initCreate,
|
||||
onRepositoryChanged,
|
||||
refreshBranchesState,
|
||||
resetCreate,
|
||||
setDescription,
|
||||
setTitle,
|
||||
useCreatePr,
|
||||
} from "./store";
|
||||
import styles from "./Create.module.css";
|
||||
|
||||
export function CreatePanel() {
|
||||
const ready = useCreatePr((s) => s.ready);
|
||||
const initError = useCreatePr((s) => s.initError);
|
||||
useEffect(() => {
|
||||
void initCreate();
|
||||
}, []);
|
||||
// Commits follow the repository (a new commit, a push, a fetch).
|
||||
useEffect(
|
||||
() =>
|
||||
useVcs.subscribe((s, prev) => {
|
||||
if (s.version !== prev.version) void onRepositoryChanged();
|
||||
}),
|
||||
[],
|
||||
);
|
||||
if (initError)
|
||||
return (
|
||||
<div className={styles.centered}>
|
||||
<div className={styles.errorText}>{initError}</div>
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() => {
|
||||
resetCreate();
|
||||
void initCreate();
|
||||
}}
|
||||
>
|
||||
<T>Retry</T>
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
if (!ready)
|
||||
return (
|
||||
<div className={styles.centered}>
|
||||
<Spinner size={14} />
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<SplitGroup orientation="vertical" id="github-create-pull-request" className={styles.root}>
|
||||
<SplitPanel id="top" defaultSize="50%" minSize="90px">
|
||||
<div className={styles.top}>
|
||||
<DirectionSelector />
|
||||
<div className={styles.changesBox}>
|
||||
<ChangesPanel />
|
||||
</div>
|
||||
</div>
|
||||
</SplitPanel>
|
||||
<SplitHandle />
|
||||
<SplitPanel id="bottom" defaultSize="50%" minSize="160px">
|
||||
<div className={styles.bottom}>
|
||||
<TextPanel />
|
||||
<MetadataGrid />
|
||||
<div className={styles.footer}>
|
||||
<StatusLine />
|
||||
<CreateButton />
|
||||
</div>
|
||||
</div>
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
);
|
||||
}
|
||||
|
||||
/** `CodeReviewTitleDescriptionComponentFactory`: the title and description editors. */
|
||||
function TextPanel() {
|
||||
const title = useCreatePr((s) => s.title);
|
||||
const description = useCreatePr((s) => s.description);
|
||||
const templateLoading = useCreatePr((s) => s.templateLoading);
|
||||
return (
|
||||
<div className={styles.text}>
|
||||
<Input
|
||||
className={styles.titleInput}
|
||||
aria-label="Title"
|
||||
placeholder="Title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<div className={styles.descriptionBox}>
|
||||
<textarea
|
||||
className={styles.description}
|
||||
aria-label={tx("Description")}
|
||||
placeholder={tx("Description")}
|
||||
value={description}
|
||||
disabled={templateLoading}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
{templateLoading && (
|
||||
<span className={styles.templateSpinner}>
|
||||
<Spinner size={12} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** "Details": the error in a popup above the link. */
|
||||
function ErrorDetails({ title, error }: { title: string; error: string }) {
|
||||
const ref = useRef<HTMLButtonElement>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<button ref={ref} type="button" className={styles.textLink} onClick={() => setOpen(true)}>
|
||||
<T>Details</T>
|
||||
</button>
|
||||
{open && (
|
||||
<Popup
|
||||
open
|
||||
anchor={ref}
|
||||
placement="top-start"
|
||||
offset={4}
|
||||
onClose={() => setOpen(false)}
|
||||
role="dialog"
|
||||
aria-label={title}
|
||||
className={styles.errorPopup}
|
||||
>
|
||||
<div className={styles.errorPopupTitle}>{title}</div>
|
||||
<div className={styles.errorPopupText}>{error}</div>
|
||||
</Popup>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ErrorLabel({ text }: { text: string }) {
|
||||
return (
|
||||
<span className={styles.statusText} title={text}>
|
||||
<Icon name="error" size={16} />
|
||||
<span className={styles.ellipsis}>{text}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function LoadingLabel({ text }: { text: string }) {
|
||||
return (
|
||||
<span className={styles.statusText}>
|
||||
<Spinner size={14} />
|
||||
<span className={styles.ellipsis}>{text}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** The branches check, then the creation progress (`statusPanel`). */
|
||||
function StatusLine() {
|
||||
const check = useCreatePr((s) => s.check);
|
||||
const creation = useCreatePr((s) => s.creation);
|
||||
let checkLine = null;
|
||||
if (check?.state === "loading") checkLine = <LoadingLabel text={tx("Checking pull request branches")} />;
|
||||
else if (check?.state === "error")
|
||||
checkLine = (
|
||||
<>
|
||||
<ErrorLabel text={tx("Failed to check pull request branches")} />
|
||||
<ErrorDetails title={tx("Failed to check pull request branches")} error={check.error} />
|
||||
<IconButton icon="refresh" size="small" title="Refresh" onClick={() => void refreshBranchesState()} />
|
||||
</>
|
||||
);
|
||||
else if (check?.state === "ok" && check.value.kind === "alreadyExists") {
|
||||
const n = check.value.number;
|
||||
checkLine = (
|
||||
<>
|
||||
<ErrorLabel text={tx("Pull request already exists")} />
|
||||
<button type="button" className={styles.textLink} onClick={() => void openPullRequest(n)}>
|
||||
<T>View</T>
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
} else if (check?.state === "ok" && check.value.kind === "noChanges")
|
||||
checkLine = <ErrorLabel text={tx`No changes between '${check.value.base}' and '${check.value.head}'`} />;
|
||||
|
||||
let progressLine = null;
|
||||
if (creation?.kind === "pushing") progressLine = <LoadingLabel text={tx("Pushing a pull request branch")} />;
|
||||
else if (creation?.kind === "creating") progressLine = <LoadingLabel text={tx("Creating a pull request")} />;
|
||||
else if (creation?.kind === "metadata") progressLine = <LoadingLabel text={tx("Updating pull request fields")} />;
|
||||
else if (creation?.kind === "error")
|
||||
progressLine = (
|
||||
<>
|
||||
<ErrorLabel text={tx("Failed to create a pull request")} />
|
||||
<ErrorDetails title={tx("Failed to create a pull request")} error={creation.error} />
|
||||
</>
|
||||
);
|
||||
if (!checkLine && !progressLine) return null;
|
||||
return (
|
||||
<div className={styles.status} role="status">
|
||||
{checkLine && <div className={styles.statusRow}>{checkLine}</div>}
|
||||
{progressLine && <div className={styles.statusRow}>{progressLine}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** `JBOptionButton`: "Create Pull Request" and, behind the arrow, "Create Draft Pull Request". */
|
||||
function CreateButton() {
|
||||
const enabled = useCreatePr(canCreate);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [menu, setMenu] = useState(false);
|
||||
const options: MenuItem[] = [
|
||||
{ label: "Create Draft Pull Request", disabled: !enabled, run: () => void createFromForm(true) },
|
||||
];
|
||||
return (
|
||||
<div ref={ref} className={styles.optionButton}>
|
||||
<Button variant="primary" disabled={!enabled} onClick={() => void createFromForm(false)}>
|
||||
<T>Create Pull Request</T>
|
||||
</Button>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.optionArrow}
|
||||
aria-label={tx("More create options")}
|
||||
aria-haspopup="menu"
|
||||
disabled={!enabled}
|
||||
onClick={() => setMenu(true)}
|
||||
>
|
||||
<Icon name="chevron-down" size={14} />
|
||||
</button>
|
||||
<Menu
|
||||
open={menu}
|
||||
onClose={() => setMenu(false)}
|
||||
anchor={ref}
|
||||
items={options}
|
||||
placement="top-start"
|
||||
aria-label="Create options"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* The merge direction (git4idea's `MergeDirectionComponentFactory`): two link-style
|
||||
* dropdowns, the base and the head, joined by "←". The base lists the branches of the
|
||||
* connected repository's remote; the head lists the local branches and the branches of
|
||||
* the chosen repository (the project's GitHub remotes and forks).
|
||||
*/
|
||||
import { useMemo, useState, type KeyboardEvent } from "react";
|
||||
import { HighlightedText, Icon, List, Popup, SearchField, Select, T, fuzzyMatch, listNavigate } from "@/ui";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { nameWithOwner, sameRepository, useGhRepository, type GHRemote } from "../data/repository";
|
||||
import { ChooserPopup } from "../ui/ChooserPopup";
|
||||
import {
|
||||
baseText,
|
||||
headBranchName,
|
||||
headText,
|
||||
localBranchesOf,
|
||||
remoteBranchesOf,
|
||||
sameHead,
|
||||
type HeadBranch,
|
||||
type RemoteBranchRef,
|
||||
} from "./model";
|
||||
import { setBaseBranch, setHead, useCreatePr } from "./store";
|
||||
import styles from "./Create.module.css";
|
||||
|
||||
function DropDownLink(props: { text: string | null; label: string; onClick: (el: HTMLElement) => void }) {
|
||||
const tx = useTx();
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.link}
|
||||
aria-label={tx(props.label)}
|
||||
title={props.text ?? undefined}
|
||||
onClick={(e) => props.onClick(e.currentTarget)}
|
||||
>
|
||||
<span className={styles.linkText}>{props.text ?? tx("Select…")}</span>
|
||||
<Icon name="chevron-down" size={12} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function DirectionSelector() {
|
||||
const direction = useCreatePr((s) => s.direction);
|
||||
const branches = useCreatePr((s) => s.branches);
|
||||
const [open, setOpen] = useState<{ which: "base" | "head"; anchor: HTMLElement } | null>(null);
|
||||
const baseBranches = useMemo(
|
||||
() => (direction ? remoteBranchesOf(branches, direction.baseRepo.remote) : []),
|
||||
[branches, direction],
|
||||
);
|
||||
if (!direction) return null;
|
||||
return (
|
||||
<div className={styles.direction}>
|
||||
<DropDownLink
|
||||
text={baseText(direction)}
|
||||
label="Base branch"
|
||||
onClick={(anchor) => setOpen({ which: "base", anchor })}
|
||||
/>
|
||||
<span className={styles.arrow} aria-hidden>
|
||||
←
|
||||
</span>
|
||||
<DropDownLink
|
||||
text={headText(direction)}
|
||||
label="Head branch"
|
||||
onClick={(anchor) => setOpen({ which: "head", anchor })}
|
||||
/>
|
||||
{open?.which === "base" && (
|
||||
<ChooserPopup<RemoteBranchRef>
|
||||
mode="single"
|
||||
anchor={open.anchor}
|
||||
items={baseBranches}
|
||||
getKey={(b) => b.name}
|
||||
present={(b) => ({ text: b.name, icon: "branch-label" })}
|
||||
placeholder="Search branches"
|
||||
aria-label="Base branch"
|
||||
onChoose={setBaseBranch}
|
||||
onClose={() => setOpen(null)}
|
||||
/>
|
||||
)}
|
||||
{open?.which === "head" && (
|
||||
<HeadPopup
|
||||
anchor={open.anchor}
|
||||
initialRepo={direction.headRepo ?? direction.baseRepo}
|
||||
onClose={() => setOpen(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type HeadRow = { section: string } | { branch: HeadBranch; text: string; match: number[] | null };
|
||||
|
||||
/** The head: the repository (several GitHub remotes only), then its branches, local first. */
|
||||
function HeadPopup(props: { anchor: HTMLElement; initialRepo: GHRemote; onClose: () => void }) {
|
||||
const tx = useTx();
|
||||
const remotes = useGhRepository((s) => s.remotes);
|
||||
const branches = useCreatePr((s) => s.branches);
|
||||
const current = useCreatePr((s) => s.direction?.headBranch ?? null);
|
||||
const [repo, setRepo] = useState(props.initialRepo);
|
||||
const [filter, setFilter] = useState("");
|
||||
const [active, setActive] = useState(1);
|
||||
const rows = useMemo(() => {
|
||||
const q = filter.trim();
|
||||
const section = (title: string, list: HeadBranch[]): HeadRow[] => {
|
||||
const items = list.flatMap((branch) => {
|
||||
const text = headBranchName(branch);
|
||||
const match = q ? fuzzyMatch(text, q) : null;
|
||||
return q && !match ? [] : [{ branch, text, match }];
|
||||
});
|
||||
return items.length ? [{ section: title }, ...items] : [];
|
||||
};
|
||||
const remote = remoteBranchesOf(branches, repo.remote).map((b): HeadBranch => ({ kind: "remote", ...b }));
|
||||
return [...section(tx("Local"), localBranchesOf(branches)), ...section(tx("Remote"), remote)];
|
||||
}, [branches, repo, filter, tx]);
|
||||
const isSection = (r: HeadRow) => "section" in r;
|
||||
const index = Math.min(Math.max(active, 0), rows.length - 1);
|
||||
const choose = (r: HeadRow | undefined) => {
|
||||
if (!r || "section" in r) return;
|
||||
setHead(repo, r.branch);
|
||||
props.onClose();
|
||||
};
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
const next = listNavigate(e.key, { items: rows, active: index, wrap: true, pageSize: 7, isSection });
|
||||
if (next !== null && e.key !== "Home" && e.key !== "End") {
|
||||
e.preventDefault();
|
||||
setActive(next);
|
||||
} else if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
choose(rows[index]);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Popup
|
||||
open
|
||||
anchor={props.anchor}
|
||||
placement="bottom-start"
|
||||
offset={4}
|
||||
onClose={props.onClose}
|
||||
role="dialog"
|
||||
aria-label={tx("Head branch")}
|
||||
className={styles.headPopup}
|
||||
>
|
||||
{remotes.length > 1 && (
|
||||
<div className={styles.headRepo}>
|
||||
<span className={styles.headRepoLabel}>
|
||||
<T>Repository:</T>
|
||||
</span>
|
||||
<Select
|
||||
value={nameWithOwner(repo)}
|
||||
options={remotes.map((r) => ({ value: nameWithOwner(r), label: `${nameWithOwner(r)} (${r.remote})` }))}
|
||||
onChange={(v) => {
|
||||
const next = remotes.find((r) => nameWithOwner(r) === v);
|
||||
if (next && !sameRepository(next, repo)) setRepo(next);
|
||||
}}
|
||||
aria-label="Head repository"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.headSearch}>
|
||||
<SearchField
|
||||
value={filter}
|
||||
onChange={(v) => {
|
||||
setFilter(v);
|
||||
setActive(1);
|
||||
}}
|
||||
onKeyDown={onKeyDown}
|
||||
placeholder={tx("Search branches")}
|
||||
aria-label="Search branches"
|
||||
data-autofocus
|
||||
/>
|
||||
</div>
|
||||
<List
|
||||
items={rows}
|
||||
getKey={(r) => ("section" in r ? `s:${r.section}` : `${r.branch.kind}:${r.text}`)}
|
||||
isSection={isSection}
|
||||
renderSection={(r) => <div className={styles.headSection}>{"section" in r ? r.section : null}</div>}
|
||||
sectionHeight={22}
|
||||
activeIndex={index}
|
||||
onActiveChange={setActive}
|
||||
onActivate={(r) => choose(r)}
|
||||
focusable={false}
|
||||
hoverSelects
|
||||
rowHeight={24}
|
||||
className={styles.headList}
|
||||
aria-label="Branches"
|
||||
empty={<div className={styles.hint}>{tx("Nothing to show")}</div>}
|
||||
renderItem={(r, state) =>
|
||||
"section" in r ? null : (
|
||||
<div className={styles.headRow} data-active={state.active || undefined}>
|
||||
<Icon name={sameHead(r.branch, current) ? "current-branch-label" : "branch-label"} size={16} />
|
||||
<HighlightedText text={r.text} indices={r.match} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Popup>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* Reviewers, assignees and labels of the new pull request (`LabeledListComponentsFactory`
|
||||
* grid): a grey label ("Reviewers:", or "No reviewers" while empty), the chosen items
|
||||
* with avatars or label colours and an edit button opening a multi-select chooser above.
|
||||
*/
|
||||
import { useState, type ReactNode } from "react";
|
||||
import { IconButton } from "@/ui";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import type { GHLabel, GHPullRequestRequestedReviewer, GHUser } from "../api/types";
|
||||
import { isTeam, reviewerKey } from "../data/model";
|
||||
import { usePotentialReviewers, useGhRepository, useRepositoryList } from "../data/repository";
|
||||
import { Avatar, AVATAR_SIZE } from "../ui/Avatar";
|
||||
import { ChooserPopup, type ChooserItemPresentation } from "../ui/ChooserPopup";
|
||||
import { LabelChip, LabelSwatch } from "../ui/chips";
|
||||
import { selectableReviewers, setAssignees, setLabels, setReviewers, useCreatePr } from "./store";
|
||||
import styles from "./Create.module.css";
|
||||
|
||||
interface ListRowProps<T> {
|
||||
label: string;
|
||||
emptyLabel: string;
|
||||
items: readonly T[];
|
||||
getKey: (item: T) => string;
|
||||
renderItem: (item: T) => ReactNode;
|
||||
chooser: (anchor: HTMLElement, close: () => void) => ReactNode;
|
||||
}
|
||||
|
||||
function ListRow<T>(props: ListRowProps<T>) {
|
||||
const tx = useTx();
|
||||
const [anchor, setAnchor] = useState<HTMLElement | null>(null);
|
||||
const label = props.items.length ? props.label : props.emptyLabel;
|
||||
return (
|
||||
<>
|
||||
<div className={styles.metaLabel}>{tx(label)}</div>
|
||||
<div className={styles.metaList}>
|
||||
{props.items.map((item) => (
|
||||
<span key={props.getKey(item)} className={styles.metaItem}>
|
||||
{props.renderItem(item)}
|
||||
</span>
|
||||
))}
|
||||
<IconButton icon="edit" size="small" title="Edit" onClick={(e) => setAnchor(e.currentTarget)} />
|
||||
{anchor && props.chooser(anchor, () => setAnchor(null))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const userPresentation = (u: GHUser): ChooserItemPresentation => ({
|
||||
text: u.login,
|
||||
detail: u.name,
|
||||
avatarUrl: u.avatarUrl,
|
||||
});
|
||||
|
||||
function reviewerPresentation(r: GHPullRequestRequestedReviewer): ChooserItemPresentation {
|
||||
if (isTeam(r)) return { text: r.slug, detail: r.teamName, avatarUrl: r.teamAvatarUrl };
|
||||
return { text: r.login, detail: r.name ?? null, avatarUrl: r.avatarUrl };
|
||||
}
|
||||
|
||||
function UserItem({ text, avatarUrl }: { text: string; avatarUrl?: string | null }) {
|
||||
return (
|
||||
<span className={styles.userItem}>
|
||||
<Avatar url={avatarUrl} name={text} size={AVATAR_SIZE.BASE} />
|
||||
<span>{text}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function MetadataGrid() {
|
||||
const reviewers = useCreatePr((s) => s.reviewers);
|
||||
const assignees = useCreatePr((s) => s.assignees);
|
||||
const labels = useCreatePr((s) => s.labels);
|
||||
const me = useGhRepository((s) => s.connection?.currentUser);
|
||||
const potentialReviewers = usePotentialReviewers();
|
||||
const potentialAssignees = useRepositoryList("assignees");
|
||||
const repoLabels = useRepositoryList("labels");
|
||||
return (
|
||||
<div className={styles.metadata}>
|
||||
<ListRow
|
||||
label="Reviewers:"
|
||||
emptyLabel="No reviewers"
|
||||
items={reviewers}
|
||||
getKey={reviewerKey}
|
||||
renderItem={(r) => <UserItem {...reviewerPresentation(r)} />}
|
||||
chooser={(anchor, close) => (
|
||||
<ChooserPopup<GHPullRequestRequestedReviewer>
|
||||
mode="multi"
|
||||
anchor={anchor}
|
||||
placement="top-start"
|
||||
items={selectableReviewers(potentialReviewers.items, me)}
|
||||
loading={potentialReviewers.loading}
|
||||
error={potentialReviewers.error}
|
||||
chosen={reviewers}
|
||||
getKey={reviewerKey}
|
||||
present={reviewerPresentation}
|
||||
aria-label="Reviewers"
|
||||
onClose={(chosen) => {
|
||||
setReviewers(chosen);
|
||||
close();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<ListRow
|
||||
label="Assignees:"
|
||||
emptyLabel="Unassigned"
|
||||
items={assignees}
|
||||
getKey={(u) => u.login}
|
||||
renderItem={(u) => <UserItem text={u.login} avatarUrl={u.avatarUrl} />}
|
||||
chooser={(anchor, close) => (
|
||||
<ChooserPopup<GHUser>
|
||||
mode="multi"
|
||||
anchor={anchor}
|
||||
placement="top-start"
|
||||
items={potentialAssignees.items}
|
||||
loading={potentialAssignees.loading}
|
||||
error={potentialAssignees.error}
|
||||
chosen={assignees}
|
||||
getKey={(u) => u.login}
|
||||
present={userPresentation}
|
||||
aria-label="Assignees"
|
||||
onClose={(chosen) => {
|
||||
setAssignees(chosen);
|
||||
close();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<ListRow
|
||||
label="Labels:"
|
||||
emptyLabel="No labels"
|
||||
items={labels}
|
||||
getKey={(l) => l.name}
|
||||
renderItem={(l) => <LabelChip label={l} />}
|
||||
chooser={(anchor, close) => (
|
||||
<ChooserPopup<GHLabel>
|
||||
mode="multi"
|
||||
anchor={anchor}
|
||||
placement="top-start"
|
||||
items={repoLabels.items}
|
||||
loading={repoLabels.loading}
|
||||
error={repoLabels.error}
|
||||
chosen={labels}
|
||||
getKey={(l) => l.name}
|
||||
present={(l) => ({ text: l.name, leading: <LabelSwatch label={l} /> })}
|
||||
aria-label="Labels"
|
||||
onClose={(chosen) => {
|
||||
setLabels(chosen);
|
||||
close();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/** "New Remote Branch for Pull Request": the name to push a local head without a push target to. */
|
||||
import { useState } from "react";
|
||||
import { Dialog, Input, T } from "@/ui";
|
||||
import { openDialog } from "../ui/dialogs";
|
||||
import styles from "./Create.module.css";
|
||||
|
||||
/** Asks for the remote branch name (suggesting `suggested`); null when cancelled. */
|
||||
export function remoteBranchNameDialog(suggested: string): Promise<string | null> {
|
||||
return openDialog<string>((done) => <RemoteBranchDialog suggested={suggested} onDone={done} />);
|
||||
}
|
||||
|
||||
function RemoteBranchDialog(props: { suggested: string; onDone: (name: string | null) => void }) {
|
||||
const [name, setName] = useState(props.suggested);
|
||||
const valid = !!name.trim();
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
title="New Remote Branch for Pull Request"
|
||||
onClose={() => props.onDone(null)}
|
||||
width={420}
|
||||
buttons={[
|
||||
{ label: "OK", role: "default", disabled: !valid, onClick: () => props.onDone(name.trim()) },
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<form
|
||||
className={styles.dialogForm}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (valid) props.onDone(name.trim());
|
||||
}}
|
||||
>
|
||||
<label className={styles.dialogLabel}>
|
||||
<T>Remote branch name:</T>
|
||||
</label>
|
||||
<Input data-autofocus aria-label="Remote branch name" value={name} onChange={(e) => setName(e.target.value)} />
|
||||
<div className={styles.dialogComment}>
|
||||
<T>Your changes will be pushed to the remote repository to create the pull request</T>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Branch } from "@/platform/ipc";
|
||||
import type { GHRemote } from "../data/repository";
|
||||
import {
|
||||
baseText,
|
||||
checkBranches,
|
||||
cleanUpBranchName,
|
||||
commitDescription,
|
||||
commitsRange,
|
||||
defaultBaseBranch,
|
||||
defaultDirection,
|
||||
generateTitle,
|
||||
headRefName,
|
||||
headText,
|
||||
needsPush,
|
||||
pushTarget,
|
||||
remoteBranchesOf,
|
||||
searchHead,
|
||||
splitRemoteBranch,
|
||||
trackedHead,
|
||||
type Direction,
|
||||
} from "./model";
|
||||
import { canCreate, selectableReviewers } from "./store";
|
||||
|
||||
const branch = (name: string, extra: Partial<Branch> = {}): Branch => ({
|
||||
name,
|
||||
remote: false,
|
||||
current: false,
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
lastCommitMs: null,
|
||||
...extra,
|
||||
});
|
||||
const remote = (name: string, commit?: string) => branch(name, { remote: true, commit });
|
||||
|
||||
const origin: GHRemote = { owner: "l0ng-ai", name: "openidea", remote: "origin", url: "" };
|
||||
const fork: GHRemote = { owner: "me", name: "openidea", remote: "fork", url: "" };
|
||||
|
||||
const branches = [
|
||||
branch("feature", { current: true, upstream: "fork/feature", commit: "a1" }),
|
||||
branch("local-only", { commit: "b1" }),
|
||||
branch("tracking-main", { upstream: "origin/main", commit: "c1" }),
|
||||
remote("origin/HEAD"),
|
||||
remote("origin/main", "c1"),
|
||||
remote("origin/master", "m1"),
|
||||
remote("fork/feature", "a0"),
|
||||
];
|
||||
|
||||
describe("merge direction", () => {
|
||||
it("splits remote branches by the longest remote name", () => {
|
||||
expect(splitRemoteBranch("origin/feat/x", ["origin"])).toEqual({ remote: "origin", name: "feat/x" });
|
||||
expect(splitRemoteBranch("my/fork/x", ["my", "my/fork"])).toEqual({ remote: "my/fork", name: "x" });
|
||||
expect(splitRemoteBranch("upstream/x", ["origin"])).toBeNull();
|
||||
});
|
||||
|
||||
it("lists a remote's branches without HEAD", () => {
|
||||
expect(remoteBranchesOf(branches, "origin").map((b) => b.name)).toEqual(["main", "master"]);
|
||||
});
|
||||
|
||||
it("defaults the base to the repository default, then master, then main", () => {
|
||||
expect(defaultBaseBranch(branches, "origin", "main")).toEqual({ remote: "origin", name: "main" });
|
||||
expect(defaultBaseBranch(branches, "origin", "develop")).toEqual({ remote: "origin", name: "master" });
|
||||
expect(defaultBaseBranch([remote("origin/main")], "origin", null)).toEqual({ remote: "origin", name: "main" });
|
||||
expect(defaultBaseBranch([], "origin", "main")).toBeNull();
|
||||
});
|
||||
|
||||
it("defaults the head to the current branch in its tracked remote's repository", () => {
|
||||
const d = defaultDirection({
|
||||
baseRepo: origin,
|
||||
remotes: [origin, fork],
|
||||
branches,
|
||||
currentBranch: "feature",
|
||||
defaultBranch: "main",
|
||||
});
|
||||
expect(d.headRepo).toBe(fork);
|
||||
expect(d.headBranch).toEqual({ kind: "local", name: "feature" });
|
||||
expect(d.baseBranch).toEqual({ remote: "origin", name: "main" });
|
||||
const untracked = defaultDirection({
|
||||
baseRepo: origin,
|
||||
remotes: [origin, fork],
|
||||
branches,
|
||||
currentBranch: "local-only",
|
||||
defaultBranch: "main",
|
||||
});
|
||||
expect(untracked.headRepo).toBe(origin);
|
||||
});
|
||||
|
||||
it("shows the owner only when the repositories differ", () => {
|
||||
const same: Direction = {
|
||||
baseRepo: origin,
|
||||
baseBranch: { remote: "origin", name: "main" },
|
||||
headRepo: origin,
|
||||
headBranch: { kind: "local", name: "feature" },
|
||||
};
|
||||
expect(baseText(same)).toBe("openidea:main");
|
||||
expect(headText(same)).toBe("openidea:feature");
|
||||
const forked: Direction = { ...same, headRepo: fork, headBranch: { kind: "remote", remote: "fork", name: "x" } };
|
||||
expect(baseText(forked)).toBe("l0ng-ai/openidea:main");
|
||||
expect(headText(forked)).toBe("me/openidea:fork/x");
|
||||
expect(baseText({ ...same, baseBranch: null })).toBeNull();
|
||||
expect(headText({ ...same, headRepo: null })).toBeNull();
|
||||
});
|
||||
|
||||
it("builds the log range and the API head names", () => {
|
||||
expect(commitsRange({ remote: "origin", name: "main" }, { kind: "local", name: "f" })).toBe("origin/main..f");
|
||||
expect(commitsRange({ remote: "origin", name: "main" }, { kind: "remote", remote: "fork", name: "f" })).toBe(
|
||||
"origin/main..fork/f",
|
||||
);
|
||||
expect(headRefName(origin, origin, "f")).toBe("f");
|
||||
expect(headRefName(origin, fork, "f")).toBe("me:f");
|
||||
expect(searchHead(origin, "f")).toBe("l0ng-ai:f");
|
||||
});
|
||||
});
|
||||
|
||||
describe("branches check", () => {
|
||||
const base = { remote: "origin", name: "main" };
|
||||
const head = { kind: "local" as const, name: "tracking-main" };
|
||||
|
||||
it("finds the tracked branch of the head", () => {
|
||||
expect(trackedHead(head, branches, ["origin", "fork"])).toEqual(base);
|
||||
expect(trackedHead({ kind: "local", name: "local-only" }, branches, ["origin"])).toBeNull();
|
||||
});
|
||||
|
||||
it("reports no changes, an existing pull request, or OK", () => {
|
||||
expect(checkBranches({ base, head, tracked: base, commits: [1], existing: null })).toEqual({
|
||||
kind: "noChanges",
|
||||
base: "main",
|
||||
head: "tracking-main",
|
||||
});
|
||||
expect(checkBranches({ base, head, tracked: null, commits: [], existing: 3 }).kind).toBe("noChanges");
|
||||
expect(checkBranches({ base, head, tracked: null, commits: [1], existing: 3 })).toEqual({
|
||||
kind: "alreadyExists",
|
||||
number: 3,
|
||||
});
|
||||
expect(checkBranches({ base, head, tracked: null, commits: [1], existing: null })).toEqual({ kind: "ok" });
|
||||
});
|
||||
|
||||
it("enables Create only for OK while nothing runs or after a failure", () => {
|
||||
const okCheck = { state: "ok" as const, value: { kind: "ok" as const } };
|
||||
expect(canCreate({ check: okCheck, creation: null })).toBe(true);
|
||||
expect(canCreate({ check: okCheck, creation: { kind: "error", error: "x" } })).toBe(true);
|
||||
expect(canCreate({ check: okCheck, creation: { kind: "pushing" } })).toBe(false);
|
||||
expect(canCreate({ check: { state: "loading" }, creation: null })).toBe(false);
|
||||
expect(canCreate({ check: { state: "ok", value: { kind: "alreadyExists", number: 1 } }, creation: null })).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("push target", () => {
|
||||
it("is the tracked branch on the head's remote", () => {
|
||||
expect(pushTarget(branches, "feature", "fork", ["origin", "fork"])).toEqual({ remote: "fork", name: "feature" });
|
||||
expect(pushTarget(branches, "feature", "origin", ["origin", "fork"])).toBeNull();
|
||||
expect(pushTarget(branches, "local-only", "origin", ["origin", "fork"])).toBeNull();
|
||||
});
|
||||
|
||||
it("needs a push when the tips differ or the remote branch is missing", () => {
|
||||
expect(needsPush(branches, "feature", { remote: "fork", name: "feature" })).toBe(true);
|
||||
expect(needsPush(branches, "tracking-main", { remote: "origin", name: "main" })).toBe(false);
|
||||
expect(needsPush(branches, "local-only", { remote: "origin", name: "local-only" })).toBe(true);
|
||||
});
|
||||
|
||||
it("cleans up branch names like GitRefNameValidator", () => {
|
||||
expect(cleanUpBranchName(" my feature: v2? ")).toBe("my_feature__v2_");
|
||||
expect(cleanUpBranchName("a..b~c^d")).toBe("a_b_c_d");
|
||||
expect(cleanUpBranchName("/x.lock")).toBe("x_lock");
|
||||
});
|
||||
});
|
||||
|
||||
describe("text", () => {
|
||||
it("titles with the only commit's subject, else the branch", () => {
|
||||
const head = { kind: "local" as const, name: "feature" };
|
||||
expect(generateTitle([{ summary: "Fix it" }], head)).toBe("Fix it");
|
||||
expect(generateTitle([{ summary: "a" }, { summary: "b" }], head)).toBe("feature");
|
||||
expect(generateTitle([], { kind: "remote", remote: "fork", name: "x" })).toBe("fork/x");
|
||||
});
|
||||
|
||||
it("takes the description paragraph of a commit message", () => {
|
||||
expect(commitDescription("Subject\n\nBody line\nmore\n\nTrailer: x")).toBe("Body line\nmore");
|
||||
expect(commitDescription("Subject")).toBe("");
|
||||
});
|
||||
|
||||
it("leaves the current user out of the reviewers", () => {
|
||||
const me = { __typename: "User" as const, id: "1", login: "me", url: "", avatarUrl: "", name: null };
|
||||
const other = { ...me, id: "2", login: "other" };
|
||||
const team = {
|
||||
__typename: "Team" as const,
|
||||
id: "1",
|
||||
slug: "core",
|
||||
url: "",
|
||||
teamAvatarUrl: null,
|
||||
teamName: "Core",
|
||||
combinedSlug: "org/core",
|
||||
};
|
||||
expect(selectableReviewers([me, other, team], me)).toEqual([other, team]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,216 @@
|
||||
/**
|
||||
* Pure logic of the New Pull Request tab (IntelliJ's `GHPRCreateViewModel` and
|
||||
* `GHPRCreateMergeDirectionModel`): the merge direction (base and head repository and
|
||||
* branch) and how it is shown, the default branches, the branches check, the generated
|
||||
* title and the push target of a local head.
|
||||
*/
|
||||
import type { Branch, Commit } from "@/platform/ipc";
|
||||
import type { GHRepositoryCoordinates } from "../api/types";
|
||||
import type { GHRemote } from "../data/repository";
|
||||
|
||||
/** A branch of a remote (`origin/main` is `{ remote: "origin", name: "main" }`). */
|
||||
export interface RemoteBranchRef {
|
||||
remote: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/** The head: a local branch or a remote one (`GitLocalBranch` / `GitRemoteBranch`). */
|
||||
export type HeadBranch = { kind: "local"; name: string } | ({ kind: "remote" } & RemoteBranchRef);
|
||||
|
||||
/** `BranchesState`: the base is always a branch of the connected repository. */
|
||||
export interface Direction {
|
||||
baseRepo: GHRemote;
|
||||
baseBranch: RemoteBranchRef | null;
|
||||
headRepo: GHRemote | null;
|
||||
headBranch: HeadBranch | null;
|
||||
}
|
||||
|
||||
const sameCoordinates = (a: GHRepositoryCoordinates, b: GHRepositoryCoordinates) =>
|
||||
a.owner.toLowerCase() === b.owner.toLowerCase() && a.name.toLowerCase() === b.name.toLowerCase();
|
||||
|
||||
/** `origin/main` → `{ remote: "origin", name: "main" }`, the longest matching remote name winning. */
|
||||
export function splitRemoteBranch(full: string, remotes: readonly string[]): RemoteBranchRef | null {
|
||||
const remote = [...remotes].filter((r) => r && full.startsWith(`${r}/`)).sort((a, b) => b.length - a.length)[0];
|
||||
return remote ? { remote, name: full.slice(remote.length + 1) } : null;
|
||||
}
|
||||
|
||||
export const remoteBranchFullName = (b: RemoteBranchRef) => `${b.remote}/${b.name}`;
|
||||
|
||||
/** What git calls the head (`feature`, `origin/feature`). */
|
||||
export const headBranchName = (b: HeadBranch) => (b.kind === "local" ? b.name : remoteBranchFullName(b));
|
||||
|
||||
export const sameRemoteBranch = (a: RemoteBranchRef | null | undefined, b: RemoteBranchRef | null | undefined) =>
|
||||
!!a && !!b && a.remote === b.remote && a.name === b.name;
|
||||
|
||||
export function sameHead(a: HeadBranch | null, b: HeadBranch | null): boolean {
|
||||
if (!a || !b) return a === b;
|
||||
if (a.kind === "local" || b.kind === "local") return a.kind === b.kind && a.name === b.name;
|
||||
return sameRemoteBranch(a, b);
|
||||
}
|
||||
|
||||
/** The branches of `remote` (its `HEAD` pointer left out), sorted by name. */
|
||||
export function remoteBranchesOf(branches: readonly Branch[], remote: string): RemoteBranchRef[] {
|
||||
return branches
|
||||
.filter((b) => b.remote)
|
||||
.flatMap((b) => {
|
||||
const ref = splitRemoteBranch(b.name, [remote]);
|
||||
return ref && ref.name !== "HEAD" ? [ref] : [];
|
||||
})
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** Local branches, sorted by name. */
|
||||
export function localBranchesOf(branches: readonly Branch[]): HeadBranch[] {
|
||||
return branches
|
||||
.filter((b) => !b.remote)
|
||||
.map((b): HeadBranch => ({ kind: "local", name: b.name }))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/**
|
||||
* `getDefaultRemoteBranch`: the repository's default branch on the base remote, else
|
||||
* `master`, else `main`.
|
||||
*/
|
||||
export function defaultBaseBranch(
|
||||
branches: readonly Branch[],
|
||||
remote: string,
|
||||
defaultBranch: string | null | undefined,
|
||||
): RemoteBranchRef | null {
|
||||
const names = new Set(remoteBranchesOf(branches, remote).map((b) => b.name));
|
||||
const name = [defaultBranch, "master", "main"].find((n): n is string => !!n && names.has(n));
|
||||
return name ? { remote, name } : null;
|
||||
}
|
||||
|
||||
/** The remote branch a local branch tracks (`upstream`), split by the known remotes. */
|
||||
export function upstreamOf(
|
||||
branches: readonly Branch[],
|
||||
local: string,
|
||||
remotes: readonly string[],
|
||||
): RemoteBranchRef | null {
|
||||
const upstream = branches.find((b) => !b.remote && b.name === local)?.upstream;
|
||||
return upstream ? splitRemoteBranch(upstream, remotes) : null;
|
||||
}
|
||||
|
||||
/** The remote branch the head is or tracks (none for an untracked local branch). */
|
||||
export function trackedHead(
|
||||
head: HeadBranch,
|
||||
branches: readonly Branch[],
|
||||
remotes: readonly string[],
|
||||
): RemoteBranchRef | null {
|
||||
return head.kind === "remote" ? head : upstreamOf(branches, head.name, remotes);
|
||||
}
|
||||
|
||||
/**
|
||||
* The default direction: base the default branch of the connected repository's remote,
|
||||
* head the current branch in the repository of its tracked remote (else the base one).
|
||||
*/
|
||||
export function defaultDirection(opts: {
|
||||
baseRepo: GHRemote;
|
||||
remotes: readonly GHRemote[];
|
||||
branches: readonly Branch[];
|
||||
currentBranch: string | null;
|
||||
defaultBranch: string | null | undefined;
|
||||
}): Direction {
|
||||
const { baseRepo, remotes, branches, currentBranch } = opts;
|
||||
const names = remotes.map((r) => r.remote);
|
||||
const tracked = currentBranch ? upstreamOf(branches, currentBranch, names) : null;
|
||||
const headRepo = (tracked && remotes.find((r) => r.remote === tracked.remote)) || baseRepo;
|
||||
return {
|
||||
baseRepo,
|
||||
baseBranch: defaultBaseBranch(branches, baseRepo.remote, opts.defaultBranch),
|
||||
headRepo,
|
||||
headBranch: currentBranch ? { kind: "local", name: currentBranch } : null,
|
||||
};
|
||||
}
|
||||
|
||||
const repoText = (r: GHRepositoryCoordinates, showOwner: boolean) => (showOwner ? `${r.owner}/${r.name}` : r.name);
|
||||
|
||||
/** The base as the direction selector shows it: `repo:branch`, `owner/repo:branch` when the head's repository differs. */
|
||||
export function baseText(d: Direction): string | null {
|
||||
if (!d.baseBranch) return null;
|
||||
const showOwner = !!d.headRepo && !sameCoordinates(d.headRepo, d.baseRepo);
|
||||
return `${repoText(d.baseRepo, showOwner)}:${d.baseBranch.name}`;
|
||||
}
|
||||
|
||||
/** The head as the direction selector shows it: `repo:branch` (`origin/branch` for a remote branch). */
|
||||
export function headText(d: Direction): string | null {
|
||||
if (!d.headBranch || !d.headRepo) return null;
|
||||
const showOwner = !sameCoordinates(d.headRepo, d.baseRepo);
|
||||
return `${repoText(d.headRepo, showOwner)}:${headBranchName(d.headBranch)}`;
|
||||
}
|
||||
|
||||
/** `git log base..head`. */
|
||||
export const commitsRange = (base: RemoteBranchRef, head: HeadBranch) =>
|
||||
`${remoteBranchFullName(base)}..${headBranchName(head)}`;
|
||||
|
||||
/** `generateTitle`: the subject of the only commit, else the branch name. */
|
||||
export function generateTitle(commits: readonly Pick<Commit, "summary">[], head: HeadBranch): string {
|
||||
return commits.length === 1 ? commits[0]!.summary : headBranchName(head);
|
||||
}
|
||||
|
||||
/** `headRefName` of `createPullRequest`: `owner:branch` for a branch of another repository (a fork). */
|
||||
export function headRefName(baseRepo: GHRepositoryCoordinates, headRepo: GHRepositoryCoordinates, branch: string) {
|
||||
return sameCoordinates(baseRepo, headRepo) ? branch : `${headRepo.owner}:${branch}`;
|
||||
}
|
||||
|
||||
/** `head` of the REST pull request search: always `owner:branch`. */
|
||||
export const searchHead = (headRepo: GHRepositoryCoordinates, branch: string) => `${headRepo.owner}:${branch}`;
|
||||
|
||||
/** `GitPushUtil.findPushTarget`: the tracked branch when it is on the head's remote. */
|
||||
export function pushTarget(
|
||||
branches: readonly Branch[],
|
||||
local: string,
|
||||
headRemote: string,
|
||||
remotes: readonly string[],
|
||||
): RemoteBranchRef | null {
|
||||
const upstream = upstreamOf(branches, local, remotes);
|
||||
return upstream?.remote === headRemote ? upstream : null;
|
||||
}
|
||||
|
||||
/** Whether the local branch differs from its push target (or the target does not exist yet). */
|
||||
export function needsPush(branches: readonly Branch[], local: string, target: RemoteBranchRef): boolean {
|
||||
const localTip = branches.find((b) => !b.remote && b.name === local)?.commit;
|
||||
const remoteTip = branches.find((b) => b.remote && b.name === remoteBranchFullName(target))?.commit;
|
||||
return !localTip || !remoteTip || localTip !== remoteTip;
|
||||
}
|
||||
|
||||
const ILLEGAL_REF_CHARS = /[\u0000- \u007f~^:?*[\\]|\.\.|@\{/g; // eslint-disable-line no-control-regex
|
||||
|
||||
/** `GitRefNameValidator.cleanUpBranchName`: characters git refuses become `_`. */
|
||||
export function cleanUpBranchName(name: string): string {
|
||||
return name
|
||||
.trim()
|
||||
.replace(ILLEGAL_REF_CHARS, "_")
|
||||
.replace(/^[./-]+|[./]+$/g, "")
|
||||
.replace(/\.lock$/, "_lock");
|
||||
}
|
||||
|
||||
/** `BranchesCheckResult`. */
|
||||
export type BranchesCheckResult =
|
||||
| { kind: "noChanges"; base: string; head: string }
|
||||
| { kind: "alreadyExists"; number: number }
|
||||
| { kind: "ok" };
|
||||
|
||||
/**
|
||||
* `checkBranches`: no changes when the head tracks the base or has no commits over
|
||||
* it, else an open pull request of the head, else OK.
|
||||
*/
|
||||
export function checkBranches(opts: {
|
||||
base: RemoteBranchRef;
|
||||
head: HeadBranch;
|
||||
tracked: RemoteBranchRef | null;
|
||||
commits: readonly unknown[];
|
||||
existing: number | null;
|
||||
}): BranchesCheckResult {
|
||||
const { base, head } = opts;
|
||||
const noChanges = { kind: "noChanges" as const, base: base.name, head: headBranchName(head) };
|
||||
if (sameRemoteBranch(base, opts.tracked)) return noChanges;
|
||||
if (opts.commits.length === 0) return noChanges;
|
||||
if (opts.existing !== null) return { kind: "alreadyExists", number: opts.existing };
|
||||
return { kind: "ok" };
|
||||
}
|
||||
|
||||
/** The description part of a commit message (`fullMessage.split("\n\n")[1]`). */
|
||||
export function commitDescription(message: string): string {
|
||||
return message.split("\n\n")[1]?.trim() ?? "";
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
/**
|
||||
* State of the New Pull Request tab (IntelliJ's `GHPRCreateViewModel`), kept while the
|
||||
* tab is open (switching tabs keeps the form) and dropped when it closes:
|
||||
*
|
||||
* - the merge direction, its commits (`git log base..head`), the branches check and the
|
||||
* changes of all commits (three-dot diff) or of the selected one, all computed locally;
|
||||
* - the title (the only commit's subject or the branch name until edited), the
|
||||
* description (the repository's template) and the reviewers, assignees and labels;
|
||||
* - creation: push a local head first (asking for the remote branch name when it has
|
||||
* none), `createPullRequest`, then the metadata; on success the pull request opens and
|
||||
* the tab closes.
|
||||
*/
|
||||
import { create } from "zustand";
|
||||
import { commitFileDiffData, type DiffData } from "@/features/vcs/diffInput";
|
||||
import { lastRemoteFailure, runRemote } from "@/features/vcs/ops";
|
||||
import { useVcs } from "@/features/vcs/store";
|
||||
import type { Branch, ChangeKind, Commit } from "@/platform/ipc";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { errorMessage } from "../api/client";
|
||||
import * as api from "../api/requests";
|
||||
import type { GHLabel, GHPullRequestRequestedReviewer, GHUser } from "../api/types";
|
||||
import { isTeam } from "../data/model";
|
||||
import { createPullRequest } from "../data/operations";
|
||||
import { loadPullRequestTemplate, requireConnection, sameRepository, useGhRepository } from "../data/repository";
|
||||
import type { GHRemote } from "../data/repository";
|
||||
import { refreshCurrentBranchPullRequest } from "../reviewMode/state";
|
||||
import { openPullRequest } from "../toolwindow/open";
|
||||
import { closeTab, useGhTabs } from "../toolwindow/store";
|
||||
import {
|
||||
checkBranches,
|
||||
cleanUpBranchName,
|
||||
commitsRange,
|
||||
defaultDirection,
|
||||
generateTitle,
|
||||
headBranchName,
|
||||
headRefName,
|
||||
needsPush,
|
||||
pushTarget,
|
||||
remoteBranchFullName,
|
||||
sameHead,
|
||||
sameRemoteBranch,
|
||||
searchHead,
|
||||
trackedHead,
|
||||
type BranchesCheckResult,
|
||||
type Direction,
|
||||
type HeadBranch,
|
||||
type RemoteBranchRef,
|
||||
} from "./model";
|
||||
import { remoteBranchNameDialog } from "./RemoteBranchDialog";
|
||||
|
||||
export type Loadable<T> = { state: "loading" } | { state: "error"; error: string } | { state: "ok"; value: T };
|
||||
|
||||
/** A changed file of the preview, with its diff. */
|
||||
export interface CreateChange {
|
||||
/** Repository-relative path (after the change). */
|
||||
path: string;
|
||||
oldPath: string | null;
|
||||
kind: ChangeKind;
|
||||
diff: DiffData;
|
||||
}
|
||||
|
||||
/** `CreationState` (CollectingData, Pushing, CallingAPI, SettingMetadata, Created, Error). */
|
||||
export type CreationState =
|
||||
| { kind: "collecting" | "pushing" | "creating" | "metadata" | "created" }
|
||||
| { kind: "error"; error: string };
|
||||
|
||||
interface CreateState {
|
||||
/** Initialized (branches read, direction chosen). */
|
||||
ready: boolean;
|
||||
initError: string | null;
|
||||
/** Local and remote branches of the repository. */
|
||||
branches: Branch[];
|
||||
direction: Direction | null;
|
||||
/** `git log base..head`, newest first; null until base and head are chosen. */
|
||||
commits: Loadable<Commit[]> | null;
|
||||
check: Loadable<BranchesCheckResult> | null;
|
||||
/** The commit whose changes are shown; null: all commits. */
|
||||
selectedCommit: string | null;
|
||||
changes: Loadable<CreateChange[]> | null;
|
||||
title: string;
|
||||
/** The user typed a title: it no longer follows the commits. */
|
||||
titleEdited: boolean;
|
||||
description: string;
|
||||
descriptionEdited: boolean;
|
||||
templateLoading: boolean;
|
||||
reviewers: GHPullRequestRequestedReviewer[];
|
||||
assignees: GHUser[];
|
||||
labels: GHLabel[];
|
||||
creation: CreationState | null;
|
||||
}
|
||||
|
||||
const initial: CreateState = {
|
||||
ready: false,
|
||||
initError: null,
|
||||
branches: [],
|
||||
direction: null,
|
||||
commits: null,
|
||||
check: null,
|
||||
selectedCommit: null,
|
||||
changes: null,
|
||||
title: "",
|
||||
titleEdited: false,
|
||||
description: "",
|
||||
descriptionEdited: false,
|
||||
templateLoading: false,
|
||||
reviewers: [],
|
||||
assignees: [],
|
||||
labels: [],
|
||||
creation: null,
|
||||
};
|
||||
|
||||
export const useCreatePr = create<CreateState>(() => ({ ...initial }));
|
||||
|
||||
/** Bumped by every reset: late results for a dropped form are ignored. */
|
||||
let generation = 0;
|
||||
/** Bumped by every direction change and refresh: late results of older checks are dropped. */
|
||||
let checkSeq = 0;
|
||||
let changesSeq = 0;
|
||||
|
||||
/** The repository's root, which the preview's repository-relative paths are relative to. */
|
||||
function repoRoot(): string | null {
|
||||
return useVcs.getState().roots[0] ?? useProject.getState().project?.root ?? null;
|
||||
}
|
||||
|
||||
const ok = <T>(value: T): Loadable<T> => ({ state: "ok", value });
|
||||
const failed = (e: unknown): Loadable<never> => ({ state: "error", error: errorMessage(e) });
|
||||
|
||||
const remoteNames = () => useGhRepository.getState().remotes.map((r) => r.remote);
|
||||
|
||||
/** The connected repository's GitHub remote (the base). */
|
||||
function baseRemote(): GHRemote {
|
||||
const { coordinates } = requireConnection();
|
||||
const remotes = useGhRepository.getState().remotes;
|
||||
return remotes.find((r) => sameRepository(r, coordinates)) ?? { ...coordinates, remote: "origin", url: "" };
|
||||
}
|
||||
|
||||
/** Reads the branches and picks the default direction; starts loading the template. */
|
||||
export async function initCreate(): Promise<void> {
|
||||
if (useCreatePr.getState().ready) return;
|
||||
const e = ++generation;
|
||||
try {
|
||||
const { repository } = requireConnection();
|
||||
const [branches, info] = await Promise.all([
|
||||
call(commands.vcsBranches(null)),
|
||||
call(commands.vcsBranchInfo(null)).catch(() => null),
|
||||
]);
|
||||
if (e !== generation) return;
|
||||
const direction = defaultDirection({
|
||||
baseRepo: baseRemote(),
|
||||
remotes: useGhRepository.getState().remotes,
|
||||
branches,
|
||||
currentBranch: info?.head ?? null,
|
||||
defaultBranch: repository.defaultBranchRef?.name,
|
||||
});
|
||||
useCreatePr.setState({ ready: true, initError: null, branches, direction, templateLoading: true });
|
||||
void loadPullRequestTemplate().then((template) => {
|
||||
if (e !== generation) return;
|
||||
const s = useCreatePr.getState();
|
||||
useCreatePr.setState({ templateLoading: false, ...(s.descriptionEdited ? {} : { description: template ?? "" }) });
|
||||
});
|
||||
reloadBranchesState();
|
||||
} catch (err) {
|
||||
if (e === generation) useCreatePr.setState({ initError: errorMessage(err) });
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops the form (the tab closed, another repository). */
|
||||
export function resetCreate() {
|
||||
generation++;
|
||||
checkSeq++;
|
||||
changesSeq++;
|
||||
useCreatePr.setState({ ...initial });
|
||||
}
|
||||
|
||||
export function setBaseBranch(branch: RemoteBranchRef) {
|
||||
const d = useCreatePr.getState().direction;
|
||||
if (!d || sameRemoteBranch(d.baseBranch, branch)) return;
|
||||
useCreatePr.setState({ direction: { ...d, baseBranch: branch } });
|
||||
reloadBranchesState();
|
||||
}
|
||||
|
||||
export function setHead(repo: GHRemote, branch: HeadBranch) {
|
||||
const d = useCreatePr.getState().direction;
|
||||
if (!d || (d.headRepo && sameRepository(d.headRepo, repo) && sameHead(d.headBranch, branch))) return;
|
||||
useCreatePr.setState({ direction: { ...d, headRepo: repo, headBranch: branch } });
|
||||
reloadBranchesState();
|
||||
}
|
||||
|
||||
/** The Refresh of a failed check: reads the branches again and checks them. */
|
||||
export async function refreshBranchesState(): Promise<void> {
|
||||
const branches = await call(commands.vcsBranches(null)).catch(() => null);
|
||||
if (branches) useCreatePr.setState({ branches });
|
||||
reloadBranchesState();
|
||||
}
|
||||
|
||||
const tip = (branches: readonly Branch[], name: string) => branches.find((b) => b.name === name)?.commit;
|
||||
|
||||
/** The repository changed: reloads the commits when the base or head moved (`infoStateIn`). */
|
||||
export async function onRepositoryChanged(): Promise<void> {
|
||||
const s = useCreatePr.getState();
|
||||
if (!s.ready || !s.direction) return;
|
||||
const branches = await call(commands.vcsBranches(null)).catch(() => null);
|
||||
if (!branches) return;
|
||||
const { baseBranch, headBranch } = useCreatePr.getState().direction ?? {};
|
||||
const before = useCreatePr.getState().branches;
|
||||
useCreatePr.setState({ branches });
|
||||
const moved = (name: string) => tip(before, name) !== tip(branches, name);
|
||||
if (
|
||||
(baseBranch && moved(remoteBranchFullName(baseBranch))) ||
|
||||
(headBranch && moved(headBranchName(headBranch))) ||
|
||||
(headBranch?.kind === "local" &&
|
||||
before.find((b) => b.name === headBranch.name)?.upstream !==
|
||||
branches.find((b) => b.name === headBranch.name)?.upstream)
|
||||
)
|
||||
reloadBranchesState();
|
||||
}
|
||||
|
||||
/** `BranchesStateWithProgress`: the commits, the open pull request of the head and the check. */
|
||||
function reloadBranchesState() {
|
||||
const e = ++checkSeq;
|
||||
const { direction: d, branches } = useCreatePr.getState();
|
||||
const base = d?.baseBranch;
|
||||
const head = d?.headBranch;
|
||||
const headRepo = d?.headRepo;
|
||||
if (!base || !head || !headRepo) {
|
||||
useCreatePr.setState({ commits: null, check: null, changes: null, selectedCommit: null });
|
||||
return;
|
||||
}
|
||||
const tracked = trackedHead(head, branches, remoteNames());
|
||||
const trackingBase = sameRemoteBranch(base, tracked);
|
||||
useCreatePr.setState({
|
||||
commits: { state: "loading" },
|
||||
changes: { state: "loading" },
|
||||
selectedCommit: null,
|
||||
check: trackingBase
|
||||
? ok(checkBranches({ base, head, tracked, commits: [], existing: null }))
|
||||
: { state: "loading" },
|
||||
});
|
||||
const existing = tracked
|
||||
? api
|
||||
.findOpenPullRequestsByHead(searchHead(headRepo, tracked.name), base.name)
|
||||
.then((prs) => prs[0]?.number ?? null)
|
||||
: Promise.resolve(null);
|
||||
existing.catch(() => undefined);
|
||||
const commits = call(
|
||||
commands.vcsLog(null, {
|
||||
branch: null,
|
||||
path: null,
|
||||
author: null,
|
||||
text: null,
|
||||
range: commitsRange(base, head),
|
||||
skip: 0,
|
||||
limit: 10_000,
|
||||
}),
|
||||
);
|
||||
void commits.then(
|
||||
(list) => {
|
||||
if (e !== checkSeq) return;
|
||||
const s = useCreatePr.getState();
|
||||
useCreatePr.setState({ commits: ok(list), ...(s.titleEdited ? {} : { title: generateTitle(list, head) }) });
|
||||
void loadChanges();
|
||||
},
|
||||
(err) => {
|
||||
if (e === checkSeq) useCreatePr.setState({ commits: failed(err), changes: null });
|
||||
},
|
||||
);
|
||||
if (trackingBase) return;
|
||||
void Promise.all([commits, existing]).then(
|
||||
([list, number]) => {
|
||||
if (e === checkSeq)
|
||||
useCreatePr.setState({ check: ok(checkBranches({ base, head, tracked, commits: list, existing: number })) });
|
||||
},
|
||||
(err) => {
|
||||
if (e === checkSeq) useCreatePr.setState({ check: failed(err) });
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** Shows the changes of commit `id` (null: all commits). */
|
||||
export function selectCommit(id: string | null) {
|
||||
if (useCreatePr.getState().selectedCommit === id) return;
|
||||
useCreatePr.setState({ selectedCommit: id });
|
||||
void loadChanges();
|
||||
}
|
||||
|
||||
/** Diff of a file of all commits: the merge base ↔ the head. */
|
||||
function rangeDiffData(
|
||||
file: { path: string; oldPath: string | null; kind: ChangeKind },
|
||||
root: string | null,
|
||||
base: { rev: string; label: string },
|
||||
head: { rev: string; label: string },
|
||||
): DiffData {
|
||||
const abs = (rel: string) => (root ? `${root}/${rel}` : rel);
|
||||
return {
|
||||
path: abs(file.path),
|
||||
left:
|
||||
file.kind === "added" || file.kind === "untracked"
|
||||
? { type: "text", text: "", label: tx("(does not exist)") }
|
||||
: { type: "rev", rev: base.rev, path: file.oldPath ? abs(file.oldPath) : undefined, label: base.label },
|
||||
right: file.kind === "deleted" ? { type: "text", text: "", label: tx("(deleted)") } : { type: "rev", ...head },
|
||||
};
|
||||
}
|
||||
|
||||
/** `getDiff`: the three-dot diff of all commits, or the selected commit's changes. */
|
||||
async function loadChanges() {
|
||||
const seq = ++changesSeq;
|
||||
const s = useCreatePr.getState();
|
||||
const d = s.direction;
|
||||
if (s.commits?.state !== "ok" || !d?.baseBranch || !d.headBranch) return;
|
||||
const list = s.commits.value;
|
||||
if (!list.length) {
|
||||
useCreatePr.setState({ changes: null });
|
||||
return;
|
||||
}
|
||||
useCreatePr.setState({ changes: { state: "loading" } });
|
||||
const root = repoRoot();
|
||||
try {
|
||||
let changes: CreateChange[];
|
||||
const commit = s.selectedCommit ? list.find((c) => c.id === s.selectedCommit) : null;
|
||||
if (commit) {
|
||||
const files = await call(commands.vcsCommitFiles(null, commit.id));
|
||||
changes = files.map((f) => ({ ...f, diff: commitFileDiffData({ ...commit, repo: root }, f) }));
|
||||
} else {
|
||||
const head = list[0]!.id;
|
||||
const baseName = remoteBranchFullName(d.baseBranch);
|
||||
const mergeBase = await call(commands.vcsMergeBase(null, baseName, head));
|
||||
if (!mergeBase) throw new Error(tx`Unrelated branches ${baseName} ${headBranchName(d.headBranch)}`);
|
||||
const files = await call(commands.vcsDiffRevisions(null, mergeBase, head));
|
||||
const baseSide = { rev: mergeBase, label: `${d.baseBranch.name} (${mergeBase.slice(0, 8)})` };
|
||||
const headSide = { rev: head, label: `${headBranchName(d.headBranch)} (${head.slice(0, 8)})` };
|
||||
changes = files.map((f) => ({ ...f, diff: rangeDiffData(f, root, baseSide, headSide) }));
|
||||
}
|
||||
if (seq === changesSeq) useCreatePr.setState({ changes: ok(changes) });
|
||||
} catch (err) {
|
||||
if (seq === changesSeq) useCreatePr.setState({ changes: failed(err) });
|
||||
}
|
||||
}
|
||||
|
||||
export function setTitle(title: string) {
|
||||
useCreatePr.setState({ title, titleEdited: true });
|
||||
}
|
||||
|
||||
export function setDescription(description: string) {
|
||||
useCreatePr.setState({ description, descriptionEdited: true });
|
||||
}
|
||||
|
||||
export function setReviewers(reviewers: GHPullRequestRequestedReviewer[]) {
|
||||
useCreatePr.setState({ reviewers });
|
||||
}
|
||||
|
||||
export function setAssignees(assignees: GHUser[]) {
|
||||
useCreatePr.setState({ assignees });
|
||||
}
|
||||
|
||||
export function setLabels(labels: GHLabel[]) {
|
||||
useCreatePr.setState({ labels });
|
||||
}
|
||||
|
||||
/** Create is enabled when the check is OK and nothing runs (or the last attempt failed). */
|
||||
export function canCreate(s: Pick<CreateState, "check" | "creation">): boolean {
|
||||
return s.check?.state === "ok" && s.check.value.kind === "ok" && (s.creation === null || s.creation.kind === "error");
|
||||
}
|
||||
|
||||
/** Pushes a local head when needed; resolves with the remote branch name, null when cancelled. */
|
||||
async function pushHead(head: Extract<HeadBranch, { kind: "local" }>, headRepo: GHRemote): Promise<string | null> {
|
||||
const branches = useCreatePr.getState().branches;
|
||||
let target = pushTarget(branches, head.name, headRepo.remote, remoteNames());
|
||||
if (!target) {
|
||||
const name = await remoteBranchNameDialog(head.name);
|
||||
if (name === null) return null;
|
||||
target = { remote: headRepo.remote, name: cleanUpBranchName(name) };
|
||||
}
|
||||
if (needsPush(branches, head.name, target)) {
|
||||
useCreatePr.setState({ creation: { kind: "pushing" } });
|
||||
const pushed = await runRemote(
|
||||
{
|
||||
op: "pushBranch",
|
||||
branch: head.name,
|
||||
revision: null,
|
||||
force_with_lease: false,
|
||||
target: target.name,
|
||||
remote: target.remote,
|
||||
},
|
||||
`${head.name} → ${remoteBranchFullName(target)}`,
|
||||
[null],
|
||||
);
|
||||
if (!pushed) {
|
||||
const error = lastRemoteFailure();
|
||||
// Cancelled: back to the form.
|
||||
if (!error) return null;
|
||||
throw new Error(tx`Push failed: ${error}`);
|
||||
}
|
||||
const after = await call(commands.vcsBranches(null)).catch(() => null);
|
||||
if (after) useCreatePr.setState({ branches: after });
|
||||
}
|
||||
return target.name;
|
||||
}
|
||||
|
||||
/** "Create Pull Request" / "Create Draft Pull Request". */
|
||||
export async function createFromForm(draft: boolean): Promise<void> {
|
||||
const s = useCreatePr.getState();
|
||||
const d = s.direction;
|
||||
if (!canCreate(s) || !d?.baseBranch || !d.headBranch || !d.headRepo) return;
|
||||
const { baseBranch, headBranch, headRepo } = d;
|
||||
const e = generation;
|
||||
useCreatePr.setState({ creation: { kind: "collecting" } });
|
||||
try {
|
||||
const remoteName = headBranch.kind === "remote" ? headBranch.name : await pushHead(headBranch, headRepo);
|
||||
if (remoteName === null) {
|
||||
useCreatePr.setState({ creation: null });
|
||||
return;
|
||||
}
|
||||
useCreatePr.setState({ creation: { kind: "creating" } });
|
||||
const { coordinates } = requireConnection();
|
||||
const pr = await createPullRequest({
|
||||
base: baseBranch.name,
|
||||
head: headRefName(coordinates, headRepo, remoteName),
|
||||
title: s.title,
|
||||
body: s.description,
|
||||
draft,
|
||||
reviewers: s.reviewers,
|
||||
assignees: s.assignees.map((u) => u.login),
|
||||
labels: s.labels.map((l) => l.name),
|
||||
onSettingMetadata: () => useCreatePr.setState({ creation: { kind: "metadata" } }),
|
||||
});
|
||||
useCreatePr.setState({ creation: { kind: "created" } });
|
||||
void refreshCurrentBranchPullRequest();
|
||||
await openPullRequest(pr.number);
|
||||
closeTab("create");
|
||||
} catch (err) {
|
||||
if (e === generation) useCreatePr.setState({ creation: { kind: "error", error: errorMessage(err) } });
|
||||
}
|
||||
}
|
||||
|
||||
/** The reviewers one can pick: not the current user. */
|
||||
export function selectableReviewers(items: readonly GHPullRequestRequestedReviewer[], me: GHUser | null | undefined) {
|
||||
return me ? items.filter((r) => isTeam(r) || r.id !== me.id) : [...items];
|
||||
}
|
||||
|
||||
// The form lives as long as its tab.
|
||||
useGhTabs.subscribe((t, prev) => {
|
||||
const open = t.tabs.some((x) => x.kind === "create");
|
||||
if (!open && prev.tabs.some((x) => x.kind === "create")) resetCreate();
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* Incrementally loaded lists (IntelliJ's `BatchesLoader` / `IncrementallyComputedValue`):
|
||||
* pages are appended as they arrive, so choosers show the first users while the rest load.
|
||||
* A list loads once and stays cached until `reset()`.
|
||||
*/
|
||||
import { create, type StoreApi, type UseBoundStore } from "zustand";
|
||||
import { errorMessage } from "../api/client";
|
||||
|
||||
export interface BatchesState<T> {
|
||||
items: T[];
|
||||
/** A page is being fetched. */
|
||||
loading: boolean;
|
||||
/** Every page arrived. */
|
||||
done: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface BatchesLoader<T> {
|
||||
store: UseBoundStore<StoreApi<BatchesState<T>>>;
|
||||
/** Starts loading unless loaded or loading; resolves with every item (rejects on failure). */
|
||||
load(): Promise<T[]>;
|
||||
/** Forgets the items; the next `load()` starts over. */
|
||||
reset(): void;
|
||||
}
|
||||
|
||||
const initial = <T>(): BatchesState<T> => ({ items: [], loading: false, done: false, error: null });
|
||||
|
||||
/** A loader fetching `page(cursor)` from `first` until `next` is null. */
|
||||
export function createBatchesLoader<T, C>(
|
||||
first: C,
|
||||
page: (cursor: C) => Promise<{ items: T[]; next: C | null }>,
|
||||
): BatchesLoader<T> {
|
||||
const store = create<BatchesState<T>>(() => initial<T>());
|
||||
let run: Promise<T[]> | null = null;
|
||||
let generation = 0;
|
||||
const load = () => {
|
||||
if (run) return run;
|
||||
const gen = ++generation;
|
||||
const alive = () => gen === generation;
|
||||
store.setState({ ...initial<T>(), loading: true });
|
||||
run = (async () => {
|
||||
let cursor: C | null = first;
|
||||
try {
|
||||
while (cursor !== null) {
|
||||
const r: { items: T[]; next: C | null } = await page(cursor);
|
||||
if (!alive()) return store.getState().items;
|
||||
store.setState((s) => ({ items: [...s.items, ...r.items] }));
|
||||
cursor = r.next;
|
||||
}
|
||||
if (alive()) store.setState({ loading: false, done: true });
|
||||
return store.getState().items;
|
||||
} catch (e) {
|
||||
if (alive()) {
|
||||
store.setState({ loading: false, error: errorMessage(e) });
|
||||
run = null;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
})();
|
||||
return run;
|
||||
};
|
||||
const reset = () => {
|
||||
generation++;
|
||||
run = null;
|
||||
store.setState(initial<T>());
|
||||
};
|
||||
return { store, load, reset };
|
||||
}
|
||||
|
||||
/** Merges several loaders' states (potential reviewers: teams + users), keeping their order. */
|
||||
export function mergeBatches<T>(states: ReadonlyArray<BatchesState<T>>): BatchesState<T> {
|
||||
return {
|
||||
items: states.flatMap((s) => s.items),
|
||||
loading: states.some((s) => s.loading),
|
||||
done: states.every((s) => s.done),
|
||||
error: states.find((s) => s.error)?.error ?? null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type {
|
||||
GHActor,
|
||||
GHPullRequestMergeabilityData,
|
||||
GHPullRequestReview,
|
||||
GHPullRequestShort,
|
||||
GHTeam,
|
||||
GHUser,
|
||||
} from "../api/types";
|
||||
import { createBatchesLoader, mergeBatches } from "./batches";
|
||||
import {
|
||||
buildMergeabilityState,
|
||||
filterCount,
|
||||
hasPermission,
|
||||
isSeen,
|
||||
listSearchQuery,
|
||||
mergeCommitMessage,
|
||||
normalizeSearch,
|
||||
parseGitHubRemote,
|
||||
remoteOfRepository,
|
||||
pullRequestPermissions,
|
||||
pullRequestStateIcon,
|
||||
repositoryDisplayName,
|
||||
reviewersStates,
|
||||
reviewerStateOf,
|
||||
searchTerms,
|
||||
sortedReviewersStates,
|
||||
splitCommitMessage,
|
||||
stateTagText,
|
||||
unresolvedThreadsCount,
|
||||
} from "./model";
|
||||
import { githubRemotes } from "./repository";
|
||||
import { withSearch } from "./searchHistory";
|
||||
|
||||
const user = (login: string): GHUser => ({
|
||||
__typename: "User",
|
||||
id: `id-${login}`,
|
||||
login,
|
||||
url: `https://github.com/${login}`,
|
||||
avatarUrl: "",
|
||||
name: null,
|
||||
});
|
||||
const team: GHTeam = {
|
||||
__typename: "Team",
|
||||
id: "T1",
|
||||
slug: "core",
|
||||
url: "",
|
||||
teamAvatarUrl: null,
|
||||
teamName: "Core",
|
||||
combinedSlug: "org/core",
|
||||
};
|
||||
let reviewSeq = 0;
|
||||
const review = (author: GHActor | null, state: GHPullRequestReview["state"], minute: number): GHPullRequestReview => ({
|
||||
__typename: "PullRequestReview",
|
||||
id: `R${++reviewSeq}`,
|
||||
url: "",
|
||||
author,
|
||||
body: "",
|
||||
state,
|
||||
createdAt: `2026-10-01T10:${String(minute).padStart(2, "0")}:00Z`,
|
||||
viewerCanUpdate: false,
|
||||
});
|
||||
|
||||
function pr(over: Partial<GHPullRequestShort> = {}): GHPullRequestShort {
|
||||
return {
|
||||
id: "PR1",
|
||||
url: "https://github.com/o/r/pull/1",
|
||||
number: 1,
|
||||
title: "Fix",
|
||||
state: "OPEN",
|
||||
isDraft: false,
|
||||
author: user("ann"),
|
||||
createdAt: "2026-10-01T09:00:00Z",
|
||||
updatedAt: "2026-10-01T12:00:00Z",
|
||||
isReadByViewer: false,
|
||||
assignees: { nodes: [] },
|
||||
labels: { nodes: [] },
|
||||
reviewRequests: { nodes: [] },
|
||||
reviewThreads: { nodes: [] },
|
||||
reviews: { nodes: [] },
|
||||
reactions: {
|
||||
pageInfo: { startCursor: null, endCursor: null, hasNextPage: false, hasPreviousPage: false },
|
||||
nodes: [],
|
||||
},
|
||||
mergeable: "MERGEABLE",
|
||||
viewerCanUpdate: false,
|
||||
viewerCanReact: true,
|
||||
viewerDidAuthor: false,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
describe("list search", () => {
|
||||
it("builds IntelliJ's terms in order", () => {
|
||||
expect(
|
||||
searchTerms({
|
||||
searchQuery: "foo bar",
|
||||
state: "MERGED",
|
||||
assignee: "me",
|
||||
reviewState: "NOT_REVIEWED_BY_ME",
|
||||
author: "ann",
|
||||
label: "good first issue",
|
||||
sort: "LEAST_RECENTLY_UPDATED",
|
||||
}),
|
||||
).toBe('(foo bar) is:merged assignee:me -reviewed-by:@me author:ann label:"good first issue" sort:updated-asc');
|
||||
expect(searchTerms({ reviewState: "AWAITING_REVIEW" })).toBe("review-requested:@me");
|
||||
expect(searchTerms({})).toBeNull();
|
||||
});
|
||||
|
||||
it("prefixes the repository for issueSearch", () => {
|
||||
expect(listSearchQuery({ owner: "o", name: "r" }, { state: "OPEN" })).toBe("type:pr repo:o/r is:open");
|
||||
expect(listSearchQuery({ owner: "o", name: "r" }, {})).toBe("type:pr repo:o/r");
|
||||
});
|
||||
|
||||
it("keeps GitHub's boolean syntax inside the repository", () => {
|
||||
const q = "is:pr is:open (review-requested:ann OR assignee:@ann)";
|
||||
expect(listSearchQuery({ owner: "o", name: "r" }, { searchQuery: q })).toBe(`type:pr repo:o/r (${q})`);
|
||||
expect(searchTerms({ searchQuery: " " })).toBeNull();
|
||||
});
|
||||
|
||||
it("counts filters and normalizes stored values", () => {
|
||||
expect(filterCount({ searchQuery: "x", state: "OPEN", sort: "NEWEST" })).toBe(3);
|
||||
expect(normalizeSearch({ state: "OPEN", sort: "SIDEWAYS", label: "", author: "ann", extra: 1 })).toEqual({
|
||||
state: "OPEN",
|
||||
author: "ann",
|
||||
});
|
||||
expect(normalizeSearch("nope")).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps searches with filters in the history, newest first, at most 10", () => {
|
||||
let h = withSearch([], { state: "OPEN" });
|
||||
expect(h).toEqual([]); // the default
|
||||
h = withSearch(h, {});
|
||||
expect(h).toEqual([]); // no filters
|
||||
h = withSearch(h, { author: "a" });
|
||||
h = withSearch(h, { author: "b" });
|
||||
h = withSearch(h, { author: "a" });
|
||||
expect(h).toEqual([{ author: "a" }, { author: "b" }]);
|
||||
for (let i = 0; i < 12; i++) h = withSearch(h, { label: `l${i}` });
|
||||
expect(h).toHaveLength(10);
|
||||
expect(h[0]).toEqual({ label: "l11" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("reviewer states", () => {
|
||||
it("lets the newest opinionated review win over later comments", () => {
|
||||
expect(reviewerStateOf([review(user("bo"), "APPROVED", 1), review(user("bo"), "COMMENTED", 2)])).toBe("APPROVED");
|
||||
expect(reviewerStateOf([review(user("bo"), "APPROVED", 1), review(user("bo"), "CHANGES_REQUESTED", 2)])).toBe(
|
||||
"CHANGES_REQUESTED",
|
||||
);
|
||||
});
|
||||
|
||||
it("surfaces a dismissed latest review as a comment", () => {
|
||||
expect(reviewerStateOf([review(user("bo"), "APPROVED", 1), review(user("bo"), "DISMISSED", 2)])).toBe("COMMENTED");
|
||||
});
|
||||
|
||||
it("skips reviewers with only pending reviews", () => {
|
||||
expect(reviewerStateOf([review(user("bo"), "PENDING", 1)])).toBeNull();
|
||||
expect(reviewerStateOf([review(user("bo"), "PENDING", 2), review(user("bo"), "COMMENTED", 1)])).toBe("COMMENTED");
|
||||
});
|
||||
|
||||
it("excludes the author and marks requests as re-requested or needing review", () => {
|
||||
const states = reviewersStates(
|
||||
pr({
|
||||
reviews: {
|
||||
nodes: [
|
||||
review(user("ann"), "COMMENTED", 1),
|
||||
review(user("bo"), "APPROVED", 2),
|
||||
review(user("cy"), "COMMENTED", 3),
|
||||
],
|
||||
},
|
||||
reviewRequests: {
|
||||
nodes: [{ requestedReviewer: user("cy") }, { requestedReviewer: team }, { requestedReviewer: null }],
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
states.map((s) => [s.reviewer.__typename === "Team" ? "team" : (s.reviewer as GHUser).login, s.state]),
|
||||
).toEqual([
|
||||
["bo", "APPROVED"],
|
||||
["cy", "RE_REQUESTED"],
|
||||
["team", "NEEDS_REVIEW"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("counts reviews of deleted users under the ghost user", () => {
|
||||
const states = reviewersStates(pr({ reviews: { nodes: [review(null, "APPROVED", 1)] } }));
|
||||
expect(states).toHaveLength(1);
|
||||
expect((states[0]!.reviewer as GHUser).login).toBe("ghost");
|
||||
});
|
||||
|
||||
it("orders the row's avatars approved → changes → commented → re-requested → needs review", () => {
|
||||
const states = sortedReviewersStates(
|
||||
pr({
|
||||
reviews: {
|
||||
nodes: [
|
||||
review(user("c"), "COMMENTED", 1),
|
||||
review(user("x"), "CHANGES_REQUESTED", 2),
|
||||
review(user("a"), "APPROVED", 3),
|
||||
],
|
||||
},
|
||||
reviewRequests: { nodes: [{ requestedReviewer: user("n") }] },
|
||||
}),
|
||||
);
|
||||
expect(states.map((s) => s.state)).toEqual(["APPROVED", "CHANGES_REQUESTED", "COMMENTED", "NEEDS_REVIEW"]);
|
||||
});
|
||||
|
||||
it("counts unresolved, current threads", () => {
|
||||
expect(
|
||||
unresolvedThreadsCount(
|
||||
pr({
|
||||
reviewThreads: {
|
||||
nodes: [
|
||||
{ isResolved: false, isOutdated: false },
|
||||
{ isResolved: true, isOutdated: false },
|
||||
{ isResolved: false, isOutdated: true },
|
||||
],
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("unread", () => {
|
||||
const me = { id: "id-me" };
|
||||
const updated = Date.parse("2026-10-01T12:00:00Z");
|
||||
|
||||
it("only applies to pull requests the user wrote or is asked to review", () => {
|
||||
expect(isSeen(pr(), me, null)).toBe(true);
|
||||
expect(isSeen(pr({ author: user("me") }), me, null)).toBe(false);
|
||||
expect(isSeen(pr({ reviewRequests: { nodes: [{ requestedReviewer: user("me") }] } }), me, null)).toBe(false);
|
||||
});
|
||||
|
||||
it("compares the last seen time, with a 5 s margin, with the update", () => {
|
||||
const mine = pr({ author: user("me") });
|
||||
expect(isSeen(mine, me, updated - 4000)).toBe(true);
|
||||
expect(isSeen(mine, me, updated - 6000)).toBe(false);
|
||||
expect(isSeen(mine, me, updated + 1)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mergeability", () => {
|
||||
const data = (over: Partial<GHPullRequestMergeabilityData> = {}): GHPullRequestMergeabilityData => ({
|
||||
mergeable: "MERGEABLE",
|
||||
canBeRebased: true,
|
||||
mergeStateStatus: "CLEAN",
|
||||
baseRef: null,
|
||||
commits: {
|
||||
pageInfo: { startCursor: null, endCursor: null, hasNextPage: false, hasPreviousPage: false },
|
||||
nodes: [
|
||||
{
|
||||
id: "c",
|
||||
commit: {
|
||||
id: "c",
|
||||
oid: "abc",
|
||||
abbreviatedOid: "abc",
|
||||
status: {
|
||||
contexts: [
|
||||
{ context: "ci/a", state: "SUCCESS", isRequired: true, targetUrl: "u1" },
|
||||
{ context: "ci/b", state: "ERROR", isRequired: false, targetUrl: null },
|
||||
],
|
||||
},
|
||||
checkSuites: {
|
||||
pageInfo: { startCursor: null, endCursor: null, hasNextPage: false, hasPreviousPage: false },
|
||||
nodes: [
|
||||
{
|
||||
checkRuns: {
|
||||
pageInfo: { startCursor: null, endCursor: null, hasNextPage: false, hasPreviousPage: false },
|
||||
nodes: [
|
||||
{ name: "build", conclusion: null, isRequired: false, detailsUrl: null, url: "run" },
|
||||
{ name: "lint", conclusion: "SKIPPED", isRequired: false, detailsUrl: "d", url: "run2" },
|
||||
{ name: "test", conclusion: "TIMED_OUT", isRequired: true, detailsUrl: null, url: "run3" },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
...over,
|
||||
});
|
||||
const rule = {
|
||||
allowsDeletions: false,
|
||||
allowsForcePushes: false,
|
||||
pattern: "main",
|
||||
requiredApprovingReviewCount: 2,
|
||||
requiredStatusCheckContexts: ["ci/a"],
|
||||
requiresLinearHistory: false,
|
||||
requiresSignatures: false,
|
||||
viewerCanPush: true,
|
||||
};
|
||||
|
||||
it("maps statuses and check runs to CI jobs", () => {
|
||||
const s = buildMergeabilityState(data(), false);
|
||||
expect(s.ciJobs.map((j) => [j.name, j.status, j.detailsUrl])).toEqual([
|
||||
["ci/a", "SUCCESS", "u1"],
|
||||
["ci/b", "FAILED", null],
|
||||
["build", "PENDING", "run"],
|
||||
["lint", "SKIPPED", "d"],
|
||||
["test", "FAILED", "run3"],
|
||||
]);
|
||||
expect(s).toMatchObject({
|
||||
hasConflicts: false,
|
||||
canBeMerged: true,
|
||||
checksState: null,
|
||||
requiredApprovingReviewsCount: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("follows the merge state and branch protection", () => {
|
||||
expect(buildMergeabilityState(data({ mergeable: "UNKNOWN" }), false).hasConflicts).toBeNull();
|
||||
expect(buildMergeabilityState(data({ mergeable: "CONFLICTING", mergeStateStatus: "DIRTY" }), false)).toMatchObject({
|
||||
hasConflicts: true,
|
||||
canBeMerged: false,
|
||||
});
|
||||
const blocked = data({ mergeStateStatus: "BLOCKED", baseRef: { refUpdateRule: rule } });
|
||||
expect(buildMergeabilityState(blocked, false)).toMatchObject({
|
||||
canBeMerged: false,
|
||||
checksState: null,
|
||||
requiredApprovingReviewsCount: 2,
|
||||
});
|
||||
expect(buildMergeabilityState(blocked, true).canBeMerged).toBe(true);
|
||||
const failing = data({
|
||||
mergeStateStatus: "BLOCKED",
|
||||
baseRef: { refUpdateRule: { ...rule, requiredStatusCheckContexts: ["ci/b"] } },
|
||||
});
|
||||
expect(buildMergeabilityState(failing, false)).toMatchObject({
|
||||
checksState: "BLOCKING_FAILING",
|
||||
requiredApprovingReviewsCount: 0,
|
||||
});
|
||||
expect(buildMergeabilityState(data({ mergeStateStatus: "BEHIND" }), false).checksState).toBe("BLOCKING_BEHIND");
|
||||
const restricted = data({
|
||||
mergeStateStatus: "BLOCKED",
|
||||
baseRef: { refUpdateRule: { ...rule, viewerCanPush: false } },
|
||||
});
|
||||
expect(buildMergeabilityState(restricted, false)).toMatchObject({
|
||||
isRestricted: true,
|
||||
requiredApprovingReviewsCount: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("decides the merge actions from permission, settings and state", () => {
|
||||
const repo = {
|
||||
viewerPermission: "WRITE" as const,
|
||||
mergeCommitAllowed: true,
|
||||
squashMergeAllowed: false,
|
||||
rebaseMergeAllowed: true,
|
||||
};
|
||||
const state = buildMergeabilityState(data(), false);
|
||||
expect(pullRequestPermissions({ viewerDidAuthor: false, state: "OPEN" }, repo, state)).toEqual({
|
||||
canManage: true,
|
||||
canMerge: true,
|
||||
canSquashMerge: false,
|
||||
canRebaseMerge: true,
|
||||
});
|
||||
expect(pullRequestPermissions({ viewerDidAuthor: false, state: "OPEN" }, repo, state, true).canMerge).toBe(false);
|
||||
const reader = { ...repo, viewerPermission: "READ" as const };
|
||||
expect(pullRequestPermissions({ viewerDidAuthor: true, state: "OPEN" }, reader, state)).toMatchObject({
|
||||
canManage: true,
|
||||
canMerge: false,
|
||||
});
|
||||
expect(pullRequestPermissions({ viewerDidAuthor: false, state: "OPEN" }, reader, state).canManage).toBe(false);
|
||||
expect(hasPermission("MAINTAIN", "WRITE")).toBe(true);
|
||||
expect(hasPermission(null, "READ")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pull request helpers", () => {
|
||||
it("names states like IntelliJ", () => {
|
||||
expect(stateTagText("OPEN", false)).toBeNull();
|
||||
expect(stateTagText("OPEN", true)).toBe("DRAFT");
|
||||
expect(stateTagText("MERGED", true)).toBe("MERGED");
|
||||
expect(pullRequestStateIcon("OPEN", true)).toBe("github-pr-draft");
|
||||
expect(pullRequestStateIcon("CLOSED", false)).toBe("github-pr-closed");
|
||||
});
|
||||
|
||||
it("prefills and splits merge commit messages", () => {
|
||||
expect(mergeCommitMessage({ number: 7, title: "Fix it" })).toBe("Merge pull request #7\n\nFix it");
|
||||
expect(mergeCommitMessage({ number: 7, title: "x" }, ["a", "b"])).toBe("Merge pull request #7\n\n* a\n\n* b");
|
||||
expect(splitCommitMessage("Subject\n\nBody\nmore")).toEqual({ title: "Subject", body: "Body\nmore" });
|
||||
expect(splitCommitMessage("Only")).toEqual({ title: "Only", body: "" });
|
||||
});
|
||||
|
||||
it("shows the owner only when owners differ", () => {
|
||||
const a = { owner: "me", name: "app" };
|
||||
const b = { owner: "org", name: "app" };
|
||||
expect(repositoryDisplayName([a], a)).toBe("app");
|
||||
expect(repositoryDisplayName([a, b], a)).toBe("me/app");
|
||||
expect(repositoryDisplayName([a, { owner: "me", name: "lib" }], a)).toBe("app");
|
||||
expect(repositoryDisplayName([a], a, true)).toBe("me/app");
|
||||
});
|
||||
|
||||
it("recognizes github.com remotes", () => {
|
||||
for (const url of [
|
||||
"https://github.com/o/r.git",
|
||||
"https://[email protected]/o/r",
|
||||
"[email protected]:o/r.git",
|
||||
"ssh://[email protected]/o/r.git",
|
||||
"ssh://[email protected]:22/o/r.git",
|
||||
"git://github.com/o/r",
|
||||
])
|
||||
expect(parseGitHubRemote(url), url).toEqual({ owner: "o", name: "r" });
|
||||
expect(parseGitHubRemote("https://gitlab.com/o/r.git")).toBeNull();
|
||||
expect(parseGitHubRemote("/local/repo")).toBeNull();
|
||||
expect(
|
||||
githubRemotes([
|
||||
{ name: "origin", url: "[email protected]:me/r.git" },
|
||||
{ name: "upstream", url: "https://github.com/org/r.git" },
|
||||
{ name: "dup", url: "https://github.com/ORG/r" },
|
||||
{ name: "other", url: "https://example.com/x/y" },
|
||||
]).map((r) => `${r.remote}=${r.owner}/${r.name}`),
|
||||
).toEqual(["origin=me/r", "upstream=org/r"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("batches", () => {
|
||||
let pages: Array<{ items: number[]; next: number | null }>;
|
||||
beforeEach(() => {
|
||||
pages = [
|
||||
{ items: [1, 2], next: 1 },
|
||||
{ items: [3], next: null },
|
||||
];
|
||||
});
|
||||
|
||||
it("appends pages as they arrive and loads once", async () => {
|
||||
let calls = 0;
|
||||
const loader = createBatchesLoader<number, number>(0, async (p) => {
|
||||
calls++;
|
||||
return pages[p]!;
|
||||
});
|
||||
const all = await loader.load();
|
||||
expect(all).toEqual([1, 2, 3]);
|
||||
expect(loader.store.getState()).toMatchObject({ items: [1, 2, 3], loading: false, done: true });
|
||||
await loader.load();
|
||||
expect(calls).toBe(2);
|
||||
loader.reset();
|
||||
expect(loader.store.getState().items).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps what loaded before a failure and retries on the next load", async () => {
|
||||
let fail = true;
|
||||
const loader = createBatchesLoader<number, number>(0, async (p) => {
|
||||
if (p === 1 && fail) throw new Error("boom");
|
||||
return pages[p]!;
|
||||
});
|
||||
await expect(loader.load()).rejects.toThrow("boom");
|
||||
expect(loader.store.getState()).toMatchObject({ items: [1, 2], loading: false, done: false, error: "boom" });
|
||||
fail = false;
|
||||
expect(await loader.load()).toEqual([1, 2, 3]);
|
||||
expect(
|
||||
mergeBatches([
|
||||
{ items: [1], loading: false, done: true, error: null },
|
||||
{ items: [2], loading: true, done: false, error: null },
|
||||
]),
|
||||
).toEqual({ items: [1, 2], loading: true, done: false, error: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("remoteOfRepository", () => {
|
||||
const repo = { owner: "Org", name: "app" };
|
||||
it("finds the remote behind an SSH host alias by the URL's path", () => {
|
||||
const alias = { name: "origin", url: "git@work-github:org/app.git" };
|
||||
expect(remoteOfRepository([{ name: "other", url: "git@work-github:org/app2.git" }, alias], repo)).toBe(alias);
|
||||
expect(remoteOfRepository([{ name: "x", url: "ssh://work-github/org/app/" }], repo)?.name).toBe("x");
|
||||
expect(remoteOfRepository([{ name: "x", url: "git@work-github:notorg/app.git" }], repo)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* When each pull request was last seen (IntelliJ's `GHPRPersistentInteractionState`),
|
||||
* stored per project; the list's unread dots compare it with `updatedAt` (`isSeen` in
|
||||
* `model.ts`). Entries of pull requests updated since and older than
|
||||
* `CLEAR_LAST_SEEN_AFTER_DAYS` are dropped.
|
||||
*/
|
||||
import { create } from "zustand";
|
||||
import { useProject } from "@/platform/project";
|
||||
import type { GHPullRequestShort, GHUser } from "../api/types";
|
||||
import { CLEAR_LAST_SEEN_AFTER_DAYS, isSeen } from "./model";
|
||||
|
||||
const key = (root: string) => `openidea.github.lastSeen.v1:${root}`;
|
||||
const projectRoot = () => useProject.getState().project?.root ?? null;
|
||||
|
||||
function load(root: string | null): Record<string, number> {
|
||||
if (!root) return {};
|
||||
try {
|
||||
const v = JSON.parse(globalThis.localStorage?.getItem(key(root)) ?? "{}") as unknown;
|
||||
if (!v || typeof v !== "object") return {};
|
||||
return Object.fromEntries(Object.entries(v).filter(([, t]) => typeof t === "number")) as Record<string, number>;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function save(root: string | null, lastSeen: Record<string, number>) {
|
||||
if (!root) return;
|
||||
try {
|
||||
globalThis.localStorage?.setItem(key(root), JSON.stringify(lastSeen));
|
||||
} catch {
|
||||
/* storage unavailable */
|
||||
}
|
||||
}
|
||||
|
||||
/** Last-seen times (ms) by pull request node id, for the open project. */
|
||||
export const useLastSeen = create<{ root: string | null; lastSeen: Record<string, number> }>(() => ({
|
||||
root: projectRoot(),
|
||||
lastSeen: load(projectRoot()),
|
||||
}));
|
||||
|
||||
function current(): Record<string, number> {
|
||||
const root = projectRoot();
|
||||
if (useLastSeen.getState().root !== root) useLastSeen.setState({ root, lastSeen: load(root) });
|
||||
return useLastSeen.getState().lastSeen;
|
||||
}
|
||||
|
||||
/** Records that the pull request with node id `prId` was seen now. */
|
||||
export function markSeen(prId: string, at = Date.now()) {
|
||||
const lastSeen = { ...current(), [prId]: at };
|
||||
useLastSeen.setState({ lastSeen });
|
||||
save(projectRoot(), lastSeen);
|
||||
}
|
||||
|
||||
/**
|
||||
* `isSeen` with the stored time; forgets entries that are stale (unseen updates, older than 14 days).
|
||||
* @public
|
||||
*/
|
||||
export function isPullRequestSeen(
|
||||
pr: Pick<GHPullRequestShort, "id" | "author" | "reviewRequests" | "updatedAt">,
|
||||
user: Pick<GHUser, "id">,
|
||||
now = Date.now(),
|
||||
): boolean {
|
||||
const all = current();
|
||||
const lastSeen = all[pr.id];
|
||||
const seen = isSeen(pr, user, lastSeen);
|
||||
if (!seen && lastSeen !== undefined && lastSeen < now - CLEAR_LAST_SEEN_AFTER_DAYS * 86_400_000) {
|
||||
const { [pr.id]: _, ...rest } = all;
|
||||
useLastSeen.setState({ lastSeen: rest });
|
||||
save(projectRoot(), rest);
|
||||
}
|
||||
return seen;
|
||||
}
|
||||
|
||||
/** React hook: whether `pr` is seen; re-renders when the last-seen times change. */
|
||||
export function usePullRequestSeen(
|
||||
pr: Pick<GHPullRequestShort, "id" | "author" | "reviewRequests" | "updatedAt">,
|
||||
user: Pick<GHUser, "id"> | null | undefined,
|
||||
): boolean {
|
||||
const lastSeen = useLastSeen((s) => s.lastSeen[pr.id]);
|
||||
return !user || isSeen(pr, user, lastSeen);
|
||||
}
|
||||
|
||||
useProject.subscribe((s, prev) => {
|
||||
const root = s.project?.root ?? null;
|
||||
if (root !== (prev.project?.root ?? null)) useLastSeen.setState({ root, lastSeen: load(root) });
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* The pull request list (IntelliJ's `GHPRListLoader` over `issueSearch`): pages of 50,
|
||||
* cursor-paged, for the current search value. `loadMore()` fetches the next page (the
|
||||
* list calls it while scrolling past 70%); `reloadList()` starts over, keeping the rows
|
||||
* visible until the first page arrives. Rows are refreshed in place when a pull request's
|
||||
* details load (`updateListItem`).
|
||||
*/
|
||||
import { create } from "zustand";
|
||||
import { errorMessage } from "../api/client";
|
||||
import * as api from "../api/requests";
|
||||
import type { GHPullRequest, GHPullRequestShort } from "../api/types";
|
||||
import { listSearchQuery, sameSearch, type PrSearchValue } from "./model";
|
||||
import { useGhRepository } from "./repository";
|
||||
|
||||
interface ListState {
|
||||
search: PrSearchValue;
|
||||
items: GHPullRequestShort[];
|
||||
cursor: string | null;
|
||||
hasMore: boolean;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
/** The first page of the current search arrived (`items` are for `search`). */
|
||||
loaded: boolean;
|
||||
}
|
||||
|
||||
export const useGhPrList = create<ListState>(() => ({
|
||||
search: {},
|
||||
items: [],
|
||||
cursor: null,
|
||||
hasMore: true,
|
||||
loading: false,
|
||||
error: null,
|
||||
loaded: false,
|
||||
}));
|
||||
|
||||
let seq = 0;
|
||||
|
||||
async function fetchPage(reset: boolean): Promise<void> {
|
||||
const repo = useGhRepository.getState().connection?.coordinates;
|
||||
if (!repo) return;
|
||||
const my = ++seq;
|
||||
const s = useGhPrList.getState();
|
||||
useGhPrList.setState({ loading: true, error: null });
|
||||
try {
|
||||
const page = await api.searchPullRequests(listSearchQuery(repo, s.search), reset ? null : s.cursor);
|
||||
if (my !== seq) return;
|
||||
useGhPrList.setState((cur) => {
|
||||
const items = reset
|
||||
? page.nodes
|
||||
: [...cur.items, ...page.nodes.filter((n) => !cur.items.some((i) => i.id === n.id))];
|
||||
return {
|
||||
items,
|
||||
cursor: page.pageInfo.endCursor,
|
||||
hasMore: page.pageInfo.hasNextPage,
|
||||
loading: false,
|
||||
loaded: true,
|
||||
};
|
||||
});
|
||||
} catch (e) {
|
||||
if (my !== seq) return;
|
||||
useGhPrList.setState({
|
||||
loading: false,
|
||||
error: errorMessage(e),
|
||||
hasMore: false,
|
||||
loaded: true,
|
||||
...(reset ? { items: [] } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Shows the pull requests matching `search` (from the first page). */
|
||||
export function setListSearch(search: PrSearchValue): Promise<void> {
|
||||
const same = sameSearch(useGhPrList.getState().search, search);
|
||||
useGhPrList.setState({ search, ...(same ? {} : { items: [], loaded: false }), cursor: null, hasMore: true });
|
||||
return fetchPage(true);
|
||||
}
|
||||
|
||||
/** Loads the next page, if there is one and none is loading. */
|
||||
export function loadMore(): Promise<void> {
|
||||
const s = useGhPrList.getState();
|
||||
if (s.loading || !s.hasMore || !s.loaded) return Promise.resolve();
|
||||
return fetchPage(false);
|
||||
}
|
||||
|
||||
/** "Refresh List": the current search from the first page. */
|
||||
export function reloadList(): Promise<void> {
|
||||
useGhPrList.setState({ cursor: null, hasMore: true });
|
||||
return fetchPage(true);
|
||||
}
|
||||
|
||||
/** Replaces the row of `pr` with fresher data (details loaded, a mutation's result). */
|
||||
export function updateListItem(pr: GHPullRequestShort | GHPullRequest) {
|
||||
useGhPrList.setState((s) => {
|
||||
const i = s.items.findIndex((x) => x.id === pr.id);
|
||||
if (i < 0) return s;
|
||||
const items = [...s.items];
|
||||
items[i] = { ...items[i]!, ...pickShort(pr) };
|
||||
return { items };
|
||||
});
|
||||
}
|
||||
|
||||
function pickShort(pr: GHPullRequestShort): GHPullRequestShort {
|
||||
const {
|
||||
id,
|
||||
url,
|
||||
number,
|
||||
title,
|
||||
state,
|
||||
isDraft,
|
||||
author,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
isReadByViewer,
|
||||
assignees,
|
||||
labels,
|
||||
reviewRequests,
|
||||
reviewThreads,
|
||||
reviews,
|
||||
reactions,
|
||||
mergeable,
|
||||
viewerCanUpdate,
|
||||
viewerCanReact,
|
||||
viewerDidAuthor,
|
||||
} = pr;
|
||||
return {
|
||||
id,
|
||||
url,
|
||||
number,
|
||||
title,
|
||||
state,
|
||||
isDraft,
|
||||
author,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
isReadByViewer,
|
||||
assignees,
|
||||
labels,
|
||||
reviewRequests,
|
||||
reviewThreads,
|
||||
reviews,
|
||||
reactions,
|
||||
mergeable,
|
||||
viewerCanUpdate,
|
||||
viewerCanReact,
|
||||
viewerDidAuthor,
|
||||
};
|
||||
}
|
||||
|
||||
/** Forgets the rows (disconnect, another repository). */
|
||||
export function clearList() {
|
||||
seq++;
|
||||
useGhPrList.setState({ items: [], cursor: null, hasMore: true, loading: false, error: null, loaded: false });
|
||||
}
|
||||
|
||||
useGhRepository.subscribe((s, prev) => {
|
||||
const a = s.connection?.coordinates;
|
||||
const b = prev.connection?.coordinates;
|
||||
if (a?.owner !== b?.owner || a?.name !== b?.name) clearList();
|
||||
});
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* Local git work for pull requests: checkout (`gh pr checkout`), fetching what a diff
|
||||
* needs (`ghPrPrepareDiff`, cached per head / base commit) and opening a changed file in
|
||||
* the diff viewer (`vcs.openDiff`; `diff/` shows its review threads). Long operations run
|
||||
* one at a time and are shown in the tool window's banner (`useGhBusy`), cancellable.
|
||||
*/
|
||||
import { Channel } from "@tauri-apps/api/core";
|
||||
import { create } from "zustand";
|
||||
import { withChain, type DiffData } from "@/features/vcs/diffInput";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import type { PrDiffRevisions, RequestId } from "@/platform/ipc";
|
||||
import { call, commands, isCancelled, nextRequestId } from "@/platform/ipc";
|
||||
import { openExternalUrl } from "@/platform/openUrl";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { errorMessage } from "../api/client";
|
||||
import type { GHCommitFile, GHPullRequest } from "../api/types";
|
||||
import { loadPullRequestData } from "./pullRequest";
|
||||
import { nameWithOwner, requireConnection } from "./repository";
|
||||
|
||||
/** The running operation (checkout, fetch for a diff) with its last output line. */
|
||||
export const useGhBusy = create<{ busy: { title: string; line: string; request: RequestId } | null }>(() => ({
|
||||
busy: null,
|
||||
}));
|
||||
|
||||
/** Runs a cancellable, streaming gh / git operation; null when it failed, was cancelled or another one runs. */
|
||||
export async function withBusy<T>(
|
||||
title: string,
|
||||
run: (request: RequestId, out: Channel<string>) => Promise<T>,
|
||||
): Promise<T | null> {
|
||||
if (useGhBusy.getState().busy) {
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
level: "info",
|
||||
title: "Another GitHub operation is still running",
|
||||
key: "github-busy",
|
||||
});
|
||||
return null;
|
||||
}
|
||||
const request = nextRequestId();
|
||||
const out = new Channel<string>();
|
||||
out.onmessage = (line) => useGhBusy.setState((s) => (s.busy ? { busy: { ...s.busy, line } } : s));
|
||||
useGhBusy.setState({ busy: { title, line: "", request } });
|
||||
try {
|
||||
return await run(request, out);
|
||||
} catch (e) {
|
||||
if (!isCancelled(e))
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
level: "error",
|
||||
title: `${title.replace(/…$/, "")} failed`,
|
||||
body: errorMessage(e),
|
||||
key: "github-op",
|
||||
});
|
||||
return null;
|
||||
} finally {
|
||||
useGhBusy.setState({ busy: null });
|
||||
}
|
||||
}
|
||||
|
||||
export function cancelBusy() {
|
||||
const b = useGhBusy.getState().busy;
|
||||
if (b) void commands.cancelRequest(b.request);
|
||||
}
|
||||
|
||||
/** "Checkout Branch": fetches and checks out the pull request's branch (gh's local name). */
|
||||
export async function checkoutPullRequest(number: number): Promise<boolean> {
|
||||
// The command resolves with nothing (`null`), which `withBusy` reports as a failure.
|
||||
const done = await withBusy(`Checking out #${number}…`, async (r, out) => {
|
||||
await call(commands.ghPrCheckout(r, number, out));
|
||||
return true;
|
||||
});
|
||||
if (done === null) return false;
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
level: "info",
|
||||
title: `Checked out pull request #${number}`,
|
||||
key: "github-checkout",
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
const diffCache = new Map<string, PrDiffRevisions>();
|
||||
|
||||
/** Fetches what the local repository lacks to diff `pr` (once per head / base commit). */
|
||||
export async function prepareDiff(pr: GHPullRequest): Promise<PrDiffRevisions | null> {
|
||||
const key = `${pr.number}:${pr.headRefOid}:${pr.baseRefOid}`;
|
||||
const hit = diffCache.get(key);
|
||||
if (hit) return hit;
|
||||
const repo = nameWithOwner(requireConnection().coordinates);
|
||||
const revs = await withBusy(`Fetching #${pr.number}…`, (r, out) =>
|
||||
call(commands.ghPrPrepareDiff(r, pr.number, pr.headRefOid, pr.baseRefOid, pr.baseRefName, repo, out)),
|
||||
);
|
||||
if (revs) diffCache.set(key, revs);
|
||||
return revs;
|
||||
}
|
||||
|
||||
export function clearDiffCache() {
|
||||
diffCache.clear();
|
||||
}
|
||||
|
||||
/** The diff context of a pull request's file (`diff/` shows its review there); `commit` for one commit's diff. */
|
||||
export const PULL_REQUEST_DIFF = "github.pullRequest";
|
||||
|
||||
/**
|
||||
* `DiffData` for a changed file of `pr`: merge base ↔ head, its context (`PULL_REQUEST_DIFF`)
|
||||
* naming the pull request and the file.
|
||||
*/
|
||||
export function fileDiffData(
|
||||
pr: Pick<GHPullRequest, "number" | "baseRefName" | "headRefName">,
|
||||
file: Pick<GHCommitFile, "filename" | "status" | "previousFilename">,
|
||||
revs: PrDiffRevisions,
|
||||
): DiffData {
|
||||
const root = revs.root;
|
||||
const changed = revs.files.find((f) => f.path === file.filename);
|
||||
const added = file.status === "added" || changed?.kind === "added";
|
||||
const deleted = file.status === "removed" || changed?.kind === "deleted";
|
||||
const oldPath = file.previousFilename ?? changed?.oldPath ?? null;
|
||||
const n = pr.number;
|
||||
const name = file.filename.slice(file.filename.lastIndexOf("/") + 1);
|
||||
return {
|
||||
path: `${root}/${file.filename}`,
|
||||
left: added
|
||||
? { type: "text", text: "", label: tx("(does not exist)") }
|
||||
: {
|
||||
type: "rev",
|
||||
rev: revs.base,
|
||||
path: oldPath ? `${root}/${oldPath}` : undefined,
|
||||
label: `${pr.baseRefName} (${revs.base.slice(0, 8)})`,
|
||||
},
|
||||
right: deleted
|
||||
? { type: "text", text: "", label: tx("(deleted)") }
|
||||
: { type: "rev", rev: revs.head, label: `#${n} ${pr.headRefName}` },
|
||||
title: `#${n}: ${name}`,
|
||||
context: { kind: PULL_REQUEST_DIFF, number: n, path: file.filename, commit: null },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens `path` of pull request `number` in the diff viewer (fetching what it needs first),
|
||||
* revealing the 0-based `line` of `side` (default right) when given (a review thread's line).
|
||||
* The pull request's other files follow in the chain (F7 past the last change).
|
||||
*/
|
||||
export async function openPullRequestFileDiff(
|
||||
number: number,
|
||||
path: string,
|
||||
opts: { line?: number; side?: "left" | "right" } = {},
|
||||
): Promise<void> {
|
||||
const [pr, files] = await Promise.all([
|
||||
loadPullRequestData(number, "details"),
|
||||
loadPullRequestData(number, "changes"),
|
||||
]);
|
||||
const revs = await prepareDiff(pr);
|
||||
if (!revs) return;
|
||||
const file = files.find((f) => f.filename === path) ?? {
|
||||
filename: path,
|
||||
status: "modified" as const,
|
||||
previousFilename: null,
|
||||
};
|
||||
const all = files.some((f) => f.filename === path) ? files : [...files, file];
|
||||
const data = withChain(
|
||||
all.map((f) => fileDiffData(pr, f, revs)),
|
||||
all.findIndex((f) => f.filename === path),
|
||||
);
|
||||
await executeAction("vcs.openDiff", opts.line == null ? data : { ...data, line: opts.line, lineSide: opts.side });
|
||||
}
|
||||
|
||||
/** "View Pull Request in Browser" and other links. */
|
||||
export function openInBrowser(url: string): Promise<void> {
|
||||
return openExternalUrl(url);
|
||||
}
|
||||
|
||||
/** "Copy Pull Request URL". */
|
||||
export async function copyUrl(url: string): Promise<void> {
|
||||
await navigator.clipboard?.writeText(url);
|
||||
}
|
||||
|
||||
/**
|
||||
* "Open in Worktree": fetches the pull request's head, adds the worktree
|
||||
* `<repository root>_PR_<n>` on it (detached) and opens it in a new window.
|
||||
*/
|
||||
export async function openInWorktree(number: number): Promise<void> {
|
||||
const pr = await loadPullRequestData(number, "details");
|
||||
const revs = await prepareDiff(pr);
|
||||
if (!revs) return;
|
||||
const path = `${String(revs.root).replace(/[\\/]+$/, "")}_PR_${number}`;
|
||||
const added = await withBusy(`Creating worktree for #${number}…`, async () => {
|
||||
await call(commands.vcsAddWorktree(null, path, pr.headRefOid, null));
|
||||
return true;
|
||||
});
|
||||
if (added) await executeAction("file.openInNewWindow", path);
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
/**
|
||||
* Pure rules of the pull request data, ported from IntelliJ: the list search value and
|
||||
* its query (`GHPRListSearchValue`, `GHPRSearchQuery`), reviewer states
|
||||
* (`GHReviewersUtils`), the unread rule (`GHPRPersistentInteractionState`), the merge box
|
||||
* state (`GHPRMergeabilityStateBuilder`), permissions (`GHPRSecurityService`) and the
|
||||
* merge commit messages (`GHPRReviewFlowViewModelImpl`).
|
||||
*/
|
||||
import type {
|
||||
CodeReviewCIJob,
|
||||
CodeReviewCIJobState,
|
||||
GHActor,
|
||||
GHCommitCheckSuiteConclusion,
|
||||
GHCommitStatusContextState,
|
||||
GHPRMergeabilityState,
|
||||
GHPRReviewerState,
|
||||
GHPullRequest,
|
||||
GHPullRequestMergeabilityData,
|
||||
GHPullRequestMergeStateStatus,
|
||||
GHPullRequestRequestedReviewer,
|
||||
GHPullRequestReview,
|
||||
GHPullRequestShort,
|
||||
GHPullRequestState,
|
||||
GHRepository,
|
||||
GHRepositoryCoordinates,
|
||||
GHRepositoryPermissionLevel,
|
||||
GHTeam,
|
||||
GHUser,
|
||||
} from "../api/types";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// List search (`GHPRListSearchValue`)
|
||||
|
||||
export type PrSearchState = "OPEN" | "CLOSED" | "MERGED";
|
||||
export type PrSearchReviewState =
|
||||
| "NO_REVIEW"
|
||||
| "REQUIRED"
|
||||
| "APPROVED"
|
||||
| "CHANGES_REQUESTED"
|
||||
| "REVIEWED_BY_ME"
|
||||
| "NOT_REVIEWED_BY_ME"
|
||||
| "AWAITING_REVIEW";
|
||||
export type PrSearchSort =
|
||||
| "NEWEST"
|
||||
| "OLDEST"
|
||||
| "MOST_COMMENTED"
|
||||
| "LEAST_COMMENTED"
|
||||
| "RECENTLY_UPDATED"
|
||||
| "LEAST_RECENTLY_UPDATED";
|
||||
|
||||
/** The list filter: free text plus the chips (author / assignee are logins). Unset = absent. */
|
||||
export interface PrSearchValue {
|
||||
searchQuery?: string;
|
||||
state?: PrSearchState;
|
||||
assignee?: string;
|
||||
reviewState?: PrSearchReviewState;
|
||||
author?: string;
|
||||
label?: string;
|
||||
sort?: PrSearchSort;
|
||||
}
|
||||
|
||||
/** `GHPRListSearchValue.DEFAULT`: the Quick Filters' "Open" (`EMPTY` is `{}`). */
|
||||
export const DEFAULT_SEARCH: PrSearchValue = { state: "OPEN" };
|
||||
|
||||
const SEARCH_KEYS = ["searchQuery", "state", "assignee", "reviewState", "author", "label", "sort"] as const;
|
||||
|
||||
const STATE_TERMS: Record<PrSearchState, string> = { OPEN: "is:open", CLOSED: "is:closed", MERGED: "is:merged" };
|
||||
const REVIEW_TERMS: Record<PrSearchReviewState, string> = {
|
||||
NO_REVIEW: "review:none",
|
||||
REQUIRED: "review:required",
|
||||
APPROVED: "review:approved",
|
||||
CHANGES_REQUESTED: "review:changes-requested",
|
||||
REVIEWED_BY_ME: "reviewed-by:@me",
|
||||
NOT_REVIEWED_BY_ME: "-reviewed-by:@me",
|
||||
AWAITING_REVIEW: "review-requested:@me",
|
||||
};
|
||||
const SORT_TERMS: Record<PrSearchSort, string> = {
|
||||
NEWEST: "sort:created-desc",
|
||||
OLDEST: "sort:created-asc",
|
||||
MOST_COMMENTED: "sort:comments-desc",
|
||||
LEAST_COMMENTED: "sort:comments-asc",
|
||||
RECENTLY_UPDATED: "sort:updated-desc",
|
||||
LEAST_RECENTLY_UPDATED: "sort:updated-asc",
|
||||
};
|
||||
|
||||
/** How many filters are set (the text counts as one), as the Quick Filters badge and "Clear {n} Filters". */
|
||||
export function filterCount(v: PrSearchValue): number {
|
||||
return SEARCH_KEYS.filter((k) => v[k] !== undefined).length;
|
||||
}
|
||||
|
||||
export function sameSearch(a: PrSearchValue, b: PrSearchValue): boolean {
|
||||
return SEARCH_KEYS.every((k) => a[k] === b[k]);
|
||||
}
|
||||
|
||||
/** A search value with only known, non-empty fields (from storage or a patch). */
|
||||
export function normalizeSearch(v: unknown): PrSearchValue | null {
|
||||
if (!v || typeof v !== "object") return null;
|
||||
const r = v as Record<string, unknown>;
|
||||
const str = (x: unknown) => (typeof x === "string" && x !== "" ? x : undefined);
|
||||
const oneOf = <T extends string>(x: unknown, all: Record<T, unknown>) =>
|
||||
typeof x === "string" && x in all ? (x as T) : undefined;
|
||||
const out: PrSearchValue = {
|
||||
searchQuery: str(r.searchQuery),
|
||||
state: oneOf(r.state, STATE_TERMS),
|
||||
assignee: str(r.assignee),
|
||||
reviewState: oneOf(r.reviewState, REVIEW_TERMS),
|
||||
author: str(r.author),
|
||||
label: str(r.label),
|
||||
sort: oneOf(r.sort, SORT_TERMS),
|
||||
};
|
||||
for (const k of SEARCH_KEYS) if (out[k] === undefined) delete out[k];
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The filter's search terms (`GHPRListSearchValue.toQuery`), or null when nothing is set.
|
||||
* The typed text is grouped in parentheses: GitHub's advanced search gives `OR` the lowest
|
||||
* precedence, so `a OR b` would otherwise escape the repository and the other filters.
|
||||
*/
|
||||
export function searchTerms(v: PrSearchValue): string | null {
|
||||
const terms: string[] = [];
|
||||
const text = v.searchQuery?.trim();
|
||||
if (text) terms.push(`(${text})`);
|
||||
if (v.state) terms.push(STATE_TERMS[v.state]);
|
||||
if (v.assignee !== undefined) terms.push(`assignee:${v.assignee}`);
|
||||
if (v.reviewState) terms.push(REVIEW_TERMS[v.reviewState]);
|
||||
if (v.author !== undefined) terms.push(`author:${v.author}`);
|
||||
if (v.label !== undefined) terms.push(`label:"${v.label}"`);
|
||||
if (v.sort) terms.push(SORT_TERMS[v.sort]);
|
||||
return terms.length ? terms.join(" ") : null;
|
||||
}
|
||||
|
||||
/** The `issueSearch` query of the list: `type:pr repo:owner/name` and the filter's terms. */
|
||||
export function listSearchQuery(repo: GHRepositoryCoordinates, v: PrSearchValue): string {
|
||||
const terms = searchTerms(v);
|
||||
return [`type:pr repo:${repo.owner}/${repo.name}`, terms].filter(Boolean).join(" ");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Reviewers (`GHReviewersUtils`)
|
||||
|
||||
export interface ReviewerWithState {
|
||||
reviewer: GHPullRequestRequestedReviewer;
|
||||
state: GHPRReviewerState;
|
||||
}
|
||||
|
||||
export const isTeam = (r: GHPullRequestRequestedReviewer | GHActor | null | undefined): r is GHTeam =>
|
||||
r?.__typename === "Team";
|
||||
|
||||
/** Login of a user / actor, `org/slug` of a team. */
|
||||
export function reviewerKey(r: GHPullRequestRequestedReviewer): string {
|
||||
return isTeam(r) ? r.combinedSlug : r.login;
|
||||
}
|
||||
|
||||
/** A reviewer's effective state from their reviews, newest first; null for no submitted review. */
|
||||
export function reviewerStateOf(reviews: readonly GHPullRequestReview[]): GHPRReviewerState | null {
|
||||
let commented = false;
|
||||
const newestFirst = [...reviews].sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));
|
||||
for (const review of newestFirst) {
|
||||
switch (review.state) {
|
||||
case "APPROVED":
|
||||
return "APPROVED";
|
||||
case "CHANGES_REQUESTED":
|
||||
return "CHANGES_REQUESTED";
|
||||
case "DISMISSED":
|
||||
return "COMMENTED";
|
||||
case "COMMENTED":
|
||||
commented = true;
|
||||
break;
|
||||
case "PENDING":
|
||||
break;
|
||||
}
|
||||
}
|
||||
return commented ? "COMMENTED" : null;
|
||||
}
|
||||
|
||||
/** Placeholder author of reviews whose user was deleted (IntelliJ's ghost user). */
|
||||
export const GHOST_USER: GHUser = {
|
||||
__typename: "User",
|
||||
id: "",
|
||||
login: "ghost",
|
||||
url: "https://github.com/ghost",
|
||||
avatarUrl: "https://avatars.githubusercontent.com/u/10137?v=4",
|
||||
name: "Deleted user",
|
||||
};
|
||||
|
||||
/**
|
||||
* Every reviewer of `pr` with their state, as GitHub shows them: reviewers by their
|
||||
* reviews (the author's own excluded), then the pending requests, which make a reviewer
|
||||
* who already reviewed RE_REQUESTED and one who did not NEEDS_REVIEW.
|
||||
*/
|
||||
export function reviewersStates(
|
||||
pr: Pick<GHPullRequestShort, "author" | "reviews" | "reviewRequests">,
|
||||
): ReviewerWithState[] {
|
||||
const result = new Map<string, ReviewerWithState>();
|
||||
const byReviewer = new Map<string, { reviewer: GHPullRequestRequestedReviewer; reviews: GHPullRequestReview[] }>();
|
||||
for (const review of pr.reviews.nodes) {
|
||||
const reviewer = review.author ?? GHOST_USER;
|
||||
const key = reviewerKey(reviewer);
|
||||
const group = byReviewer.get(key) ?? { reviewer, reviews: [] };
|
||||
group.reviews.push(review);
|
||||
byReviewer.set(key, group);
|
||||
}
|
||||
const authorKey = pr.author ? pr.author.login : null;
|
||||
for (const [key, { reviewer, reviews }] of byReviewer) {
|
||||
if (key === authorKey) continue;
|
||||
const state = reviewerStateOf(reviews);
|
||||
if (state) result.set(key, { reviewer, state });
|
||||
}
|
||||
for (const { requestedReviewer } of pr.reviewRequests.nodes) {
|
||||
if (!requestedReviewer) continue;
|
||||
const key = reviewerKey(requestedReviewer);
|
||||
result.set(key, { reviewer: requestedReviewer, state: result.has(key) ? "RE_REQUESTED" : "NEEDS_REVIEW" });
|
||||
}
|
||||
return [...result.values()];
|
||||
}
|
||||
|
||||
const REVIEWER_ORDER: Record<GHPRReviewerState, number> = {
|
||||
APPROVED: 0,
|
||||
CHANGES_REQUESTED: 1,
|
||||
COMMENTED: 2,
|
||||
RE_REQUESTED: 3,
|
||||
NEEDS_REVIEW: 4,
|
||||
};
|
||||
|
||||
/** `reviewersStates` ordered like the list row's avatars: approved → changes requested → commented → re-requested → needs review. */
|
||||
export function sortedReviewersStates(pr: Pick<GHPullRequestShort, "author" | "reviews" | "reviewRequests">) {
|
||||
return reviewersStates(pr).sort((a, b) => REVIEWER_ORDER[a.state] - REVIEWER_ORDER[b.state]);
|
||||
}
|
||||
|
||||
/** Review threads that are neither resolved nor outdated (the list row's comment counter). */
|
||||
export function unresolvedThreadsCount(pr: Pick<GHPullRequestShort, "reviewThreads">): number {
|
||||
return pr.reviewThreads.nodes.filter((t) => !t.isResolved && !t.isOutdated).length;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Unread (`GHPRPersistentInteractionState`)
|
||||
|
||||
/** Registry `github.last.seen.state.margin.millis`. */
|
||||
export const LAST_SEEN_MARGIN_MS = 5000;
|
||||
/** Registry `github.clear.last.seen.state.days`. */
|
||||
export const CLEAR_LAST_SEEN_AFTER_DAYS = 14;
|
||||
|
||||
/**
|
||||
* Whether `pr` counts as seen by `user`: always, unless the user wrote it or their review
|
||||
* is requested; then when it was last seen (ms, stored locally) no earlier than its update.
|
||||
*/
|
||||
export function isSeen(
|
||||
pr: Pick<GHPullRequestShort, "author" | "reviewRequests" | "updatedAt">,
|
||||
user: Pick<GHUser, "id">,
|
||||
lastSeen: number | null | undefined,
|
||||
): boolean {
|
||||
const involved =
|
||||
pr.author?.id === user.id || pr.reviewRequests.nodes.some((r) => r.requestedReviewer?.id === user.id);
|
||||
if (!involved) return true;
|
||||
return lastSeen != null && lastSeen + LAST_SEEN_MARGIN_MS >= Date.parse(pr.updatedAt);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pull request state
|
||||
|
||||
/** `GHUIUtil.getPullRequestStateIcon`. */
|
||||
export function pullRequestStateIcon(state: GHPullRequestState, isDraft: boolean): string {
|
||||
if (state === "MERGED") return "github-pr-merged";
|
||||
if (state === "CLOSED") return "github-pr-closed";
|
||||
return isDraft ? "github-pr-draft" : "github-pr-open";
|
||||
}
|
||||
|
||||
/** The state tag's text, or null for an open pull request (draft wins over open). */
|
||||
export function stateTagText(state: GHPullRequestState, isDraft: boolean): "DRAFT" | "CLOSED" | "MERGED" | null {
|
||||
if (state === "MERGED") return "MERGED";
|
||||
if (state === "CLOSED") return "CLOSED";
|
||||
return isDraft ? "DRAFT" : null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mergeability (`GHPRMergeabilityStateBuilder`)
|
||||
|
||||
const CAN_MERGE: ReadonlySet<GHPullRequestMergeStateStatus> = new Set(["CLEAN", "HAS_HOOKS", "UNSTABLE"]);
|
||||
const ADMIN_CAN_MERGE: ReadonlySet<GHPullRequestMergeStateStatus> = new Set(["BLOCKED", "BEHIND"]);
|
||||
|
||||
function contextJobState(s: GHCommitStatusContextState): CodeReviewCIJobState {
|
||||
if (s === "PENDING") return "PENDING";
|
||||
if (s === "SUCCESS") return "SUCCESS";
|
||||
return "FAILED";
|
||||
}
|
||||
|
||||
function checkRunJobState(c: GHCommitCheckSuiteConclusion | null): CodeReviewCIJobState {
|
||||
if (c === null) return "PENDING";
|
||||
if (c === "SKIPPED") return "SKIPPED";
|
||||
if (c === "SUCCESS") return "SUCCESS";
|
||||
return "FAILED";
|
||||
}
|
||||
|
||||
export function buildMergeabilityState(
|
||||
data: GHPullRequestMergeabilityData,
|
||||
currentUserIsAdmin: boolean,
|
||||
): GHPRMergeabilityState {
|
||||
const rule = data.baseRef?.refUpdateRule ?? null;
|
||||
const canOverrideAsAdmin = rule ? currentUserIsAdmin : false;
|
||||
const requiredContexts = rule ? rule.requiredStatusCheckContexts.filter((c): c is string => c !== null) : [];
|
||||
const isRestricted = rule ? !rule.viewerCanPush : false;
|
||||
const requiredReviews = rule?.requiredApprovingReviewCount ?? 0;
|
||||
|
||||
const hasConflicts = data.mergeable === "MERGEABLE" ? false : data.mergeable === "CONFLICTING" ? true : null;
|
||||
const lastCommit = data.commits.nodes.at(-1)?.commit;
|
||||
const contexts = lastCommit?.status?.contexts ?? [];
|
||||
const ciJobs: CodeReviewCIJob[] = [
|
||||
...contexts.map((c) => ({
|
||||
name: c.context,
|
||||
status: contextJobState(c.state),
|
||||
isRequired: c.isRequired,
|
||||
detailsUrl: c.targetUrl,
|
||||
})),
|
||||
...(lastCommit?.checkSuites?.nodes ?? [])
|
||||
.flatMap((s) => s.checkRuns?.nodes ?? [])
|
||||
.map((r) => ({
|
||||
name: r.name,
|
||||
status: checkRunJobState(r.conclusion),
|
||||
isRequired: r.isRequired,
|
||||
detailsUrl: r.detailsUrl ?? r.url,
|
||||
})),
|
||||
];
|
||||
const status = data.mergeStateStatus;
|
||||
const canBeMerged = CAN_MERGE.has(status) || (ADMIN_CAN_MERGE.has(status) && canOverrideAsAdmin);
|
||||
let checksState: GHPRMergeabilityState["checksState"] = null;
|
||||
if (status === "BEHIND") checksState = "BLOCKING_BEHIND";
|
||||
else if (status === "BLOCKED") {
|
||||
const passed = new Set(contexts.filter((c) => c.state === "SUCCESS").map((c) => c.context));
|
||||
if (requiredContexts.length && !requiredContexts.every((c) => passed.has(c))) checksState = "BLOCKING_FAILING";
|
||||
}
|
||||
const requiredApprovingReviewsCount =
|
||||
status === "BLOCKED" && !isRestricted && checksState !== "BLOCKING_FAILING" ? requiredReviews : 0;
|
||||
return {
|
||||
hasConflicts,
|
||||
ciJobs,
|
||||
canBeMerged,
|
||||
canBeRebased: data.canBeRebased,
|
||||
isRestricted,
|
||||
requiredApprovingReviewsCount,
|
||||
checksState,
|
||||
mergeable: data.mergeable,
|
||||
mergeStateStatus: status,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Permissions (`GHPRSecurityService`)
|
||||
|
||||
const PERMISSION_ORDER: GHRepositoryPermissionLevel[] = ["READ", "TRIAGE", "WRITE", "MAINTAIN", "ADMIN"];
|
||||
|
||||
/** Whether `permission` is at least `level` (an unknown permission has none). */
|
||||
export function hasPermission(
|
||||
permission: GHRepositoryPermissionLevel | null | undefined,
|
||||
level: GHRepositoryPermissionLevel,
|
||||
): boolean {
|
||||
return (permission ? PERMISSION_ORDER.indexOf(permission) : -1) >= PERMISSION_ORDER.indexOf(level);
|
||||
}
|
||||
|
||||
/**
|
||||
* Which pull request actions the user may run (IntelliJ's review flow enablement): managing
|
||||
* (request reviewers, close, reopen, post a draft) needs triage access or authorship; merging
|
||||
* needs write access, a method the repository allows, a mergeable state and an unrestricted
|
||||
* base branch, and `mergeForbidden` (the project setting) off.
|
||||
*/
|
||||
export function pullRequestPermissions(
|
||||
pr: Pick<GHPullRequest, "viewerDidAuthor" | "state">,
|
||||
repo: Pick<GHRepository, "viewerPermission" | "mergeCommitAllowed" | "squashMergeAllowed" | "rebaseMergeAllowed">,
|
||||
mergeability: GHPRMergeabilityState | null,
|
||||
mergeForbidden = false,
|
||||
) {
|
||||
const canManage = hasPermission(repo.viewerPermission, "TRIAGE") || pr.viewerDidAuthor;
|
||||
const canWrite = hasPermission(repo.viewerPermission, "WRITE") && !mergeForbidden;
|
||||
const open = pr.state === "OPEN";
|
||||
const mergeable = open && canWrite && !!mergeability && !mergeability.isRestricted;
|
||||
return {
|
||||
canManage,
|
||||
canMerge: mergeable && repo.mergeCommitAllowed && mergeability!.canBeMerged,
|
||||
canSquashMerge: mergeable && repo.squashMergeAllowed && mergeability!.canBeMerged,
|
||||
canRebaseMerge: mergeable && repo.rebaseMergeAllowed && mergeability!.canBeRebased,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Merge commit messages
|
||||
|
||||
/** The merge dialog's message: subject `Merge pull request #n`, body the title, or `* headline` per commit when squashing. */
|
||||
export function mergeCommitMessage(
|
||||
pr: Pick<GHPullRequest, "number" | "title">,
|
||||
squashCommitHeadlines?: readonly string[],
|
||||
): string {
|
||||
const subject = `Merge pull request #${pr.number}`;
|
||||
const body = squashCommitHeadlines ? `* ${squashCommitHeadlines.join("\n\n* ")}` : pr.title;
|
||||
return `${subject}\n\n${body}`;
|
||||
}
|
||||
|
||||
/** Splits a commit message into its subject (first line) and body (`splitCommitMessage`). */
|
||||
export function splitCommitMessage(message: string): { title: string; body: string } {
|
||||
const i = message.indexOf("\n");
|
||||
if (i < 0) return { title: message.trim(), body: "" };
|
||||
return { title: message.slice(0, i).trim(), body: message.slice(i + 1).trim() };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Repositories
|
||||
|
||||
/** `GHUIUtil.getRepositoryDisplayName`: `name`, or `owner/name` when the owners differ (or always). */
|
||||
export function repositoryDisplayName(
|
||||
all: readonly GHRepositoryCoordinates[],
|
||||
repo: GHRepositoryCoordinates,
|
||||
alwaysShowOwner = false,
|
||||
): string {
|
||||
const showOwner = alwaysShowOwner || (all.length > 1 && all.some((r) => r.owner !== all[0]!.owner));
|
||||
return showOwner ? `${repo.owner}/${repo.name}` : repo.name;
|
||||
}
|
||||
|
||||
/** `owner/name` of a github.com remote URL (https, ssh or scp-like), else null. */
|
||||
export function parseGitHubRemote(url: string): GHRepositoryCoordinates | null {
|
||||
const m =
|
||||
/^(?:https?:\/\/(?:[^@/]+@)?|ssh:\/\/(?:[^@/]+@)?|git:\/\/|(?:[^@/]+@)?)(?:www\.)?github\.com(?::\d+(?=\/))?[:/]+([^/]+)\/([^/]+?)(?:\.git)?\/?$/i.exec(
|
||||
url.trim(),
|
||||
);
|
||||
return m ? { owner: m[1]!, name: m[2]! } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The remote of `repo` among `remotes`, by the URL's path: gh also resolves a remote behind
|
||||
* an SSH host alias (`git@work-github:o/r.git`), which `parseGitHubRemote` can't tell is GitHub.
|
||||
*/
|
||||
export function remoteOfRepository(
|
||||
remotes: ReadonlyArray<{ name: string; url: string }>,
|
||||
repo: GHRepositoryCoordinates,
|
||||
): { name: string; url: string } | null {
|
||||
const path = `${repo.owner}/${repo.name}`.toLowerCase();
|
||||
return (
|
||||
remotes.find((r) => {
|
||||
const url = r.url
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/\/$/, "")
|
||||
.replace(/\.git$/, "");
|
||||
return url.endsWith(`/${path}`) || url.endsWith(`:${path}`);
|
||||
}) ?? null
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
/**
|
||||
* Pull request changes (IntelliJ's `GHPRDetailsDataProvider`, `GHPRReviewDataProvider`,
|
||||
* `GHPRViewedStateDataProvider`, `GHPRCommentsDataProvider` mutations). Each sends the
|
||||
* request, then refreshes what it changed — details, mergeability, timeline, threads,
|
||||
* pending review, the list row — so every view of the pull request follows. Errors
|
||||
* propagate to the caller, which shows them where IntelliJ does.
|
||||
*/
|
||||
import * as api from "../api/requests";
|
||||
import type {
|
||||
GHDiffSide,
|
||||
GHPullRequestDraftReviewThread,
|
||||
GHPullRequestPendingReview,
|
||||
GHPullRequestRequestedReviewer,
|
||||
GHPullRequestReviewEvent,
|
||||
GHPullRequestReviewThread,
|
||||
GHPullRequestShort,
|
||||
GHReactionContent,
|
||||
} from "../api/types";
|
||||
import { reloadList, updateListItem } from "./list";
|
||||
import { isTeam } from "./model";
|
||||
import {
|
||||
loadPullRequestData,
|
||||
pullRequestId,
|
||||
reloadPullRequestData,
|
||||
reloadTimeline,
|
||||
setPullRequestData,
|
||||
updateTimeline,
|
||||
} from "./pullRequest";
|
||||
import { requireConnection } from "./repository";
|
||||
|
||||
const settle = (ps: Array<Promise<unknown>>) => Promise.allSettled(ps).then(() => undefined);
|
||||
|
||||
/** After a change of the pull request itself: details, mergeability and new timeline items. */
|
||||
function refreshState(number: number) {
|
||||
return settle([
|
||||
reloadPullRequestData(number, "details"),
|
||||
reloadPullRequestData(number, "mergeability"),
|
||||
updateTimeline(number),
|
||||
]);
|
||||
}
|
||||
|
||||
/** After a review change: pending review, threads, details (reviews) and the timeline. */
|
||||
function refreshReview(number: number) {
|
||||
return settle([
|
||||
reloadPullRequestData(number, "pendingReview"),
|
||||
reloadPullRequestData(number, "threads"),
|
||||
reloadPullRequestData(number, "details"),
|
||||
reloadTimeline(number),
|
||||
]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Details
|
||||
|
||||
/**
|
||||
* Edits the title and / or description.
|
||||
*/
|
||||
export async function updateDetails(number: number, patch: { title?: string; body?: string }) {
|
||||
const pr = await api.updatePullRequest(await pullRequestId(number), patch);
|
||||
setPullRequestData(number, "details", () => pr);
|
||||
updateListItem(pr);
|
||||
await updateTimeline(number);
|
||||
return pr;
|
||||
}
|
||||
|
||||
/** Adds / removes requested reviewers (users and teams), as the reviewer picker's delta. */
|
||||
export async function adjustReviewers(
|
||||
number: number,
|
||||
delta: { added: GHPullRequestRequestedReviewer[]; removed: GHPullRequestRequestedReviewer[] },
|
||||
) {
|
||||
const split = (rs: GHPullRequestRequestedReviewer[]) => ({
|
||||
logins: rs.filter((r) => !isTeam(r)).map((r) => (r as { login: string }).login),
|
||||
teamSlugs: rs.filter(isTeam).map((t) => t.slug),
|
||||
});
|
||||
if (delta.removed.length) await api.changeRequestedReviewers(number, "DELETE", split(delta.removed));
|
||||
if (delta.added.length) await api.changeRequestedReviewers(number, "POST", split(delta.added));
|
||||
await refreshState(number);
|
||||
}
|
||||
|
||||
/** "Close Pull Request". */
|
||||
export async function closePullRequest(number: number) {
|
||||
await api.updatePullRequestState(number, "closed");
|
||||
await refreshState(number);
|
||||
}
|
||||
|
||||
/** "Reopen Pull Request". */
|
||||
export async function reopenPullRequest(number: number) {
|
||||
await api.updatePullRequestState(number, "open");
|
||||
await refreshState(number);
|
||||
}
|
||||
|
||||
/** "Post Pull Request": marks a draft ready for review. */
|
||||
export async function markReadyForReview(number: number) {
|
||||
await api.markPullRequestReadyForReview(await pullRequestId(number));
|
||||
await refreshState(number);
|
||||
}
|
||||
|
||||
/** Merge… / Squash and Merge… (with the dialog's message) / Rebase, at head `headRefOid`. */
|
||||
export async function mergePullRequest(
|
||||
number: number,
|
||||
method: "merge" | "squash" | "rebase",
|
||||
headRefOid: string,
|
||||
message?: { title: string; body: string },
|
||||
) {
|
||||
await api.mergePullRequest(number, method, headRefOid, method === "rebase" ? undefined : message);
|
||||
await refreshState(number);
|
||||
}
|
||||
|
||||
/** Deletes the merged head branch (the timeline's merged banner). */
|
||||
export async function deleteMergedBranch(number: number, refId: string) {
|
||||
await api.deleteRef(refId);
|
||||
await settle([reloadPullRequestData(number, "details"), updateTimeline(number)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the assignees (logins).
|
||||
* @public
|
||||
*/
|
||||
export async function setAssignees(number: number, logins: string[]) {
|
||||
await api.updateAssignees(number, logins);
|
||||
await settle([reloadPullRequestData(number, "details"), updateTimeline(number)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the labels (names).
|
||||
* @public
|
||||
*/
|
||||
export async function setLabels(number: number, names: string[]) {
|
||||
await api.replaceLabels(number, names);
|
||||
await settle([reloadPullRequestData(number, "details"), updateTimeline(number)]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Viewed state
|
||||
|
||||
/**
|
||||
* Marks `paths` viewed / not viewed: the cache changes at once, one request per path runs
|
||||
* in parallel, and the state is reloaded when any fails.
|
||||
*/
|
||||
export async function setViewed(number: number, paths: readonly string[], viewed: boolean) {
|
||||
setPullRequestData(number, "viewedState", (v) => {
|
||||
const next = { ...v };
|
||||
for (const p of paths) next[p] = viewed ? "VIEWED" : "UNVIEWED";
|
||||
return next;
|
||||
});
|
||||
const id = await pullRequestId(number);
|
||||
const results = await Promise.allSettled(
|
||||
paths.map((p) => (viewed ? api.markFileAsViewed(id, p) : api.unmarkFileAsViewed(id, p))),
|
||||
);
|
||||
const failed = results.find((r): r is PromiseRejectedResult => r.status === "rejected");
|
||||
if (failed) {
|
||||
await reloadPullRequestData(number, "viewedState").catch(() => undefined);
|
||||
throw failed.reason;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Reviews
|
||||
|
||||
/**
|
||||
* `createReview`: a pending review (no `event`), or a submitted one; `threads` are the
|
||||
* new comments ("Start Review" / "Add Single Comment" with `event: "COMMENT"`).
|
||||
*/
|
||||
export async function createReview(
|
||||
number: number,
|
||||
input: {
|
||||
event?: GHPullRequestReviewEvent;
|
||||
body?: string;
|
||||
commitOid?: string;
|
||||
threads?: GHPullRequestDraftReviewThread[];
|
||||
} = {},
|
||||
): Promise<GHPullRequestPendingReview> {
|
||||
const review = await api.createReview({ pullRequestId: await pullRequestId(number), ...input });
|
||||
await refreshReview(number);
|
||||
return review;
|
||||
}
|
||||
|
||||
/** Submits the pending review `reviewId`. */
|
||||
export async function submitReview(number: number, reviewId: string, event: GHPullRequestReviewEvent, body?: string) {
|
||||
await api.submitReview(reviewId, event, body || null);
|
||||
await refreshReview(number);
|
||||
await reloadPullRequestData(number, "mergeability").catch(() => undefined);
|
||||
}
|
||||
|
||||
/** Submit Review popup: submits the pending review, or creates a submitted one. */
|
||||
export async function submitOrCreateReview(number: number, event: GHPullRequestReviewEvent, body: string) {
|
||||
const pending = await loadPullRequestData(number, "pendingReview");
|
||||
if (pending) await submitReview(number, pending.id, event, body);
|
||||
else await createReview(number, { event, body: body || undefined });
|
||||
}
|
||||
|
||||
/** Discards a pending review with its comments. */
|
||||
export async function deleteReview(number: number, reviewId: string) {
|
||||
await api.deleteReview(reviewId);
|
||||
await refreshReview(number);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edits a review's body; resolves with the new body.
|
||||
*/
|
||||
export async function updateReviewBody(number: number, reviewId: string, body: string) {
|
||||
const review = await api.updateReview(reviewId, body);
|
||||
await reloadTimeline(number);
|
||||
return review.body;
|
||||
}
|
||||
|
||||
/** Replaces one thread in the cache (resolve / unresolve / new thread) and refreshes the list counter. */
|
||||
function putThread(number: number, thread: GHPullRequestReviewThread) {
|
||||
setPullRequestData(number, "threads", (ts) => {
|
||||
const list = ts ?? [];
|
||||
return list.some((t) => t.id === thread.id)
|
||||
? list.map((t) => (t.id === thread.id ? thread : t))
|
||||
: [...list, thread];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A new thread in the pending review `reviewId` (lines are 1-based, both ends on one side).
|
||||
* @public
|
||||
*/
|
||||
export async function createThread(
|
||||
number: number,
|
||||
input: {
|
||||
reviewId: string;
|
||||
body: string;
|
||||
path: string;
|
||||
line: number;
|
||||
side: GHDiffSide;
|
||||
startLine?: number;
|
||||
startSide?: GHDiffSide;
|
||||
},
|
||||
) {
|
||||
const thread = await api.addReviewThread({
|
||||
pullRequestReviewId: input.reviewId,
|
||||
body: input.body,
|
||||
path: input.path,
|
||||
line: input.line,
|
||||
side: input.side,
|
||||
startLine: input.startLine ?? null,
|
||||
startSide: input.startSide ?? null,
|
||||
});
|
||||
putThread(number, thread);
|
||||
await settle([reloadPullRequestData(number, "pendingReview"), reloadTimeline(number)]);
|
||||
return thread;
|
||||
}
|
||||
|
||||
/**
|
||||
* A comment on a single commit's diff (`position` in its patch) in the pending review `reviewId`.
|
||||
* @public
|
||||
*/
|
||||
export async function addCommitComment(
|
||||
number: number,
|
||||
input: { reviewId: string; body: string; commitSha: string; path: string; position: number },
|
||||
) {
|
||||
const comment = await api.addReviewComment({
|
||||
reviewId: input.reviewId,
|
||||
body: input.body,
|
||||
commit: input.commitSha,
|
||||
file: input.path,
|
||||
position: input.position,
|
||||
});
|
||||
await refreshReview(number);
|
||||
return comment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replies to the review comment `replyToCommentId` (in the pending review, else a new one).
|
||||
*/
|
||||
export async function replyToComment(number: number, replyToCommentId: string, body: string) {
|
||||
const pending = await loadPullRequestData(number, "pendingReview");
|
||||
const reviewId = pending?.id ?? (await api.createReview({ pullRequestId: await pullRequestId(number) })).id;
|
||||
const comment = await api.addReviewComment({ reviewId, body, inReplyTo: replyToCommentId });
|
||||
// A reply outside a review is posted at once, like GitHub's "Reply".
|
||||
if (!pending) await api.submitReview(reviewId, "COMMENT", null);
|
||||
await refreshReview(number);
|
||||
return comment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Edits a review comment.
|
||||
*/
|
||||
export async function updateReviewComment(number: number, commentId: string, body: string) {
|
||||
const comment = await api.updateReviewComment(commentId, body);
|
||||
await settle([reloadPullRequestData(number, "threads"), reloadTimeline(number)]);
|
||||
return comment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a review comment (its thread goes with its last comment).
|
||||
*/
|
||||
export async function deleteReviewComment(number: number, commentId: string) {
|
||||
await api.deleteReviewComment(commentId);
|
||||
await refreshReview(number);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve: marks a review thread resolved.
|
||||
*/
|
||||
export async function resolveThread(number: number, threadId: string) {
|
||||
const thread = await api.resolveReviewThread(threadId);
|
||||
putThread(number, thread);
|
||||
await settle([reloadPullRequestData(number, "details"), reloadTimeline(number)]);
|
||||
return thread;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unresolve: reopens a review thread.
|
||||
*/
|
||||
export async function unresolveThread(number: number, threadId: string) {
|
||||
const thread = await api.unresolveReviewThread(threadId);
|
||||
putThread(number, thread);
|
||||
await settle([reloadPullRequestData(number, "details"), reloadTimeline(number)]);
|
||||
return thread;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Conversation comments and reactions
|
||||
|
||||
/**
|
||||
* Adds a conversation comment (the timeline's composer).
|
||||
*/
|
||||
export async function addIssueComment(number: number, body: string) {
|
||||
await api.createIssueComment(number, body);
|
||||
await updateTimeline(number);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edits a conversation comment.
|
||||
*/
|
||||
export async function updateIssueComment(number: number, commentId: string, body: string) {
|
||||
const comment = await api.updateIssueComment(commentId, body);
|
||||
await reloadTimeline(number);
|
||||
return comment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a conversation comment.
|
||||
*/
|
||||
export async function deleteIssueComment(number: number, commentId: string) {
|
||||
await api.deleteIssueComment(commentId);
|
||||
await reloadTimeline(number);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds or removes the viewer's reaction on `subjectId` (the description, a comment, a
|
||||
* review comment); `on` says which data holds the subject, to refresh it.
|
||||
*/
|
||||
export async function toggleReaction(
|
||||
number: number,
|
||||
subjectId: string,
|
||||
reaction: GHReactionContent,
|
||||
add: boolean,
|
||||
on: "details" | "timeline" | "threads",
|
||||
) {
|
||||
if (add) await api.addReaction(subjectId, reaction);
|
||||
else await api.removeReaction(subjectId, reaction);
|
||||
if (on === "timeline") await reloadTimeline(number);
|
||||
else await reloadPullRequestData(number, on);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// New pull requests
|
||||
|
||||
/**
|
||||
* Creates a pull request in the connected repository (`GHPRCreationService`): `head` is
|
||||
* the branch (`owner:branch` for a fork's). A blank title falls back to the branch name,
|
||||
* a blank body is sent as null. Reviewers, assignees and labels are set afterwards
|
||||
* (`onSettingMetadata` is called first: "Updating pull request fields").
|
||||
*/
|
||||
export async function createPullRequest(input: {
|
||||
base: string;
|
||||
head: string;
|
||||
title: string;
|
||||
body: string;
|
||||
draft: boolean;
|
||||
reviewers?: GHPullRequestRequestedReviewer[];
|
||||
assignees?: string[];
|
||||
labels?: string[];
|
||||
onSettingMetadata?: () => void;
|
||||
}): Promise<GHPullRequestShort> {
|
||||
const { repository } = requireConnection();
|
||||
const branch = input.head.slice(input.head.indexOf(":") + 1);
|
||||
const pr = await api.createPullRequest({
|
||||
repositoryId: repository.id,
|
||||
baseRefName: input.base,
|
||||
headRefName: input.head,
|
||||
title: input.title.trim() || branch,
|
||||
body: input.body.trim() ? input.body : null,
|
||||
draft: input.draft,
|
||||
});
|
||||
const n = pr.number;
|
||||
if (input.reviewers?.length || input.assignees?.length || input.labels?.length) input.onSettingMetadata?.();
|
||||
await settle([
|
||||
...(input.reviewers?.length ? [adjustReviewers(n, { added: input.reviewers, removed: [] })] : []),
|
||||
...(input.assignees?.length ? [api.updateAssignees(n, input.assignees)] : []),
|
||||
...(input.labels?.length ? [api.replaceLabels(n, input.labels)] : []),
|
||||
]);
|
||||
void reloadList();
|
||||
return pr;
|
||||
}
|
||||
Loaded 100 of 303 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача