mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 21:29:54 +00:00
Props: vis option for setters; settings read follows open_with's folder and reports a damaged file; agent link rejects out-of-range ports
This commit is contained in:
@@ -37,6 +37,8 @@ pub enum LinkProblem {
|
||||
/// Why.
|
||||
error: String,
|
||||
},
|
||||
/// The control port setting is outside 0..=65535; nothing listens.
|
||||
PortOutOfRange(u32),
|
||||
/// The connection file could not be written; nothing listens without it.
|
||||
Publish(String),
|
||||
/// The app's own note ([`AgentLink::note`]), such as a folder it could not use.
|
||||
@@ -50,6 +52,7 @@ impl fmt::Display for LinkProblem {
|
||||
Self::NoSettingsFolder => f.write_str("Agents can't connect: the app has no settings folder (no home folder)."),
|
||||
Self::TokenFile(e) => write!(f, "Agents can't connect: the token file could not be written: {e}"),
|
||||
Self::Listen { port, error } => write!(f, "Couldn't listen on 127.0.0.1:{port}: {error}"),
|
||||
Self::PortOutOfRange(port) => write!(f, "Agents can't connect: the control port {port} is outside 0 to 65535."),
|
||||
Self::Publish(e) => write!(f, "Couldn't publish the agent connection: {e}"),
|
||||
Self::App(note) => f.write_str(note),
|
||||
}
|
||||
@@ -204,8 +207,10 @@ impl AgentLink {
|
||||
return Ok(());
|
||||
}
|
||||
update.stopped = self.running.take().is_some();
|
||||
// The setting's range is 0..=65535; anything else picks a free port.
|
||||
let port = u16::try_from(want.control_port).unwrap_or(0);
|
||||
// A setting outside 0..=65535 names no port; a retry would not change that, so none is scheduled.
|
||||
let Ok(port) = u16::try_from(want.control_port) else {
|
||||
return Err(LinkProblem::PortOutOfRange(want.control_port));
|
||||
};
|
||||
match self.start(&dir, port, want.control_port, host) {
|
||||
Ok((running, requests)) => {
|
||||
log::info!("agents can connect on {}", running.server.addr);
|
||||
|
||||
@@ -31,6 +31,7 @@ craft_ui::words! {
|
||||
no_settings_folder: template "agents.noSettingsFolder" = "Agents can't connect: {app} has no settings folder (no home folder).";
|
||||
token_file: template "agents.tokenFile" = "Agents can't connect: the token file could not be written: {error}";
|
||||
listen: template "agents.listen" = "Couldn't listen on 127.0.0.1:{port}: {error}";
|
||||
port_out_of_range: template "agents.portOutOfRange" = "Agents can't connect: the control port {port} is outside 0 to 65535.";
|
||||
publish: template "agents.publish" = "Couldn't publish the agent connection: {error}";
|
||||
}
|
||||
}
|
||||
@@ -43,6 +44,7 @@ impl AgentsWords {
|
||||
LinkProblem::NoSettingsFolder => self.no_settings_folder.fill(&[("app", app)]),
|
||||
LinkProblem::TokenFile(error) => self.token_file.fill(&[("error", error)]),
|
||||
LinkProblem::Listen { port, error } => self.listen.fill(&[("port", &port.to_string()), ("error", error)]),
|
||||
LinkProblem::PortOutOfRange(port) => self.port_out_of_range.fill(&[("port", &port.to_string())]),
|
||||
LinkProblem::Publish(error) => self.publish.fill(&[("error", error)]),
|
||||
LinkProblem::App(note) => note.clone(),
|
||||
}
|
||||
|
||||
@@ -235,6 +235,13 @@ fn a_new_port_restarts_with_the_same_token_and_a_taken_port_is_retried() {
|
||||
assert_eq!(link.status().port, Some(taken_port));
|
||||
assert_eq!(link.status().problem, None);
|
||||
assert_eq!(std::fs::read_to_string(dir.path().join(TOKEN_FILE)).unwrap(), token);
|
||||
|
||||
// A port setting outside 0..=65535 is a problem, not a random port.
|
||||
let out = link.sync(Some(&on(70_000)), &host);
|
||||
assert!(out.requests.is_none());
|
||||
assert_eq!(link.status().problem, Some(LinkProblem::PortOutOfRange(70_000)));
|
||||
assert_eq!(link.status().port, None);
|
||||
assert_eq!(read_connection(dir.path()).unwrap(), None, "the listener stopped and no file is left");
|
||||
}
|
||||
|
||||
/// Ten syncs with the same settings start one server.
|
||||
|
||||
@@ -303,7 +303,7 @@ pub struct TransformBox<'a> {
|
||||
line: Option<LineLook>,
|
||||
/// A plain press within `points` screen points outside the frame moves the box (0: off). Crate-private: the
|
||||
/// public entry is `TransformOverlay::move_reach`.
|
||||
#[prop(quantity = "press reach outside the frame, in screen points")]
|
||||
#[prop(quantity = "press reach outside the frame, in screen points", vis = "pub(crate)")]
|
||||
move_reach: f32,
|
||||
/// Whether this pass holds a drag of the reference point, so the hidden point is drawn while it moves.
|
||||
pivot_held: bool,
|
||||
|
||||
@@ -98,6 +98,9 @@ pub struct LoadReport {
|
||||
pub warning: Option<String>,
|
||||
/// Where the values came from.
|
||||
pub source: Source,
|
||||
/// The `config.toml` that could not be parsed. Defaults were used. [`SettingsStore::open_with`](crate::SettingsStore::open_with)
|
||||
/// moves it aside (see `broken_moved_to`); [`SettingsStore::read`](crate::SettingsStore::read) leaves it in place.
|
||||
pub damaged: Option<PathBuf>,
|
||||
/// Set when a damaged `config.toml` was renamed; the new name.
|
||||
pub broken_moved_to: Option<PathBuf>,
|
||||
/// Values replaced by their defaults. A `config.toml` value is also taken out of the file, which
|
||||
@@ -112,7 +115,7 @@ pub struct LoadReport {
|
||||
impl LoadReport {
|
||||
/// True when something should be shown to the user.
|
||||
pub fn has_problems(&self) -> bool {
|
||||
self.broken_moved_to.is_some() || !self.section_errors.is_empty() || self.read_only.is_some()
|
||||
self.damaged.is_some() || self.broken_moved_to.is_some() || !self.section_errors.is_empty() || self.read_only.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -137,10 +137,11 @@ pub fn resolve_named(app_id: &str, folder: &str, portable: &Portable, location:
|
||||
resolve_checked(app_id, folder, portable, location, probe, ensure_writable)
|
||||
}
|
||||
|
||||
/// [`resolve_named`] without touching the disk: a portable folder is taken as found, without creating it or
|
||||
/// checking that it is writable. For [`SettingsStore::read`](crate::SettingsStore::read), which writes nothing.
|
||||
/// [`resolve_named`] without changing the disk: the portable folder is judged by its permissions (see
|
||||
/// [`accepts_files`]) instead of creating it and writing a probe, with the same fallback to the platform folder.
|
||||
/// For [`SettingsStore::read`](crate::SettingsStore::read), which writes nothing.
|
||||
pub(crate) fn resolve_unprobed(app_id: &str, folder: &str, portable: &Portable, location: &Location, probe: &Probe) -> Resolved {
|
||||
resolve_checked(app_id, folder, portable, location, probe, |_| Ok(()))
|
||||
resolve_checked(app_id, folder, portable, location, probe, accepts_files)
|
||||
}
|
||||
|
||||
/// The folder rules, with `writable` deciding whether a portable folder is used.
|
||||
@@ -195,6 +196,20 @@ fn ensure_writable(dir: &Path) -> std::io::Result<()> {
|
||||
crate::recovery::check_writable(dir)
|
||||
}
|
||||
|
||||
/// Whether `dir`, or for a folder that doesn't exist yet its nearest existing ancestor (where
|
||||
/// [`ensure_writable`] would create it), is a folder with write permission. Reads metadata only.
|
||||
fn accepts_files(dir: &Path) -> std::io::Result<()> {
|
||||
let existing = dir.ancestors().find(|ancestor| ancestor.exists()).unwrap_or(dir);
|
||||
let meta = std::fs::metadata(existing)?;
|
||||
if !meta.is_dir() {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::NotADirectory, format!("{} is not a folder", existing.display())));
|
||||
}
|
||||
if meta.permissions().readonly() {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, format!("{} is read-only", existing.display())));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The marker found and the folder it points at, when `exe_dir` has one.
|
||||
///
|
||||
/// On macOS the executable sits in `X.app/Contents/MacOS`; the marker is looked for next to the
|
||||
|
||||
@@ -166,7 +166,8 @@ impl<T: Settings> SettingsStore<T> {
|
||||
|
||||
/// The settings [`open_with`](Self::open_with) would load from `options`, read without opening a store: for a
|
||||
/// second process, or a read before the application's store opens. It takes the same load path, and touches
|
||||
/// nothing on disk: no folder is created, none is checked for writing (a portable folder is taken as found), a
|
||||
/// nothing on disk: no folder is created, none is probed by writing (a portable folder that its permissions show as read-only falls back to the platform
|
||||
/// folder, as in `open_with`), a
|
||||
/// damaged `config.toml` reads as defaults and stays where it is, and with no `config.toml` the legacy files are
|
||||
/// imported in memory only.
|
||||
pub fn read(options: &OpenOptions<T>) -> (T, LoadReport) {
|
||||
@@ -188,6 +189,7 @@ impl<T: Settings> SettingsStore<T> {
|
||||
warning: resolved.warning.clone(),
|
||||
source: Source::Defaults,
|
||||
broken_moved_to: None,
|
||||
damaged: None,
|
||||
section_errors: Vec::new(),
|
||||
migrated_from: None,
|
||||
read_only: None,
|
||||
@@ -382,6 +384,7 @@ impl<T: Settings> SettingsStore<T> {
|
||||
let mut doc = match document::parse(text) {
|
||||
Ok(doc) => doc,
|
||||
Err(_) => {
|
||||
report.damaged = Some(path.to_path_buf());
|
||||
if damaged == Damaged::MoveAside {
|
||||
match self.files.move_aside(path) {
|
||||
Ok(moved) => report.broken_moved_to = Some(moved),
|
||||
|
||||
@@ -182,7 +182,39 @@ fn a_read_sees_what_a_store_wrote_and_touches_nothing_on_disk() {
|
||||
let (prefs, report) = SettingsStore::<Prefs>::read(&read_options(tmp.path()));
|
||||
assert_eq!(prefs.general.language, Prefs::default().general.language);
|
||||
assert!(report.broken_moved_to.is_none());
|
||||
assert_eq!(report.damaged.as_deref(), Some(config_path(tmp.path()).as_path()), "a damaged file is named, not read as absent");
|
||||
assert!(report.has_problems());
|
||||
assert_eq!(read_config(tmp.path()), broken, "a read never moves or rewrites the file");
|
||||
let moved = std::fs::read_dir(tmp.path()).unwrap().flatten().any(|e| e.file_name().to_string_lossy().starts_with("config.broken-"));
|
||||
assert!(!moved, "nothing is moved aside");
|
||||
}
|
||||
|
||||
/// A portable folder that is not writable: `read` loads the platform folder, as `open_with` does.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_read_falls_back_to_the_platform_folder_like_an_open() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let exe = tmp.path().join("exe");
|
||||
let portable = exe.join("config");
|
||||
let platform = tmp.path().join("platform");
|
||||
std::fs::create_dir_all(&portable).unwrap();
|
||||
std::fs::create_dir_all(platform.join("testcraft")).unwrap();
|
||||
std::fs::write(exe.join("portable"), "").unwrap();
|
||||
write_config(&portable, "schema_version = 2\n[general]\nlanguage = \"portable\"\n");
|
||||
write_config(&platform.join("testcraft"), "schema_version = 2\n[general]\nlanguage = \"platform\"\n");
|
||||
let options = || {
|
||||
let probe = craft_settings::Probe { env: Box::new(|_| None), exe_dir: Some(exe.clone()), platform_config_dir: Some(platform.clone()) };
|
||||
OpenOptions::<Prefs>::new(Location::Auto).probe(probe)
|
||||
};
|
||||
let (prefs, _) = SettingsStore::<Prefs>::read(&options());
|
||||
assert_eq!(prefs.general.language, "portable");
|
||||
|
||||
std::fs::set_permissions(&portable, std::fs::Permissions::from_mode(0o555)).unwrap();
|
||||
let (prefs, report) = SettingsStore::<Prefs>::read(&options());
|
||||
let (store, _) = SettingsStore::open_with(options());
|
||||
std::fs::set_permissions(&portable, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert_eq!(prefs.general.language, "platform");
|
||||
assert!(report.warning.is_some());
|
||||
assert_eq!(store.get().general.language, "platform", "an open takes the same folder");
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ struct Prop {
|
||||
boxed_bounds: Option<syn::punctuated::Punctuated<TypeParamBound, syn::Token![+]>>,
|
||||
name: Option<Ident>,
|
||||
func: Option<TypeParamBound>,
|
||||
/// The setter's visibility from `vis = ".."`; `pub` when absent.
|
||||
vis: Option<syn::Visibility>,
|
||||
}
|
||||
|
||||
/// The declared quantity of a `quantity = ".."` option: it states that a numeric prop is not a size, for the
|
||||
@@ -53,11 +55,14 @@ fn parse_prop(attr: &Attribute) -> syn::Result<Prop> {
|
||||
} else if meta.path.is_ident("func") {
|
||||
let bound: LitStr = meta.value()?.parse()?;
|
||||
prop.func = Some(bound.parse().map_err(|_| syn::Error::new(bound.span(), "`func` is a closure bound such as \"Fn(&K) -> bool\""))?);
|
||||
} else if meta.path.is_ident("vis") {
|
||||
let vis: LitStr = meta.value()?.parse()?;
|
||||
prop.vis = Some(vis.parse().map_err(|_| syn::Error::new(vis.span(), "`vis` is a visibility such as \"pub(crate)\""))?);
|
||||
} else if meta.path.is_ident("quantity") {
|
||||
read_quantity(&meta)?;
|
||||
} else {
|
||||
return Err(meta.error(
|
||||
"unknown `prop` option; expected `into`, `flag`, `boxed`, `boxed = \"..\"`, `name = \"..\"`, `func = \"..\"` or `quantity = \"..\"`",
|
||||
"unknown `prop` option; expected `into`, `flag`, `boxed`, `boxed = \"..\"`, `name = \"..\"`, `func = \"..\"`, `vis = \"..\"` or `quantity = \"..\"`",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
@@ -85,6 +90,7 @@ fn setter(field: &Field, attr: &Attribute) -> syn::Result<TokenStream> {
|
||||
return Err(syn::Error::new_spanned(field_name, "a `#[prop]` needs a doc comment: it becomes the setter's documentation"));
|
||||
}
|
||||
let name = prop.name.as_ref().unwrap_or(field_name);
|
||||
let vis = prop.vis.as_ref().map_or_else(|| quote!(pub), |vis| quote!(#vis));
|
||||
let ty = &field.ty;
|
||||
let (parameter, stored) = if prop.flag {
|
||||
if prop.into || !is_named(ty, "bool") {
|
||||
@@ -93,7 +99,7 @@ fn setter(field: &Field, attr: &Attribute) -> syn::Result<TokenStream> {
|
||||
let body = quote!(self.#field_name = true;);
|
||||
return Ok(quote! {
|
||||
#(#docs)*
|
||||
pub fn #name(mut self) -> Self {
|
||||
#vis fn #name(mut self) -> Self {
|
||||
#body
|
||||
self
|
||||
}
|
||||
@@ -111,7 +117,7 @@ fn setter(field: &Field, attr: &Attribute) -> syn::Result<TokenStream> {
|
||||
};
|
||||
return Ok(quote! {
|
||||
#(#docs)*
|
||||
pub fn #name<T: #bounds>(mut self, value: T) -> Self {
|
||||
#vis fn #name<T: #bounds>(mut self, value: T) -> Self {
|
||||
self.#field_name = ::core::option::Option::Some(::std::boxed::Box::new(value));
|
||||
self
|
||||
}
|
||||
@@ -136,7 +142,7 @@ fn setter(field: &Field, attr: &Attribute) -> syn::Result<TokenStream> {
|
||||
};
|
||||
Ok(quote! {
|
||||
#(#docs)*
|
||||
pub fn #name(mut self, #parameter) -> Self {
|
||||
#vis fn #name(mut self, #parameter) -> Self {
|
||||
self.#field_name = #stored;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -237,22 +237,22 @@ pub struct ParamDialog<'a> {
|
||||
answers: Vec<HostAnswer>,
|
||||
/// Marks the bound values as opened by the host with `opening`, so the first pass doesn't open them again and
|
||||
/// Reset restores `opening`.
|
||||
#[prop]
|
||||
#[prop(vis = "pub(crate)")]
|
||||
values_opened: Option<DialogFields>,
|
||||
/// Makes OK keep the dialog open and report its answer in `ParamDialogOutput::held`.
|
||||
#[prop(name = "hold_ok")]
|
||||
#[prop(name = "hold_ok", vis = "pub(crate)")]
|
||||
hold: bool,
|
||||
/// Closes the dialog as OK in this pass: the host accepted the held answer.
|
||||
#[prop]
|
||||
#[prop(vis = "pub(crate)")]
|
||||
finish_held: bool,
|
||||
/// Shows `reason` under the rows while the values are `refused`.
|
||||
#[prop]
|
||||
#[prop(vis = "pub(crate)")]
|
||||
refusal: Option<(Label, DialogFields)>,
|
||||
/// Centres the preview pane's view on the picture point `point` in this pass; without a picture it does nothing.
|
||||
#[prop(name = "centre_on")]
|
||||
#[prop(name = "centre_on", vis = "pub(crate)")]
|
||||
centre: Option<Pos2>,
|
||||
/// The colours the colour rows show in place of their values in this pass, by row key.
|
||||
#[prop]
|
||||
#[prop(vis = "pub(crate)")]
|
||||
preview_colors: Vec<(String, Srgba)>,
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user