дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-19 16:15:42 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
cdc228daf0 |
No files matched your search
@@ -14,7 +14,7 @@ pub use deploy::{
|
||||
Deployment, DeploymentCoverage, SyncAction, SyncEntry, SyncStatus, SyncStep, TransferReport, coverage,
|
||||
};
|
||||
pub use mapping::{Excludes, Mappings, ResolvedMapping};
|
||||
pub use service::{DeployedPath, DeploymentRoot, RemoteService};
|
||||
pub use service::{DeployedPath, DeploymentRoot, RemoteService, default_targets};
|
||||
pub use target::{RemoteRuns, RemoteStart};
|
||||
|
||||
pub mod plugin_target;
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Deployment over SFTP, FTP or local folders, and SSH run targets.
|
||||
//! Shared by IPC commands and project save/delete hooks.
|
||||
|
||||
use crate::deploy::{Deployment, FileStamp, SyncEntry, SyncStatus, SyncStep, TransferReport, status};
|
||||
use crate::deploy::{Deployment, FileStamp, SyncEntry, SyncStatus, SyncStep, TransferError, TransferReport, status};
|
||||
use crate::mapping::{Excludes, Mappings, ResolvedMapping, posix};
|
||||
use crate::target::{RemoteRuns, RemoteStart, SyncFn, rewrite_external_classpath};
|
||||
use ide_core::remote_settings::{AutoUpload, DeploymentServer, DeploymentType, RunTarget};
|
||||
@@ -65,6 +65,39 @@ pub fn server(settings: &Settings, id: Option<&str>) -> IdeResult<DeploymentServ
|
||||
.ok_or_else(|| IdeError::not_found(format!("no deployment server {id}")))
|
||||
}
|
||||
|
||||
/// The servers automatic upload goes to: the default server, or each server of the default group.
|
||||
pub fn default_targets(settings: &Settings) -> Vec<String> {
|
||||
let d = &settings.deployment;
|
||||
match d.groups.iter().find(|g| g.id == d.default_server) {
|
||||
Some(group) => group.servers.iter().filter(|id| d.servers.iter().any(|s| &s.id == *id)).cloned().collect(),
|
||||
None if d.default_server.is_empty() => Vec::new(),
|
||||
None => vec![d.default_server.clone()],
|
||||
}
|
||||
}
|
||||
|
||||
/// One report for transfers to several servers, failures named after their server.
|
||||
fn merge_reports(reports: Vec<(String, IdeResult<TransferReport>)>) -> IdeResult<TransferReport> {
|
||||
if let [(_, _)] = reports.as_slice() {
|
||||
return reports.into_iter().next().map(|(_, r)| r).unwrap_or_else(|| Ok(TransferReport::default()));
|
||||
}
|
||||
let mut out = TransferReport::default();
|
||||
for (server, report) in reports {
|
||||
match report {
|
||||
Ok(r) => {
|
||||
out.files += r.files;
|
||||
out.skipped += r.skipped;
|
||||
out.errors.extend(
|
||||
r.errors.into_iter().map(|e| TransferError { message: format!("{server}: {}", e.message), ..e }),
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
out.errors.push(TransferError { path: String::new(), message: format!("{server}: {}", e.message) })
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn run_target(settings: &Settings, id: &str) -> IdeResult<RunTarget> {
|
||||
settings
|
||||
.run_targets
|
||||
@@ -391,15 +424,17 @@ impl RemoteService {
|
||||
.await;
|
||||
return Some(r);
|
||||
}
|
||||
if settings.deployment.auto_upload == AutoUpload::Never
|
||||
|| settings.deployment.default_server.is_empty()
|
||||
|| !path.starts_with(root)
|
||||
{
|
||||
let targets = default_targets(settings);
|
||||
if settings.deployment.auto_upload == AutoUpload::Never || targets.is_empty() || !path.starts_with(root) {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
self.upload(settings, root, None, &[path.to_path_buf()], CancellationToken::new(), &mut |_, _, _| {}).await,
|
||||
)
|
||||
let mut reports = Vec::new();
|
||||
for id in targets {
|
||||
let paths = [path.to_path_buf()];
|
||||
let r = self.upload(settings, root, Some(&id), &paths, CancellationToken::new(), &mut |_, _, _| {}).await;
|
||||
reports.push((id, r));
|
||||
}
|
||||
Some(merge_reports(reports))
|
||||
}
|
||||
|
||||
/// After files were deleted locally: their remote copies too (automatic upload + Delete remote files).
|
||||
@@ -410,10 +445,16 @@ impl RemoteService {
|
||||
paths: &[PathBuf],
|
||||
) -> Option<IdeResult<TransferReport>> {
|
||||
let d = &settings.deployment;
|
||||
if d.auto_upload == AutoUpload::Never || !d.delete_remote || d.default_server.is_empty() {
|
||||
let targets = default_targets(settings);
|
||||
if d.auto_upload == AutoUpload::Never || !d.delete_remote || targets.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(self.delete_remote(settings, root, None, paths).await)
|
||||
let mut reports = Vec::new();
|
||||
for id in targets {
|
||||
let r = self.delete_remote(settings, root, Some(&id), paths).await;
|
||||
reports.push((id, r));
|
||||
}
|
||||
Some(merge_reports(reports))
|
||||
}
|
||||
|
||||
// --- run targets ---------------------------------------------------------------
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Local deployment uses the service entry points used by SFTP and save hooks.
|
||||
use ide_core::CancellationToken;
|
||||
use ide_core::remote_settings::{AutoUpload, DeploymentMapping, DeploymentServer, DeploymentType};
|
||||
use ide_core::remote_settings::{AutoUpload, DeploymentGroup, DeploymentMapping, DeploymentServer, DeploymentType};
|
||||
use ide_core::settings::Settings;
|
||||
use ide_remote::{RemoteService, SyncAction, SyncStatus, SyncStep};
|
||||
use ide_ssh::{FsConnection, SshFiles, SshManager};
|
||||
@@ -410,3 +410,40 @@ async fn download_into_copies_only_the_selected_items() {
|
||||
.unwrap();
|
||||
assert_eq!((report.files, report.errors.len()), (0, 1), "{report:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn automatic_upload_to_a_default_group_reaches_each_of_its_servers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
let (staging, live) = (tmp.path().join("staging"), tmp.path().join("live"));
|
||||
for dir in [root.join("src"), staging.clone(), live.clone()] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
std::fs::write(root.join("src/a.txt"), "v1").unwrap();
|
||||
let mut settings = settings(&staging);
|
||||
settings.deployment.servers.push(DeploymentServer {
|
||||
id: "live".into(),
|
||||
kind: DeploymentType::Local,
|
||||
root_path: live.to_string_lossy().into_owned(),
|
||||
mappings: vec![DeploymentMapping { deployment: "app".into(), ..Default::default() }],
|
||||
..Default::default()
|
||||
});
|
||||
settings.deployment.groups.push(DeploymentGroup {
|
||||
id: "all".into(),
|
||||
name: "All".into(),
|
||||
servers: vec!["local".into(), "live".into(), "gone".into()],
|
||||
});
|
||||
settings.deployment.default_server = "all".into();
|
||||
assert_eq!(ide_remote::default_targets(&settings), ["local", "live"]);
|
||||
|
||||
let service = service(tmp.path());
|
||||
let saved = service.on_saved(&settings, &root, &root.join("src/a.txt")).await.unwrap().unwrap();
|
||||
assert_eq!((saved.files, saved.errors.len()), (2, 0), "{saved:?}");
|
||||
for target in [&staging, &live] {
|
||||
assert_eq!(std::fs::read_to_string(target.join("app/src/a.txt")).unwrap(), "v1");
|
||||
}
|
||||
std::fs::remove_file(root.join("src/a.txt")).unwrap();
|
||||
let deleted = service.on_deleted(&settings, &root, &[root.join("src/a.txt")]).await.unwrap().unwrap();
|
||||
assert!(deleted.errors.is_empty(), "{deleted:?}");
|
||||
assert!(!staging.join("app/src/a.txt").exists() && !live.join("app/src/a.txt").exists());
|
||||
}
|
||||
@@ -6,6 +6,7 @@ const mocks = vi.hoisted(() => ({
|
||||
actions: [] as { id: string; run: (context: { arg: string[] }) => unknown }[],
|
||||
servers: [] as DeploymentServerValid[],
|
||||
groups: [] as { id: string; name: string; servers: string[] }[],
|
||||
defaultServer: "one",
|
||||
coverage: [] as { server: string; paths: string[]; skipped: { path: string; message: string }[] }[],
|
||||
choose: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
@@ -38,7 +39,9 @@ vi.mock("@/platform/project", () => ({
|
||||
useProject: { getState: () => ({ project: { root: "/project" } }) },
|
||||
}));
|
||||
vi.mock("@/platform/workflowSettings", () => ({
|
||||
workflowSettings: () => ({ deployment: { servers: mocks.servers, groups: mocks.groups, defaultServer: "one" } }),
|
||||
workflowSettings: () => ({
|
||||
deployment: { servers: mocks.servers, groups: mocks.groups, defaultServer: mocks.defaultServer },
|
||||
}),
|
||||
}));
|
||||
vi.mock("@/workbench/contributions", () => ({
|
||||
notifications: () => ({ notify: mocks.notify }),
|
||||
@@ -74,6 +77,7 @@ beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.servers = ["one", "two"].map((id) => ({ id, name: id, kind: "local" }) as DeploymentServerValid);
|
||||
mocks.groups = [];
|
||||
mocks.defaultServer = "one";
|
||||
mocks.coverage = [
|
||||
{
|
||||
server: "one",
|
||||
@@ -112,6 +116,15 @@ describe("server groups", () => {
|
||||
expect(mocks.upload).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({ title: "Cannot upload to one" }));
|
||||
});
|
||||
it("uploads to each server of the default group without asking", async () => {
|
||||
mocks.groups = [{ id: "g", name: "Production", servers: ["two", "one"] }];
|
||||
mocks.defaultServer = "g";
|
||||
mocks.coverage[1]!.paths = ["/project/a"];
|
||||
mocks.actions.find((action) => action.id === "deployment.uploadToDefault")!.run({ arg: ["/project/a"] });
|
||||
await vi.waitFor(() => expect(mocks.upload).toHaveBeenCalledTimes(2));
|
||||
expect(mocks.upload.mock.calls.map((c) => c[1])).toEqual(["two", "one"]);
|
||||
expect(mocks.choose).not.toHaveBeenCalled();
|
||||
});
|
||||
it("uploads to every covered server of the group in order", async () => {
|
||||
mocks.groups = [{ id: "g", name: "Production", servers: ["two", "one"] }];
|
||||
mocks.coverage[1]!.paths = ["/project/b"];
|
||||
|
||||
@@ -25,7 +25,7 @@ import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { notifications, projectViewSelection, toolWindowService } from "@/workbench/contributions";
|
||||
import { chooseItem } from "@/workbench/inputDialogs";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import { initialSyncChoices, resolveServer, serverLabel, summarizeReport, targetPaths } from "./model";
|
||||
import { defaultGroup, initialSyncChoices, resolveServer, serverLabel, summarizeReport, targetPaths } from "./model";
|
||||
import { withSsh } from "./ssh";
|
||||
import { REMOTE_HOST_WINDOW, patchSync, useDeployment } from "./store";
|
||||
import styles from "./Deployment.module.css";
|
||||
@@ -468,7 +468,15 @@ export function registerDeploymentActions(): () => void {
|
||||
icon: "export",
|
||||
when,
|
||||
keywords: ["deploy", "sftp", "upload", "remote"],
|
||||
run: withTargets(async (paths) => transfer("upload", await defaultServer("Upload to", paths), paths)),
|
||||
run: withTargets(async (paths) => {
|
||||
// The default server group: each of its servers in turn, as Upload to… on the group does.
|
||||
const group = defaultGroup(deployment());
|
||||
if (group) {
|
||||
for (const server of group.servers) await transfer("upload", server, paths);
|
||||
return;
|
||||
}
|
||||
await transfer("upload", await defaultServer("Upload to", paths), paths);
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: "deployment.uploadTo",
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
sshRemedy,
|
||||
summarizeReport,
|
||||
transferMenuEntries,
|
||||
defaultGroup,
|
||||
syncChoices,
|
||||
syncSteps,
|
||||
targetPaths,
|
||||
@@ -111,6 +112,18 @@ describe("servers and reports", () => {
|
||||
expect(actions([a], "")).toEqual(named);
|
||||
expect(actions([a, b], "a")).toEqual([...named, ...choosers]);
|
||||
expect(actions([a, b], "")).toEqual(choosers);
|
||||
// A default server group uploads to its servers; the rest choose one server.
|
||||
const groups = [{ id: "g", name: "All stages", servers: [b.id, a.id] }];
|
||||
expect(
|
||||
transferMenuEntries({ ...DEFAULT_DEPLOYMENT, servers: [a, b], groups, defaultServer: "g" }).map(
|
||||
(e) => e.label ?? e.action,
|
||||
),
|
||||
).toEqual(["Upload to All stages", ...choosers]);
|
||||
expect(defaultGroup({ ...DEFAULT_DEPLOYMENT, servers: [a, b], groups, defaultServer: "g" })?.servers).toEqual([
|
||||
b,
|
||||
a,
|
||||
]);
|
||||
expect(defaultGroup({ ...DEFAULT_DEPLOYMENT, servers: [a, b], groups, defaultServer: "a" })).toBeNull();
|
||||
});
|
||||
|
||||
it("summarizes transfer reports", () => {
|
||||
|
||||
@@ -88,8 +88,27 @@ export function resolveServer(settings: DeploymentSettingsValid, id: string | nu
|
||||
|
||||
export const serverLabel = (s: Pick<DeploymentServerValid, "id" | "name">) => s.name.trim() || s.id;
|
||||
|
||||
/** The default target when it is a server group: its name and servers, in upload order. */
|
||||
export function defaultGroup(
|
||||
settings: DeploymentSettingsValid,
|
||||
): { name: string; servers: DeploymentServerValid[] } | null {
|
||||
const group = settings.groups.find((g) => g.id === settings.defaultServer);
|
||||
if (!group) return null;
|
||||
const servers = group.servers.flatMap((id) => settings.servers.find((s) => s.id === id) ?? []);
|
||||
return { name: group.name.trim() || group.id, servers };
|
||||
}
|
||||
|
||||
/** Transfer entries of the Deployment menu: named after the default server, choosers when there are several. */
|
||||
export function transferMenuEntries(settings: DeploymentSettingsValid): { action: string; label?: string }[] {
|
||||
// A default group uploads to each of its servers; downloads and syncs pick one server.
|
||||
const group = defaultGroup(settings);
|
||||
if (group)
|
||||
return [
|
||||
{ action: "deployment.uploadToDefault", label: tx`Upload to ${group.name}` },
|
||||
{ action: "deployment.uploadTo" },
|
||||
{ action: "deployment.downloadFrom" },
|
||||
{ action: "deployment.syncWith" },
|
||||
];
|
||||
const target = resolveServer(settings, null);
|
||||
const name = target && serverLabel(target);
|
||||
const named = target
|
||||
|
||||
@@ -744,18 +744,24 @@ function DeploymentServersEditor() {
|
||||
const [tab, setTab] = useState<ServerTab>("connection");
|
||||
const current = selected?.kind === "server" ? (list.find((s) => s.id === selected.id) ?? null) : null;
|
||||
const currentGroup = selected?.kind === "group" ? (groupList.find((g) => g.id === selected.id) ?? null) : null;
|
||||
const effectiveDefault = fixDefaultServer(list, defaultServer ?? "");
|
||||
const effectiveDefault = fixDefaultServer(list, defaultServer ?? "", groupList);
|
||||
|
||||
const commit = (next: DeploymentServerValid[]) => {
|
||||
setServers(next);
|
||||
const d = fixDefaultServer(next, defaultServer ?? "");
|
||||
if (d !== (defaultServer ?? "")) setDefaultServer(d);
|
||||
const pruned = pruneGroups(groupList, next);
|
||||
const d = fixDefaultServer(next, defaultServer ?? "", pruned);
|
||||
if (d !== (defaultServer ?? "")) setDefaultServer(d);
|
||||
if (pruned.some((g, i) => g !== groupList[i])) setGroups(pruned);
|
||||
};
|
||||
const update = (patch: Partial<DeploymentServerValid>) => {
|
||||
if (current) commit(list.map((s) => (s.id === current.id ? { ...s, ...patch } : s)));
|
||||
};
|
||||
/** Removing the default group makes the first server the default again. */
|
||||
const removeGroups = (rest: DeploymentGroupValid[]) => {
|
||||
setGroups(rest);
|
||||
const d = fixDefaultServer(list, defaultServer ?? "", rest);
|
||||
if (d !== (defaultServer ?? "")) setDefaultServer(d);
|
||||
};
|
||||
const updateGroup = (patch: Partial<DeploymentGroupValid>) => {
|
||||
if (currentGroup) setGroups(groupList.map((g) => (g.id === currentGroup.id ? { ...g, ...patch } : g)));
|
||||
};
|
||||
@@ -777,7 +783,7 @@ function DeploymentServersEditor() {
|
||||
if (!group) return;
|
||||
const index = groupList.indexOf(group);
|
||||
const rest = groupList.filter((g) => g.id !== group.id);
|
||||
setGroups(rest);
|
||||
removeGroups(rest);
|
||||
const next = rest[Math.min(index, rest.length - 1)] ?? null;
|
||||
setSelected(next ? { kind: "group", id: next.id } : list[0] ? { kind: "server", id: list[0].id } : null);
|
||||
return;
|
||||
@@ -794,7 +800,7 @@ function DeploymentServersEditor() {
|
||||
if (currentGroup) {
|
||||
const index = groupList.indexOf(currentGroup);
|
||||
const rest = groupList.filter((g) => g.id !== currentGroup.id);
|
||||
setGroups(rest);
|
||||
removeGroups(rest);
|
||||
const next = rest[Math.min(index, rest.length - 1)] ?? null;
|
||||
setSelected(next ? { kind: "group", id: next.id } : list[0] ? { kind: "server", id: list[0].id } : null);
|
||||
return;
|
||||
@@ -817,19 +823,18 @@ function DeploymentServersEditor() {
|
||||
e.stopPropagation();
|
||||
setSelected(target);
|
||||
const server = target?.kind === "server" ? list.find((s) => s.id === target.id) : undefined;
|
||||
const defaultItem = (id: string): MenuItem => ({
|
||||
label: "Use as Default",
|
||||
icon: "check",
|
||||
disabled: id === effectiveDefault,
|
||||
run: () => setDefaultServer(id),
|
||||
});
|
||||
showContextMenu(e, [
|
||||
{ label: "Add", icon: "plus", submenu: addItems },
|
||||
...(server
|
||||
? [
|
||||
{ label: "Duplicate", icon: "copy", run: () => add(server) } as MenuItem,
|
||||
{
|
||||
label: "Use as Default",
|
||||
icon: "check",
|
||||
disabled: server.id === effectiveDefault,
|
||||
run: () => setDefaultServer(server.id),
|
||||
} as MenuItem,
|
||||
]
|
||||
? [{ label: "Duplicate", icon: "copy", run: () => add(server) } as MenuItem, defaultItem(server.id)]
|
||||
: []),
|
||||
...(target?.kind === "group" ? [defaultItem(target.id)] : []),
|
||||
{ kind: "separator" },
|
||||
// `remove` acts on the selection, which the state update above has not applied yet.
|
||||
{ label: "Remove", icon: "minus", run: () => removeTarget(target) },
|
||||
@@ -861,8 +866,11 @@ function DeploymentServersEditor() {
|
||||
icon="check"
|
||||
title="Use as Default"
|
||||
size="small"
|
||||
disabled={!current || current.id === effectiveDefault}
|
||||
onClick={() => current && setDefaultServer(current.id)}
|
||||
disabled={(current ?? currentGroup)?.id === effectiveDefault || (!current && !currentGroup)}
|
||||
onClick={() => {
|
||||
const id = (current ?? currentGroup)?.id;
|
||||
if (id) setDefaultServer(id);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
@@ -889,8 +897,11 @@ function DeploymentServersEditor() {
|
||||
onContextMenu={(e) => rowMenu(e, { kind: "group", id: g.id })}
|
||||
>
|
||||
<Icon name="folder" />
|
||||
<span className={styles.serverName}>{g.name || g.id}</span>
|
||||
<span className={clsx(styles.serverName, g.id === effectiveDefault && styles.default)}>
|
||||
{g.name || g.id}
|
||||
</span>
|
||||
<Badge>{g.servers.length}</Badge>
|
||||
{g.id === effectiveDefault && <Badge tone="accent">{tx("default")}</Badge>}
|
||||
</div>
|
||||
))}
|
||||
{list.map((s) => (
|
||||
|
||||
@@ -100,8 +100,13 @@ export function pruneGroups(
|
||||
}
|
||||
|
||||
/** The default server after `servers` changed: kept when still present, else the first one (or none). */
|
||||
export function fixDefaultServer(servers: readonly DeploymentServerValid[], defaultServer: string): string {
|
||||
if (servers.some((s) => s.id === defaultServer)) return defaultServer;
|
||||
/** The default target kept valid: an existing server or server group, else the first server. */
|
||||
export function fixDefaultServer(
|
||||
servers: readonly DeploymentServerValid[],
|
||||
defaultServer: string,
|
||||
groups: readonly { id: string }[] = [],
|
||||
): string {
|
||||
if (servers.some((s) => s.id === defaultServer) || groups.some((g) => g.id === defaultServer)) return defaultServer;
|
||||
return servers[0]?.id ?? "";
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Заблокувати користувача