railwayapp 4.61.1

Interact with Railway via CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use std::path::PathBuf;

use anyhow::bail;
use clap::Parser;
use colored::Colorize;
use is_terminal::IsTerminal;

use crate::{
    commands::volume::sftp::{self, VolumeSftp},
    controllers::volume_browser::{self, VolumeBrowserParams},
    telemetry,
    util::prompt::prompt_confirm_with_default,
};

use super::super::Result;

#[derive(Clone)]
pub(crate) struct FileTarget {
    pub(crate) service_instance_id: String,
    pub(crate) mount_path: String,
    pub(crate) label: FileTargetLabel,
}

#[derive(Clone)]
pub(crate) enum FileTargetLabel {
    Volume {
        id: String,
        name: String,
        mount_path: String,
    },
    Service {
        id: String,
        name: String,
    },
}

#[derive(Parser)]
pub(crate) enum Commands {
    /// Download a file or directory
    Download(DownloadArgs),

    /// Upload a file or directory
    Upload(UploadArgs),

    /// List files in a directory
    #[clap(visible_alias = "ls")]
    List(ListArgs),

    /// Browse files interactively
    #[clap(visible_alias = "browser")]
    Browse(BrowseArgs),

    /// Delete a file
    #[clap(visible_alias = "rm", visible_alias = "remove")]
    Delete(DeleteArgs),

    /// Rename a file
    #[clap(visible_alias = "mv")]
    Rename(RenameArgs),
}

#[derive(Parser)]
pub(crate) struct DownloadArgs {
    /// The path on the remote server to download from
    #[clap(value_name = "REMOTE_PATH")]
    pub(crate) remote_path: String,

    /// The path to save the download
    #[clap(value_name = "LOCAL_PATH", default_value = ".")]
    pub(crate) local_path: PathBuf,

    /// Output in JSON format
    #[clap(long)]
    pub(crate) json: bool,

    /// Replace LOCAL_PATH if it already exists
    #[clap(long, visible_alias = "override")]
    pub(crate) overwrite: bool,

    /// Concurrent file downloads when REMOTE_PATH is a directory
    #[clap(long, value_name = "N", default_value_t = sftp::DEFAULT_TRANSFER_CONCURRENCY)]
    pub(crate) concurrency: usize,
}

#[derive(Parser)]
pub(crate) struct UploadArgs {
    /// The local file or directory to upload
    #[clap(value_name = "LOCAL_PATH")]
    pub(crate) local_path: PathBuf,

    /// The path on the remote server to upload to
    #[clap(value_name = "REMOTE_PATH")]
    pub(crate) remote_path: String,

    /// Output in JSON format
    #[clap(long)]
    pub(crate) json: bool,

    /// Replace REMOTE_PATH if it already exists
    #[clap(long)]
    pub(crate) overwrite: bool,

    /// Concurrent file uploads when LOCAL_PATH is a directory
    #[clap(long, value_name = "N", default_value_t = sftp::DEFAULT_TRANSFER_CONCURRENCY)]
    pub(crate) concurrency: usize,
}

#[derive(Parser)]
pub(crate) struct ListArgs {
    /// The directory path on the remote server to list
    #[clap(value_name = "REMOTE_PATH", default_value = "/")]
    pub(crate) remote_path: String,

    /// Output in JSON format
    #[clap(long)]
    pub(crate) json: bool,
}

#[derive(Parser)]
pub(crate) struct BrowseArgs {
    /// The directory path on the remote server to open
    #[clap(value_name = "REMOTE_PATH", default_value = "/")]
    pub(crate) remote_path: String,

    /// Editor command to use when editing files
    #[clap(long, value_name = "COMMAND")]
    pub(crate) editor: Option<String>,

    /// Concurrent file downloads
    #[clap(long, value_name = "N", default_value_t = sftp::DEFAULT_TRANSFER_CONCURRENCY)]
    pub(crate) concurrency: usize,
}

