1use std::path::PathBuf;
4
5use anyhow::{Context, bail};
6use semora_proto::{CreateProject, Level};
7
8use crate::args::ProjectCmd;
9use crate::client::ProjectCreated;
10use crate::local_links::{self, LocalLink};
11use crate::project_link::Fit;
12use crate::{Ctx, exit, output, project_link};
13
14pub async fn run(ctx: &Ctx, cmd: ProjectCmd) -> anyhow::Result<i32> {
15 match cmd {
16 ProjectCmd::Init { dir, name, join } => init(ctx, dir, name, join).await,
17 ProjectCmd::Ls => ls(ctx).await,
18 ProjectCmd::Link {
19 dir,
20 rewrite,
21 project,
22 } => link(ctx, dir, rewrite, project).await,
23 ProjectCmd::Unlink { dir } => unlink(ctx, dir),
24 ProjectCmd::Map(a) => super::map::run(ctx, a).await,
25 }
26}
27
28async fn init(
29 ctx: &Ctx,
30 dir: Option<PathBuf>,
31 name: Option<String>,
32 join: bool,
33) -> anyhow::Result<i32> {
34 let client = ctx.client()?;
35 let dir = std::fs::canonicalize(dir.unwrap_or_else(|| PathBuf::from(".")))
36 .context("cannot read the project folder")?;
37 if !dir.is_dir() {
38 bail!("{} is not a folder", project_link::shown(&dir));
39 }
40 let dir_name = dir
41 .file_name()
42 .map(|n| n.to_string_lossy().into_owned())
43 .unwrap_or_default();
44 if let Some(n) = &name
45 && !project_link::valid_slug(n)
46 {
47 bail!(
48 "`{n}` is not a valid project id: use lowercase letters, digits and dashes, up to 40 characters, starting with a letter or digit"
49 );
50 }
51 let config_dir = &ctx.settings.config_dir;
52 let existing = match project_link::read_at(&dir)? {
56 Some(file) => Some(project_link::resolve(&client, config_dir, file).await?),
57 None => None,
58 };
59 if let Some(l) = &existing
60 && name.as_ref().is_some_and(|n| *n != l.slug)
61 {
62 bail!(
63 "{} already links this folder to project `{}`. Remove it to start again.",
64 project_link::shown(&dir.join(project_link::FILE)),
65 l.slug
66 );
67 }
68 let slug = match (name, &existing) {
69 (Some(n), _) => n,
70 (None, Some(l)) => l.slug.clone(),
71 (None, None) => project_link::slug_from(&dir_name).with_context(|| {
72 format!("can't make a project id from `{dir_name}`; pass one with --name")
73 })?,
74 };
75 let req = CreateProject {
76 slug: slug.clone(),
77 name: Some(dir_name).filter(|n| !n.trim().is_empty()),
78 join,
79 };
80 let (info, created) = match client.create_project(&req).await? {
81 ProjectCreated::Created(p) => (p, true),
82 ProjectCreated::Linked(p) => (p, false),
83 ProjectCreated::Taken => bail!(
84 "the project id `{slug}` belongs to someone else; choose another with --name, for example `--name {slug}-2`"
85 ),
86 ProjectCreated::JoinNeeded { owner, level } => bail!(
88 "Project `{slug}` belongs to {}, and you are {} {} in it. Run `semora project init --join` to publish into it, or choose another id with --name.",
89 output::clean_name(&owner),
90 if level == Level::Editor { "an" } else { "a" },
91 level.label()
92 ),
93 };
94 let slug = info.slug.clone();
96 let wrote = match existing {
97 None => {
98 let id = crate::server_id::of(&client, config_dir, true).await?;
100 Some(project_link::write(&dir, &id, &slug)?)
101 }
102 Some(l) => {
103 project_link::adopt(l, &slug);
104 None
105 }
106 };
107 if ctx.json {
108 output::json(&info);
109 return Ok(exit::OK);
110 }
111 let done = output::out().done;
112 if created {
113 anstream::println!("{done}Created{done:#} project \"{}\" ({slug})", info.name);
114 } else if info.level == Level::Owner {
115 anstream::println!(
116 "{done}Linked{done:#} to your existing project \"{}\" ({slug})",
117 info.name
118 );
119 } else {
120 anstream::println!(
121 "{done}Joined{done:#} project \"{}\" ({slug}) as {} {}",
122 info.name,
123 if info.level == Level::Editor {
124 "an"
125 } else {
126 "a"
127 },
128 info.level.label()
129 );
130 }
131 if let Some(file) = wrote {
132 println!("Wrote {}", project_link::shown(&file));
133 println!("Commit it so every checkout publishes to the same project.");
134 }
135 anstream::println!("{LINK}{}{LINK:#}", info.url, LINK = output::LINK);
136 Ok(exit::OK)
137}
138
139fn file_for(dir: Option<PathBuf>) -> anyhow::Result<project_link::FileLink> {
141 let dir = dir.unwrap_or_else(|| PathBuf::from("."));
142 project_link::find(&dir)?.with_context(|| {
143 format!(
144 "{} is not in a project: no {} here or in a parent folder.",
145 project_link::shown(&dir),
146 project_link::FILE
147 )
148 })
149}
150
151async fn link(
154 ctx: &Ctx,
155 dir: Option<PathBuf>,
156 rewrite: bool,
157 project: Option<String>,
158) -> anyhow::Result<i32> {
159 let client = ctx.client()?;
160 let config_dir = &ctx.settings.config_dir;
161 let file = file_for(dir)?;
162 let path = project_link::shown(&file.root.join(project_link::FILE));
163 let fit = project_link::fit(&client, config_dir, &file).await?;
164 if matches!(fit, Fit::Ours | Fit::LegacyOurs) {
165 println!("{path} is already for your server.");
166 return Ok(exit::OK);
167 }
168 let id = crate::server_id::of(&client, config_dir, true).await?;
169 let key = project_link::server_value(&file.server);
170 if rewrite {
171 project_link::set_line(&file.root, "server", &id)?;
172 let mut moved = String::new();
174 if let Fit::Mapped(record) = &fit
175 && record.project != file.slug
176 {
177 project_link::set_line(&file.root, "project", &record.project)?;
178 moved = format!(
179 " Its project is now '{}', the id this machine used.",
180 record.project
181 );
182 }
183 local_links::remove(config_dir, &key, &file.slug)?;
184 output::warn(format!(
185 "{path} now names your server.{moved} If you commit it, everyone else's checkouts stop working until they log in to your server or link it. Commit it only if the whole project is moving."
186 ));
187 return Ok(exit::OK);
188 }
189 let project = project.unwrap_or_else(|| file.slug.clone());
190 if !project_link::valid_slug(&project) {
191 bail!(
192 "`{project}` is not a valid project id: use lowercase letters, digits and dashes, up to 40 characters, starting with a letter or digit"
193 );
194 }
195 let origin = client.origin();
196 local_links::save(
197 config_dir,
198 LocalLink {
199 file_server: key,
200 file_project: file.slug.clone(),
201 origin: origin.clone(),
202 server_id: id,
203 project: project.clone(),
204 root: Some(file.root.clone()),
205 },
206 )?;
207 output::warn(format!(
208 "Linked {path}'s project '{}' to {origin} on this machine, as project '{project}'. Documents you push go to your server only, and drift from everyone else's copy. `semora project unlink` undoes it.",
209 file.slug
210 ));
211 Ok(exit::OK)
212}
213
214fn unlink(ctx: &Ctx, dir: Option<PathBuf>) -> anyhow::Result<i32> {
216 let file = file_for(dir)?;
217 let path = project_link::shown(&file.root.join(project_link::FILE));
218 let key = project_link::server_value(&file.server);
219 if local_links::remove(&ctx.settings.config_dir, &key, &file.slug)? {
220 println!("Dropped this machine's link for {path}.");
221 } else {
222 println!("{path} has no link on this machine.");
223 }
224 Ok(exit::OK)
225}
226
227async fn ls(ctx: &Ctx) -> anyhow::Result<i32> {
228 let client = ctx.client()?;
229 let projects = client.projects().await?;
230 if ctx.json {
231 output::json(&projects);
232 return Ok(exit::OK);
233 }
234 if projects.is_empty() {
235 println!("No projects. Run `semora project init` in a folder.");
236 return Ok(exit::OK);
237 }
238 for p in &projects {
239 println!(
240 "{:<24} {:<9} {:>4} docs {} {}",
241 p.slug,
242 p.level.as_str(),
243 p.documents,
244 output::ts(p.updated_at),
245 p.name
246 );
247 }
248 Ok(exit::OK)
249}