-
Notifications
You must be signed in to change notification settings - Fork 209
/
Copy pathinit.rs
674 lines (595 loc) · 21.8 KB
/
init.rs
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
use std::{
cmp::PartialEq,
fs,
io::{Error, ErrorKind, Write},
path::{Path, PathBuf},
str::FromStr,
};
use clap::{Parser, ValueEnum};
use miette::{Context, IntoDiagnostic};
use minijinja::{context, Environment};
use pixi_config::{get_default_author, Config};
use pixi_consts::consts;
use pixi_manifest::{
pyproject::PyProjectManifest, DependencyOverwriteBehavior, FeatureName, SpecType,
};
use pixi_spec::PixiSpec;
use pixi_utils::conda_environment_file::CondaEnvFile;
use rattler_conda_types::{NamedChannelOrUrl, Platform};
use tokio::fs::OpenOptions;
use url::Url;
use uv_normalize::PackageName;
use crate::Project;
#[derive(Parser, Debug, Clone, PartialEq, ValueEnum)]
pub enum ManifestFormat {
Pixi,
Pyproject,
}
/// Creates a new project
#[derive(Parser, Debug)]
pub struct Args {
/// Where to place the project (defaults to current path)
#[arg(default_value = ".")]
pub path: PathBuf,
/// Channels to use in the project.
#[arg(short, long = "channel", id = "channel", conflicts_with = "env_file")]
pub channels: Option<Vec<NamedChannelOrUrl>>,
/// Platforms that the project supports.
#[arg(short, long = "platform", id = "platform")]
pub platforms: Vec<String>,
/// Environment.yml file to bootstrap the project.
#[arg(short = 'i', long = "import")]
pub env_file: Option<PathBuf>,
/// The manifest format to create.
#[arg(long, conflicts_with_all = ["env_file", "pyproject_toml"], ignore_case = true)]
pub format: Option<ManifestFormat>,
/// Create a pyproject.toml manifest instead of a pixi.toml manifest
// BREAK (0.27.0): Remove this option from the cli in favor of the `format` option.
#[arg(long, conflicts_with_all = ["env_file", "format"], alias = "pyproject", hide = true)]
pub pyproject_toml: bool,
/// Source Control Management used for this project
#[arg(short = 's', long = "scm", ignore_case = true)]
pub scm: Option<GitAttributes>,
}
/// The pixi.toml template
///
/// This uses a template just to simplify the flexibility of emitting it.
const PROJECT_TEMPLATE: &str = r#"[project]
{%- if author %}
authors = ["{{ author[0] }} <{{ author[1] }}>"]
{%- endif %}
channels = {{ channels }}
description = "Add a short description here"
name = "{{ name }}"
platforms = {{ platforms }}
version = "{{ version }}"
{%- if index_url or extra_indexes %}
[pypi-options]
{% if index_url %}index-url = "{{ index_url }}"{% endif %}
{% if extra_index_urls %}extra-index-urls = {{ extra_index_urls }}{% endif %}
{%- endif %}
[tasks]
[dependencies]
"#;
/// The pyproject.toml template
///
/// This is injected into an existing pyproject.toml
const PYROJECT_TEMPLATE_EXISTING: &str = r#"
[tool.pixi.project]
{%- if pixi_name %}
name = "{{ name }}"
{%- endif %}
channels = {{ channels }}
platforms = {{ platforms }}
[tool.pixi.pypi-dependencies]
{{ name }} = { path = ".", editable = true }
{%- for env, features in environments|items %}
{%- if loop.first %}
[tool.pixi.environments]
default = { solve-group = "default" }
{%- endif %}
{{env}} = { features = {{ features }}, solve-group = "default" }
{%- endfor %}
[tool.pixi.tasks]
"#;
/// The pyproject.toml template
///
/// This is used to create a pyproject.toml from scratch
const NEW_PYROJECT_TEMPLATE: &str = r#"[project]
{%- if author %}
authors = [{name = "{{ author[0] }}", email = "{{ author[1] }}"}]
{%- endif %}
dependencies = []
description = "Add a short description here"
name = "{{ name }}"
requires-python = ">= 3.11"
version = "{{ version }}"
[build-system]
build-backend = "hatchling.build"
requires = ["hatchling"]
[tool.pixi.project]
channels = {{ channels }}
platforms = {{ platforms }}
{%- if index_url or extra_indexes %}
[tool.pixi.pypi-options]
{% if index_url %}index-url = "{{ index_url }}"{% endif %}
{% if extra_index_urls %}extra-index-urls = {{ extra_index_urls }}{% endif %}
{%- endif %}
[tool.pixi.pypi-dependencies]
{{ pypi_package_name }} = { path = ".", editable = true }
[tool.pixi.tasks]
"#;
const GITIGNORE_TEMPLATE: &str = r#"
# pixi environments
.pixi
*.egg-info
"#;
#[derive(Parser, Debug, Clone, PartialEq, ValueEnum)]
pub enum GitAttributes {
Github,
Gitlab,
Codeberg,
}
impl GitAttributes {
fn template(&self) -> &'static str {
match self {
GitAttributes::Github | GitAttributes::Codeberg => {
r#"# SCM syntax highlighting
pixi.lock linguist-language=YAML linguist-generated=true
"#
}
GitAttributes::Gitlab => {
r#"# GitLab syntax highlighting
pixi.lock gitlab-language=yaml gitlab-generated=true
"#
}
}
}
}
pub async fn execute(args: Args) -> miette::Result<()> {
let env = Environment::new();
let dir = get_dir(args.path).into_diagnostic()?;
let pixi_manifest_path = dir.join(consts::PROJECT_MANIFEST);
let pyproject_manifest_path = dir.join(consts::PYPROJECT_MANIFEST);
let gitignore_path = dir.join(".gitignore");
let gitattributes_path = dir.join(".gitattributes");
let config = Config::load_global();
// Deprecation warning for the `pyproject` option
if args.pyproject_toml {
eprintln!(
"{}The '{}' option is deprecated and will be removed in the future.\nUse '{}' instead.",
console::style(console::Emoji("⚠️ ", "")).yellow(),
console::style("--pyproject").bold().red(),
console::style("--format pyproject").bold().green(),
);
}
// Fail silently if the directory already exists or cannot be created.
fs_err::create_dir_all(&dir).ok();
let default_name = get_name_from_dir(&dir).unwrap_or_else(|_| String::from("new_project"));
let version = "0.1.0";
let author = get_default_author();
let platforms = if args.platforms.is_empty() {
vec![Platform::current().to_string()]
} else {
args.platforms.clone()
};
// Create a 'pixi.toml' manifest and populate it by importing a conda
// environment file
if let Some(env_file_path) = args.env_file {
// Check if the 'pixi.toml' file doesn't already exist. We don't want to
// overwrite it.
if pixi_manifest_path.is_file() {
miette::bail!("{} already exists", consts::PROJECT_MANIFEST);
}
let env_file = CondaEnvFile::from_path(&env_file_path)?;
let name = env_file
.name()
.unwrap_or(default_name.clone().as_str())
.to_string();
// TODO: Improve this:
// - Use .condarc as channel config
let (conda_deps, pypi_deps, channels) = env_file.to_manifest(&config)?;
let rv = render_project(
&env,
name,
version,
author.as_ref(),
channels,
&platforms,
None,
&vec![],
);
let mut project = Project::from_str(&pixi_manifest_path, &rv)?;
let channel_config = project.channel_config();
for spec in conda_deps {
// Determine the name of the package to add
let (Some(name), spec) = spec.clone().into_nameless() else {
miette::bail!(
"{} does not support wildcard dependencies",
pixi_utils::executable_name()
);
};
let spec = PixiSpec::from_nameless_matchspec(spec, &channel_config);
project.manifest.add_dependency(
&name,
&spec,
SpecType::Run,
// No platforms required as you can't define them in the yaml
&[],
&FeatureName::default(),
DependencyOverwriteBehavior::Overwrite,
)?;
}
for requirement in pypi_deps {
project.manifest.add_pep508_dependency(
&requirement,
// No platforms required as you can't define them in the yaml
&[],
&FeatureName::default(),
None,
DependencyOverwriteBehavior::Overwrite,
&None,
)?;
}
project.save()?;
eprintln!(
"{}Created {}",
console::style(console::Emoji("✔ ", "")).green(),
// Canonicalize the path to make it more readable, but if it fails just use the path as
// is.
project.manifest_path().display()
);
} else {
let channels = if let Some(channels) = args.channels {
channels
} else {
config.default_channels().to_vec()
};
let index_url = config.pypi_config.index_url;
let extra_index_urls = config.pypi_config.extra_index_urls;
// Dialog with user to create a 'pyproject.toml' or 'pixi.toml' manifest
// If nothing is defined but there is a `pyproject.toml` file, ask the user.
let pyproject = if !pixi_manifest_path.is_file()
&& args.format.is_none()
&& !args.pyproject_toml
&& pyproject_manifest_path.is_file()
{
dialoguer::Confirm::new()
.with_prompt(format!("\nA '{}' file already exists.\nDo you want to extend it with the '{}' configuration?", console::style(consts::PYPROJECT_MANIFEST).bold(), console::style("[tool.pixi]").bold().green()))
.default(false)
.show_default(true)
.interact()
.into_diagnostic()?
} else {
args.format == Some(ManifestFormat::Pyproject) || args.pyproject_toml
};
// Inject a tool.pixi.project section into an existing pyproject.toml file if
// there is one without '[tool.pixi.project]'
if pyproject && pyproject_manifest_path.is_file() {
let pyproject = PyProjectManifest::from_path(&pyproject_manifest_path)?;
// Early exit if 'pyproject.toml' already contains a '[tool.pixi.project]' table
if pyproject.has_pixi_table() {
eprintln!(
"{}Nothing to do here: 'pyproject.toml' already contains a '[tool.pixi.project]' section.",
console::style(console::Emoji("🤔 ", "")).blue(),
);
return Ok(());
}
let (name, pixi_name) = match pyproject.name() {
Some(name) => (name, false),
None => (default_name.as_str(), true),
};
let environments = pyproject.environments_from_extras().into_diagnostic()?;
let rv = env
.render_named_str(
consts::PYPROJECT_MANIFEST,
PYROJECT_TEMPLATE_EXISTING,
context! {
name,
pixi_name,
channels,
platforms,
environments,
},
)
.unwrap();
if let Err(e) = {
fs::OpenOptions::new()
.append(true)
.open(pyproject_manifest_path.clone())
.and_then(|mut p| p.write_all(rv.as_bytes()))
} {
tracing::warn!(
"Warning, couldn't update '{}' because of: {}",
pyproject_manifest_path.to_string_lossy(),
e
);
} else {
// Inform about the addition of the package itself as an editable dependency of
// the project
eprintln!(
"{}Added package '{}' as an editable dependency.",
console::style(console::Emoji("✔ ", "")).green(),
name
);
// Inform about the addition of environments from optional dependencies
// or dependency groups (if any)
if !environments.is_empty() {
let envs: Vec<&str> = environments.keys().map(AsRef::as_ref).collect();
eprintln!(
"{}Added environment{} '{}' from optional dependencies or dependency groups.",
console::style(console::Emoji("✔ ", "")).green(),
if envs.len() > 1 { "s" } else { "" },
envs.join("', '")
)
}
}
// Create a 'pyproject.toml' manifest
} else if pyproject {
// Python package names cannot contain '-', so we replace them with '_'
let pypi_package_name = PackageName::from_str(&default_name)
.map(|name| name.as_dist_info_name().to_string())
.unwrap_or_else(|_| default_name.clone());
let rv = env
.render_named_str(
consts::PYPROJECT_MANIFEST,
NEW_PYROJECT_TEMPLATE,
context! {
name => default_name,
pypi_package_name,
version,
author,
channels,
platforms,
index_url => index_url.as_ref(),
extra_index_urls => &extra_index_urls,
},
)
.unwrap();
save_manifest_file(&pyproject_manifest_path, rv)?;
let src_dir = dir.join("src").join(pypi_package_name);
tokio::fs::create_dir_all(&src_dir)
.await
.into_diagnostic()
.wrap_err_with(|| format!("Could not create directory {}.", src_dir.display()))?;
let init_file = src_dir.join("__init__.py");
match OpenOptions::new()
.write(true)
.create_new(true)
.open(&init_file)
.await
{
Ok(_) => (),
Err(e) if e.kind() == ErrorKind::AlreadyExists => {
// If the file already exists, do nothing
}
Err(e) => {
return Err(e).into_diagnostic().wrap_err_with(|| {
format!("Could not create file {}.", init_file.display())
});
}
};
// Create a 'pixi.toml' manifest
} else {
// Check if the 'pixi.toml' file doesn't already exist. We don't want to
// overwrite it.
if pixi_manifest_path.is_file() {
miette::bail!("{} already exists", consts::PROJECT_MANIFEST);
}
let rv = render_project(
&env,
default_name,
version,
author.as_ref(),
channels,
&platforms,
index_url.as_ref(),
&extra_index_urls,
);
save_manifest_file(&pixi_manifest_path, rv)?;
};
}
// create a .gitignore if one is missing
if let Err(e) = create_or_append_file(&gitignore_path, GITIGNORE_TEMPLATE) {
tracing::warn!(
"Warning, couldn't update '{}' because of: {}",
gitignore_path.to_string_lossy(),
e
);
}
let git_attributes = args.scm.unwrap_or(GitAttributes::Github);
// create a .gitattributes if one is missing
if let Err(e) = create_or_append_file(&gitattributes_path, git_attributes.template()) {
tracing::warn!(
"Warning, couldn't update '{}' because of: {}",
gitattributes_path.to_string_lossy(),
e
);
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn render_project(
env: &Environment<'_>,
name: String,
version: &str,
author: Option<&(String, String)>,
channels: Vec<NamedChannelOrUrl>,
platforms: &Vec<String>,
index_url: Option<&Url>,
extra_index_urls: &Vec<Url>,
) -> String {
env.render_named_str(
consts::PROJECT_MANIFEST,
PROJECT_TEMPLATE,
context! {
name,
version,
author,
channels,
platforms,
index_url,
extra_index_urls,
},
)
.unwrap()
}
/// Save the rendered template to a file, and print a message to the user.
fn save_manifest_file(path: &Path, content: String) -> miette::Result<()> {
fs_err::write(path, content).into_diagnostic()?;
eprintln!(
"{}Created {}",
console::style(console::Emoji("✔ ", "")).green(),
// Canonicalize the path to make it more readable, but if it fails just use the path as is.
dunce::canonicalize(path)
.unwrap_or(path.to_path_buf())
.display()
);
Ok(())
}
fn get_name_from_dir(path: &Path) -> miette::Result<String> {
Ok(path
.file_name()
.ok_or(miette::miette!(
"Cannot get file or directory name from the path: {}",
path.to_string_lossy()
))?
.to_string_lossy()
.to_string())
}
// When the specific template is not in the file or the file does not exist.
// Make the file and append the template to the file.
fn create_or_append_file(path: &Path, template: &str) -> std::io::Result<()> {
let file = fs_err::read_to_string(path).unwrap_or_default();
if !file.contains(template) {
fs::OpenOptions::new()
.append(true)
.create(true)
.open(path)?
.write_all(template.as_bytes())?;
}
Ok(())
}
fn get_dir(path: PathBuf) -> Result<PathBuf, Error> {
if path.components().count() == 1 {
Ok(std::env::current_dir().unwrap_or_default().join(path))
} else {
path.canonicalize().map_err(|e| match e.kind() {
ErrorKind::NotFound => Error::new(
ErrorKind::NotFound,
format!(
"Cannot find '{}' please make sure the folder is reachable",
path.to_string_lossy()
),
),
_ => Error::new(
ErrorKind::InvalidInput,
"Cannot canonicalize the given path",
),
})
}
}
#[cfg(test)]
mod tests {
use std::{
io::Read,
path::{Path, PathBuf},
};
use tempfile::tempdir;
use super::*;
use crate::cli::init::get_dir;
#[test]
fn test_get_name() {
assert_eq!(
get_dir(PathBuf::from(".")).unwrap(),
std::env::current_dir().unwrap()
);
assert_eq!(
get_dir(PathBuf::from("test_folder")).unwrap(),
std::env::current_dir().unwrap().join("test_folder")
);
assert_eq!(
get_dir(std::env::current_dir().unwrap()).unwrap(),
std::env::current_dir().unwrap().canonicalize().unwrap()
);
}
#[test]
fn test_get_name_panic() {
match get_dir(PathBuf::from("invalid/path")) {
Ok(_) => panic!("Expected error, but got OK"),
Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound),
}
}
#[test]
fn test_create_or_append_file() {
let dir = tempdir().unwrap();
let file_path = dir.path().join("test_file.txt");
let template = "Test Template";
fn read_file_content(path: &Path) -> String {
let mut file = fs_err::File::open(path).unwrap();
let mut content = String::new();
file.read_to_string(&mut content).unwrap();
content
}
// Scenario 1: File does not exist.
create_or_append_file(&file_path, template).unwrap();
assert_eq!(read_file_content(&file_path), template);
// Scenario 2: File exists but doesn't contain the template.
create_or_append_file(&file_path, "New Content").unwrap();
assert!(read_file_content(&file_path).contains(template));
assert!(read_file_content(&file_path).contains("New Content"));
// Scenario 3: File exists and already contains the template.
let original_content = read_file_content(&file_path);
create_or_append_file(&file_path, template).unwrap();
assert_eq!(read_file_content(&file_path), original_content);
// Scenario 4: Path is a folder not a file, give an error.
assert!(create_or_append_file(dir.path(), template).is_err());
dir.close().unwrap();
}
#[test]
fn test_multiple_format_values() {
let test_cases = vec![
("pixi", ManifestFormat::Pixi),
("PiXi", ManifestFormat::Pixi),
("PIXI", ManifestFormat::Pixi),
("pyproject", ManifestFormat::Pyproject),
("PyPrOjEcT", ManifestFormat::Pyproject),
("PYPROJECT", ManifestFormat::Pyproject),
];
for (input, expected) in test_cases {
let args = Args::try_parse_from(["init", "--format", input]).unwrap();
assert_eq!(args.format, Some(expected));
}
}
#[test]
fn test_multiple_scm_values() {
let test_cases = vec![
("github", GitAttributes::Github),
("GiThUb", GitAttributes::Github),
("GITHUB", GitAttributes::Github),
("Github", GitAttributes::Github),
("gitlab", GitAttributes::Gitlab),
("GiTlAb", GitAttributes::Gitlab),
("GITLAB", GitAttributes::Gitlab),
("codeberg", GitAttributes::Codeberg),
("CoDeBeRg", GitAttributes::Codeberg),
("CODEBERG", GitAttributes::Codeberg),
];
for (input, expected) in test_cases {
let args = Args::try_parse_from(["init", "--scm", input]).unwrap();
assert_eq!(args.scm, Some(expected));
}
}
#[test]
fn test_invalid_scm_values() {
let invalid_values = vec!["invalid", "", "git", "bitbucket", "mercurial", "svn"];
for value in invalid_values {
let result = Args::try_parse_from(["init", "--scm", value]);
assert!(
result.is_err(),
"Expected error for invalid SCM value '{}', but got success",
value
);
}
}
}