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
use std::{
fmt,
path::{Path, PathBuf},
sync::Arc,
};
use anyhow::Context;
use serde::{Deserialize, Serialize};
use crate::{
glob::Glob,
path_serializer,
project::ProjectNode,
snapshot_middleware::{emit_legacy_scripts_default, Middleware},
RojoRef,
};
/// Rojo-specific metadata that can be associated with an instance or a snapshot
/// of an instance.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InstanceMetadata {
/// Whether instances not present in the source should be ignored when
/// live-syncing. This is useful when there are instances that Rojo does not
/// manage.
pub ignore_unknown_instances: bool,
/// If a change occurs to this instance, the instigating source is what
/// should be run through the snapshot functions to regenerate it.
#[serde(skip_serializing_if = "Option::is_none")]
pub instigating_source: Option<InstigatingSource>,
/// The paths that, when changed, could cause the function that generated
/// this snapshot to generate a different snapshot. Paths should be included
/// even if they don't exist, since the presence of a file can change the
/// outcome of a snapshot function.
///
/// For example, a file named foo.lua might have these relevant paths:
/// - foo.lua
/// - foo.meta.json (even if this file doesn't exist!)
///
/// A directory named bar/ might have these:
/// - bar/
/// - bar/init.meta.json
/// - bar/init.lua
/// - bar/init.server.lua
/// - bar/init.client.lua
/// - bar/default.project.json
///
/// This path is used to make sure that file changes update all instances
/// that may need updates.
// TODO: Change this to be a SmallVec for performance in common cases?
#[serde(serialize_with = "path_serializer::serialize_vec_absolute")]
pub relevant_paths: Vec<PathBuf>,
/// Contains information about this instance that should persist between
/// snapshot invocations and is generally inherited.
///
/// If an instance has a piece of context attached to it, then the next time
/// that instance's instigating source is snapshotted directly, the same
/// context will be passed into it.
pub context: InstanceContext,
/// Indicates the ID used for Ref properties pointing to this Instance.
pub specified_id: Option<RojoRef>,
}
impl InstanceMetadata {
pub fn new() -> Self {
Self {
ignore_unknown_instances: false,
instigating_source: None,
relevant_paths: Vec::new(),
context: InstanceContext::default(),
specified_id: None,
}
}
pub fn ignore_unknown_instances(self, ignore_unknown_instances: bool) -> Self {
Self {
ignore_unknown_instances,
..self
}
}
pub fn instigating_source(self, instigating_source: impl Into<InstigatingSource>) -> Self {
Self {
instigating_source: Some(instigating_source.into()),
..self
}
}
pub fn relevant_paths(self, relevant_paths: Vec<PathBuf>) -> Self {
Self {
relevant_paths,
..self
}
}
pub fn context(self, context: &InstanceContext) -> Self {
Self {
context: context.clone(),
..self
}
}
pub fn specified_id(self, id: Option<RojoRef>) -> Self {
Self {
specified_id: id,
..self
}
}
}
impl Default for InstanceMetadata {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InstanceContext {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub path_ignore_rules: Arc<Vec<PathIgnoreRule>>,
pub emit_legacy_scripts: bool,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub sync_rules: Vec<SyncRule>,
}
impl InstanceContext {
pub fn new() -> Self {
Self {
path_ignore_rules: Arc::new(Vec::new()),
emit_legacy_scripts: emit_legacy_scripts_default().unwrap(),
sync_rules: Vec::new(),
}
}
pub fn with_emit_legacy_scripts(emit_legacy_scripts: Option<bool>) -> Self {
Self {
emit_legacy_scripts: emit_legacy_scripts
.or_else(emit_legacy_scripts_default)
.unwrap(),
..Self::new()
}
}
/// Extend the list of ignore rules in the context with the given new rules.
pub fn add_path_ignore_rules<I>(&mut self, new_rules: I)
where
I: IntoIterator<Item = PathIgnoreRule>,
I::IntoIter: ExactSizeIterator,
{
let new_rules = new_rules.into_iter();
// If the iterator is empty, we can skip cloning our list of ignore
// rules and appending to it.
if new_rules.len() == 0 {
return;
}
let rules = Arc::make_mut(&mut self.path_ignore_rules);
rules.extend(new_rules);
}
/// Extend the list of syncing rules in the context with the given new rules.
pub fn add_sync_rules<I>(&mut self, new_rules: I)
where
I: IntoIterator<Item = SyncRule>,
{
self.sync_rules.extend(new_rules);
}
/// Clears all sync rules for this InstanceContext
pub fn clear_sync_rules(&mut self) {
self.sync_rules.clear();
}
pub fn set_emit_legacy_scripts(&mut self, emit_legacy_scripts: bool) {
self.emit_legacy_scripts = emit_legacy_scripts;
}
/// Returns the middleware specified by the first sync rule that
/// matches the provided path. This does not handle default syncing rules.
pub fn get_user_sync_rule(&self, path: &Path) -> Option<&SyncRule> {
self.sync_rules.iter().find(|&rule| rule.matches(path))
}
}
impl Default for InstanceContext {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PathIgnoreRule {
/// The path that this glob is relative to. Since ignore globs are defined
/// in project files, this will generally be the folder containing the
/// project file that defined this glob.
#[serde(serialize_with = "path_serializer::serialize_absolute")]
pub base_path: PathBuf,
/// The actual glob that can be matched against the input path.
pub glob: Glob,
}
impl PathIgnoreRule {
pub fn passes<P: AsRef<Path>>(&self, path: P) -> bool {
let path = path.as_ref();
match path.strip_prefix(&self.base_path) {
Ok(suffix) => !self.glob.is_match(suffix),
Err(_) => true,
}
}
}
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub enum InstigatingSource {
Path(#[serde(serialize_with = "path_serializer::serialize_absolute")] PathBuf),
ProjectNode(
#[serde(serialize_with = "path_serializer::serialize_absolute")] PathBuf,
String,
Box<ProjectNode>,
Option<String>,
),
}
impl fmt::Debug for InstigatingSource {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
InstigatingSource::Path(path) => write!(formatter, "Path({})", path.display()),
InstigatingSource::ProjectNode(path, name, node, parent_class) => write!(
formatter,
"ProjectNode({}: {:?}) from path {} and parent class {:?}",
name,
node,
path.display(),
parent_class,
),
}
}
}
impl From<PathBuf> for InstigatingSource {
fn from(path: PathBuf) -> Self {
InstigatingSource::Path(path)
}
}
impl From<&Path> for InstigatingSource {
fn from(path: &Path) -> Self {
InstigatingSource::Path(path.to_path_buf())
}
}
/// Represents an user-specified rule for transforming files
/// into Instances using a given middleware.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
pub struct SyncRule {
/// A pattern used to determine if a file is included in this SyncRule
#[serde(rename = "pattern")]
pub include: Glob,
/// A pattern used to determine if a file is excluded from this SyncRule.
#[serde(skip_serializing_if = "Option::is_none")]
pub exclude: Option<Glob>,
/// The middleware specified by the user for this SyncRule
#[serde(rename = "use")]
pub middleware: Middleware,
/// A suffix to trim off of file names, including the file extension.
/// If not specified, the file extension is the only thing cut off.
#[serde(skip_serializing_if = "Option::is_none")]
pub suffix: Option<String>,
/// The 'base' of the glob above, allowing it to be used
/// relative to a path instead of absolute.
#[serde(skip)]
pub base_path: PathBuf,
}
impl SyncRule {
/// Returns whether the given path matches this rule.
pub fn matches(&self, path: &Path) -> bool {
match path.strip_prefix(&self.base_path) {
Ok(suffix) => {
if let Some(pattern) = &self.exclude {
if pattern.is_match(suffix) {
return false;
}
}
self.include.is_match(suffix)
}
Err(_) => false,
}
}
pub fn file_name_for_path<'a>(&self, path: &'a Path) -> anyhow::Result<&'a str> {
if let Some(suffix) = &self.suffix {
let file_name = path
.file_name()
.and_then(|s| s.to_str())
.with_context(|| format!("file name of {} is invalid", path.display()))?;
if file_name.ends_with(suffix) {
let end = file_name.len().saturating_sub(suffix.len());
Ok(&file_name[..end])
} else {
Ok(file_name)
}
} else {
// If the user doesn't specify a suffix, we assume they just want
// the name of the file (the file_stem)
path.file_stem()
.and_then(|s| s.to_str())
.with_context(|| format!("file name of {} is invalid", path.display()))
}
}
}