#[derive(Parser)]
pub(crate) struct DeleteArgs {
    /// The path on the remote server to delete
    #[clap(value_name = "REMOTE_PATH")]
    pub(crate) remote_path: String,

    /// Output in JSON format
    #[clap(long)]
    pub(crate) json: bool,

    /// Skip confirmation dialog
    #[clap(short = 'y', long = "yes")]
    pub(crate) yes: bool,
}

#[derive(Parser)]
pub(crate) struct RenameArgs {
    /// The current path on the remote server
    #[clap(value_name = "OLD_REMOTE_PATH")]
    pub(crate) old_remote_path: String,

    /// The new path on the remote server
    #[clap(value_name = "NEW_REMOTE_PATH")]
    pub(crate) new_remote_path: String,

    /// Output in JSON format
    #[clap(long)]
    pub(crate) json: bool,
}

pub(crate) async fn command_from_parts(target: FileTarget, command: Commands) -> Result<()> {
    match command {
        Commands::Download(args) => download(target, args).await,
        Commands::Upload(args) => upload(target, args).await,
        Commands::List(args) => list(target, args).await,
        Commands::Browse(args) => browse(target, args).await,
        Commands::Delete(args) => delete(target, args).await,
        Commands::Rename(args) => rename(target, args).await,
    }
}

pub(crate) async fn download(target: FileTarget, args: DownloadArgs) -> Result<()> {
    let mut sftp = sftp_for(&target, args.concurrency);
    let downloaded_path = sftp
        .download(&args.remote_path, &args.local_path, args.overwrite)
        .await?;

    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&target_json(
                &target,
                serde_json::json!({
                    "remotePath": args.remote_path,
                    "localPath": downloaded_path,
                    "overwritten": args.overwrite,
                }),
            ))?
        );
    } else {
        println!(
            "Downloaded {} to {}",
            args.remote_path.cyan(),
            downloaded_path.display().to_string().green()
        );
    }

    Ok(())
}

pub(crate) async fn upload(target: FileTarget, args: UploadArgs) -> Result<()> {
    let mut sftp = sftp_for(&target, args.concurrency);
    let uploaded_path = sftp
        .upload(&args.local_path, &args.remote_path, args.overwrite)
        .await?;

    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&target_json(
                &target,
                serde_json::json!({
                    "localPath": args.local_path,
                    "remotePath": uploaded_path,
                    "overwritten": args.overwrite,
                }),
            ))?
        );
    } else {
        println!(
            "Uploaded {} to {}",
            args.local_path.display().to_string().cyan(),
            uploaded_path.green()
        );
    }

    Ok(())
}

pub(crate) async fn list(target: FileTarget, args: ListArgs) -> Result<()> {
    let mut sftp = sftp_for(&target, sftp::DEFAULT_TRANSFER_CONCURRENCY);
    let file_tree = sftp.list_files(&args.remote_path).await?;

    if args.json {
        let files: Vec<serde_json::Value> = file_tree
            .entries()
            .iter()
            .map(|entry| {
                serde_json::json!({
                    "name": entry.name,
                    "path": entry.path,
                    "type": entry.kind,
                    "size": entry.size,
                })
            })
            .collect();
        println!(
            "{}",
            serde_json::to_string_pretty(&target_json(
                &target,
                serde_json::json!({
                    "remotePath": args.remote_path,
                    "files": files,
                }),
            ))?
        );
    } else {
        print!("{file_tree}");
    }

    Ok(())
}

pub(crate) async fn browse(target: FileTarget, args: BrowseArgs) -> Result<()> {
    if !std::io::stdout().is_terminal() {
        bail!("The browse command requires an interactive terminal");
    }

    volume_browser::run(VolumeBrowserParams {
        service_instance_id: target.service_instance_id.clone(),
        target_name: target.name(),
        mount_path: target.mount_path.clone(),
        remote_path: args.remote_path,
        transfer_concurrency: args.concurrency,
        editor: args.editor,
    })
    .await
}

