sharepoint_cli/commands/
init.rs1use std::io::{BufRead, Write};
9
10use crate::cli::{AuthCmd, Runtime};
11use crate::commands::auth;
12use crate::config;
13use crate::error::{CliError, Result};
14
15pub async fn run(rt: &Runtime) -> Result<()> {
16 if rt.out.quiet {
17 return Err(CliError::Input(
18 "init is interactive and cannot run with --quiet".into(),
19 ));
20 }
21 let stdin = std::io::stdin();
24 let mut lines = stdin.lock().lines();
25
26 let tenant = prompt(
27 &mut lines,
28 "Tenant (domain or GUID, e.g. contoso.onmicrosoft.com): ",
29 )?;
30 if tenant.is_empty() {
31 return Err(CliError::Input("tenant is required".into()));
32 }
33 let client_id = prompt(&mut lines, "Client ID (Entra public-client app GUID): ")?;
34 if client_id.is_empty() {
35 return Err(CliError::Input(
36 "client_id is required: register an Entra public-client app \
37 (device-code flow, delegated Files.Read.All / Sites.Read.All / offline_access \
38 scopes) and paste its Application (client) ID here"
39 .into(),
40 ));
41 }
42 let default_site = prompt(
43 &mut lines,
44 "Default site name or URL (optional, press enter to skip): ",
45 )?;
46
47 let profile_name = rt.cfg.profile_name.clone();
48 let mut file = rt.config_file.clone();
49 let entry = file.profile.entry(profile_name.clone()).or_default();
50 entry.tenant_id = Some(tenant.clone());
51 entry.client_id = Some(client_id.clone());
52 if !default_site.is_empty() {
53 entry.default_site = Some(default_site.clone());
54 }
55 config::save_file(&rt.config_path, &file)?;
56 rt.out
57 .print_message(&format!("Wrote {}", rt.config_path.display()));
58
59 let mut updated = rt.cfg.clone();
61 updated.tenant_id = Some(tenant);
62 updated.client_id = Some(client_id);
63 updated.default_site = if default_site.is_empty() {
64 file.profile
65 .get(&profile_name)
66 .and_then(|p| p.default_site.clone())
67 } else {
68 Some(default_site)
69 };
70 let new_rt = Runtime {
71 out: rt.out,
72 cfg: updated,
73 config_file: file,
74 config_path: rt.config_path.clone(),
75 cache_path: rt.cache_path.clone(),
76 };
77
78 auth::run(&new_rt, AuthCmd::Login).await
79}
80
81fn prompt(lines: &mut std::io::Lines<std::io::StdinLock<'_>>, label: &str) -> Result<String> {
82 eprint!("{label}");
83 std::io::stderr().flush().ok();
84 match lines.next() {
85 Some(Ok(line)) => Ok(line.trim().to_string()),
86 Some(Err(e)) => Err(CliError::Other(format!("read stdin: {e}"))),
87 None => Ok(String::new()),
88 }
89}