forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnew.rs
More file actions
350 lines (304 loc) · 9.8 KB
/
Copy pathnew.rs
File metadata and controls
350 lines (304 loc) · 9.8 KB
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
use std::fs;
use camino::{Utf8Path, Utf8PathBuf};
use common::config::{Config, WorkspaceMemberSelection};
use common::paths::{absolute_utf8, file_url_to_utf8_path, normalize_slashes};
use resolver::workspace::{discover_context, expand_workspace_members};
use toml::Value;
use url::Url;
const DEFAULT_VERSION: &str = "0.1.0";
pub fn run(
path: &Utf8PathBuf,
workspace: bool,
name: Option<&str>,
version: Option<&str>,
) -> Result<(), String> {
let target = absolute_target(path)?;
if target.exists() && target.is_file() {
return Err(format!(
"Target path {target} exists and is a file; expected directory"
));
}
if workspace {
create_workspace_layout(&target, name, version)?;
return Ok(());
}
let mut start_dir = target.parent().unwrap_or(target.as_path());
while !start_dir.exists() {
let Some(parent) = start_dir.parent() else {
break;
};
start_dir = parent;
}
let workspace_root = find_workspace_root(start_dir)?;
create_ingot_layout(&target, name, version)?;
if let Some(root) = workspace_root {
match workspace_member_suggestion(&root, &target) {
Ok(Some(message)) => println!("{message}"),
Ok(None) => {}
Err(err) => eprintln!("Warning: failed to check workspace members: {err}"),
}
}
Ok(())
}
fn create_workspace_layout(
base: &Utf8PathBuf,
explicit_name: Option<&str>,
explicit_version: Option<&str>,
) -> Result<(), String> {
fs::create_dir_all(base)
.map_err(|err| format!("Failed to create workspace directory {base}: {err}"))?;
let workspace_name = explicit_name
.map(ToString::to_string)
.unwrap_or_else(|| infer_workspace_name(base));
let version = explicit_version.unwrap_or(DEFAULT_VERSION);
let workspace_config = base.join("fe.toml");
write_if_absent(
&workspace_config,
format!(
r#"# Workspace config
[workspace]
name = "{workspace_name}"
version = "{version}"
# Members can be a flat array or a table with main/dev groups.
members = []
# members = ["ingots/*"]
# members = {{ main = ["packages/*"], dev = ["examples/*"] }}
# Paths to exclude from member discovery.
exclude = ["target"]
"#
),
)?;
println!("Created workspace at {base}");
Ok(())
}
fn create_ingot_layout(
base: &Utf8PathBuf,
explicit_name: Option<&str>,
explicit_version: Option<&str>,
) -> Result<(), String> {
fs::create_dir_all(base)
.map_err(|err| format!("Failed to create ingot directory {base}: {err}"))?;
let src_dir = base.join("src");
fs::create_dir_all(&src_dir)
.map_err(|err| format!("Failed to create src directory {src_dir}: {err}"))?;
let name = explicit_name
.map(ToString::to_string)
.unwrap_or_else(|| infer_ingot_name(base));
let version = explicit_version.unwrap_or(DEFAULT_VERSION);
let config_path = base.join("fe.toml");
write_if_absent(
&config_path,
format!(
r#"# Ingot config
[ingot]
name = "{name}"
version = "{version}"
# Optional dependencies
# [dependencies]
# utils = {{ path = "../utils" }}
"#
),
)?;
let src_lib = src_dir.join("lib.fe");
write_if_absent(
&src_lib,
r#"// A simple Counter contract to get you started.
// Run `fe test` to see it in action!
use std::abi::sol
use std::evm::{Evm, Call}
use std::evm::effects::assert
// Messages define your contract's public interface.
// Each variant becomes a callable function with a unique selector.
// The `sol()` const fn computes the standard Solidity selector at compile time.
msg CounterMsg {
#[selector = sol("increment()")]
Increment,
#[selector = sol("get()")]
Get -> u256,
}
// Storage is defined as a regular struct.
// Its fields are persisted on-chain between calls.
struct CounterStore {
value: u256,
}
// The contract itself: declares its storage and handles messages.
pub contract Counter {
mut store: CounterStore
// The constructor runs once when the contract is deployed.
init() uses (mut store) {
store.value = 0
}
// The recv block routes incoming messages to handlers.
recv CounterMsg {
Increment uses (mut store) {
store.value = store.value + 1
}
Get -> u256 uses (store) {
store.value
}
}
}
// Tests can deploy and interact with contracts.
// Run with: fe test
#[test]
fn test_counter() uses (evm: mut Evm) {
// Deploy the contract
let addr = evm.create2<Counter>(value: 0, args: (), salt: 0)
assert(addr.inner != 0)
// Initially the counter is 0
let val: u256 = evm.call(
addr: addr,
gas: 100000,
value: 0,
message: CounterMsg::Get {}
)
assert(val == 0)
// Increment the counter
evm.call(
addr: addr,
gas: 100000,
value: 0,
message: CounterMsg::Increment {}
)
// Now it should be 1
let val: u256 = evm.call(
addr: addr,
gas: 100000,
value: 0,
message: CounterMsg::Get {}
)
assert(val == 1)
}
"#,
)?;
println!("Created ingot at {base}");
Ok(())
}
fn write_if_absent(path: &Utf8PathBuf, content: impl AsRef<str>) -> Result<(), String> {
if path.exists() {
return Err(format!("Refusing to overwrite existing {}", path));
}
fs::write(path, content.as_ref()).map_err(|err| format!("Failed to write {}: {err}", path))?;
Ok(())
}
fn infer_ingot_name(path: &Utf8PathBuf) -> String {
let fallback = "ingot".to_string();
let Some(stem) = path.file_name().map(|s| s.to_string()) else {
return fallback;
};
sanitize_name(&stem, fallback)
}
fn infer_workspace_name(path: &Utf8PathBuf) -> String {
let fallback = "workspace".to_string();
let Some(stem) = path.file_name().map(|s| s.to_string()) else {
return fallback;
};
sanitize_name(&stem, fallback)
}
fn sanitize_name(candidate: &str, fallback: String) -> String {
let mut sanitized = String::new();
for c in candidate.chars() {
if c.is_ascii_alphanumeric() || c == '_' {
sanitized.push(c);
} else {
sanitized.push('_');
}
}
if sanitized.is_empty() {
fallback
} else {
sanitized
}
}
fn absolute_target(path: &Utf8PathBuf) -> Result<Utf8PathBuf, String> {
absolute_utf8(path).map_err(|err| format!("Failed to resolve absolute path for {path}: {err}"))
}
fn find_workspace_root(start: &Utf8Path) -> Result<Option<Utf8PathBuf>, String> {
let start_url = Url::from_directory_path(start.as_std_path())
.map_err(|_| "Invalid directory path".to_string())?;
let discovery = discover_context(&start_url, false).map_err(|err| err.to_string())?;
let Some(workspace_url) = discovery.workspace_root else {
return Ok(None);
};
let path = file_url_to_utf8_path(&workspace_url)
.ok_or_else(|| "Workspace path is not valid UTF-8".to_string())?;
Ok(Some(path))
}
fn workspace_member_suggestion(
workspace_root: &Utf8PathBuf,
member_dir: &Utf8PathBuf,
) -> Result<Option<String>, String> {
let config_path = workspace_root.join("fe.toml");
let config_str = fs::read_to_string(config_path.as_std_path())
.map_err(|err| format!("Failed to read {}: {err}", config_path))?;
let config_file = Config::parse(&config_str)
.map_err(|err| format!("Failed to parse {}: {err}", config_path))?;
let workspace = match config_file {
Config::Workspace(workspace_config) => workspace_config.workspace,
Config::Ingot(_) => return Ok(None),
};
let relative_member = member_dir
.strip_prefix(workspace_root)
.map_err(|_| "Ingot path is not inside workspace".to_string())?
.to_path_buf();
let relative_member_str = normalize_member_path(&relative_member);
if relative_member.as_str().is_empty() {
return Ok(None);
}
let base_url = Url::from_directory_path(workspace_root.as_std_path())
.map_err(|_| format!("Invalid workspace path: {workspace_root}"))?;
if let Ok(expanded) =
expand_workspace_members(&workspace, &base_url, WorkspaceMemberSelection::All)
&& expanded
.iter()
.any(|member| normalize_member_path(&member.path) == relative_member_str)
{
return Ok(None);
}
let value: Value = config_str
.parse()
.map_err(|err| format!("Failed to parse {}: {err}", config_path))?;
let root_table = value
.as_table()
.ok_or_else(|| format!("{} is not a workspace config", config_path))?;
let has_workspace_table = root_table
.get("workspace")
.and_then(|value| value.as_table())
.is_some();
let workspace_table = if has_workspace_table {
root_table
.get("workspace")
.and_then(|value| value.as_table())
.ok_or_else(|| "workspace is not a table".to_string())?
} else {
root_table
};
let members_path = match workspace_table.get("members") {
Some(Value::Array(_)) | None => {
if has_workspace_table {
"[workspace].members"
} else {
"members"
}
}
Some(Value::Table(_)) => {
if has_workspace_table {
"[workspace].members.main"
} else {
"members.main"
}
}
Some(_) => {
return Err(format!(
"members is not an array or table in {}",
config_path
));
}
};
Ok(Some(format!(
"Workspace detected at {workspace_root}. To include this ingot, add \"{relative_member_str}\" to {members_path} in {config_path}."
)))
}
fn normalize_member_path(path: &Utf8Path) -> String {
normalize_slashes(path.as_str())
}