pub(crate) async fn delete(target: FileTarget, args: DeleteArgs) -> Result<()> {
    if telemetry::is_agent() {
        bail!("{}", agent_file_delete_refusal(&target, &args.remote_path));
    }

    let is_terminal = std::io::stdout().is_terminal();
    let confirm = if args.yes {
        true
    } else if is_terminal {
        prompt_confirm_with_default(
            format!(r#"Are you sure you want to delete "{}"?"#, args.remote_path).as_str(),
            false,
        )?
    } else {
        bail!(
            "Cannot prompt for confirmation in non-interactive mode. Use --yes to skip confirmation."
        );
    };

    if !confirm {
        return Ok(());
    }

    let mut sftp = sftp_for(&target, sftp::DEFAULT_TRANSFER_CONCURRENCY);
    sftp.delete(&args.remote_path).await?;

    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&target_json(
                &target,
                serde_json::json!({
                    "remotePath": args.remote_path,
                    "deleted": true,
                }),
            ))?
        );
    } else {
        println!("Deleted {}", args.remote_path.cyan());
    }

    Ok(())
}

pub(crate) async fn rename(target: FileTarget, args: RenameArgs) -> Result<()> {
    let mut sftp = sftp_for(&target, sftp::DEFAULT_TRANSFER_CONCURRENCY);
    sftp.rename(&args.old_remote_path, &args.new_remote_path)
        .await?;

    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&target_json(
                &target,
                serde_json::json!({
                    "oldRemotePath": args.old_remote_path,
                    "newRemotePath": args.new_remote_path,
                    "renamed": true,
                }),
            ))?
        );
    } else {
        println!(
            "Renamed {} to {}",
            args.old_remote_path.cyan(),
            args.new_remote_path.green()
        );
    }

    Ok(())
}

fn sftp_for(target: &FileTarget, concurrency: usize) -> VolumeSftp {
    let mut sftp = VolumeSftp::new(
        target.service_instance_id.clone(),
        target.mount_path.clone(),
    );
    sftp.set_transfer_concurrency(concurrency);
    sftp
}

fn target_json(target: &FileTarget, details: serde_json::Value) -> serde_json::Value {
    let mut output = match &target.label {
        FileTargetLabel::Volume {
            id,
            name,
            mount_path,
        } => serde_json::json!({
            "volume": {
                "id": id,
                "name": name,
                "mountPath": mount_path,
            },
            "serviceInstanceId": target.service_instance_id,
        }),
        FileTargetLabel::Service { id, name } => serde_json::json!({
            "service": {
                "id": id,
                "name": name,
            },
            "serviceInstanceId": target.service_instance_id,
        }),
    };

    if let (Some(output), Some(details)) = (output.as_object_mut(), details.as_object()) {
        for (key, value) in details {
            output.insert(key.clone(), value.clone());
        }
    }

    output
}

fn agent_file_delete_refusal(target: &FileTarget, remote_path: &str) -> String {
    let command = human_delete_file_command(target, remote_path);
    format!("Refusing: agents cannot delete files. Ask a human to run:\n\n  {command}")
}

fn human_delete_file_command(target: &FileTarget, remote_path: &str) -> String {
    let mut command = match &target.label {
        FileTargetLabel::Volume { name, .. } => {
            format!("railway volume files delete --volume {}", shell_quote(name))
        }
        FileTargetLabel::Service { name, .. } => {
            format!(
                "railway service files delete --service {}",
                shell_quote(name)
            )
        }
    };
    command.push(' ');
    command.push_str(&shell_quote(remote_path));
    command
}

fn shell_quote(value: &str) -> String {
    if value
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '_' | '-' | ':'))
    {
        value.to_string()
    } else {
        format!("'{}'", value.replace('\'', "'\\''"))
    }
}

impl FileTarget {
    pub(crate) fn name(&self) -> String {
        match &self.label {
            FileTargetLabel::Volume { name, .. } | FileTargetLabel::Service { name, .. } => {
                name.clone()
            }
        }
    }
}