wash-cli 0.6.4

wasmcloud Shell (wash) CLI tool
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
// This file is copied from git.rs from cargo-generate
//   source: https://github.com/cargo-generate/cargo-generate
//   version: 0.9.0
//   license: MIT/Apache-2.0
//
use crate::generate::{any_msg, copy_dir_all, emoji};
use anyhow::{Context, Result};
use cargo::core::GitReference;
use console::style;
use git2::{
    build::RepoBuilder,
    ErrorCode, {Cred, FetchOptions, ProxyOptions, RemoteCallbacks, Repository},
};
use log::warn;
use remove_dir_all::remove_dir_all;
use std::{
    borrow::Cow,
    ops::{Add, Deref, Sub},
    path::{Path, PathBuf},
    thread::sleep,
    time::Duration,
};

#[derive(Debug, PartialEq)]
enum RepoKind {
    LocalFolder,
    RemoteHttp,
    RemoteHttps,
    RemoteSsh,
    Invalid,
}

pub(crate) struct GitConfig<'a> {
    remote: Cow<'a, str>,
    branch: GitReference,
    kind: RepoKind,
    identity: Option<PathBuf>,
}

impl<'a> GitConfig<'a> {
    /// Creates a new `GitConfig` by parsing `git` as a URL or a local path.
    pub fn new(
        git: Cow<'a, str>,
        branch: Option<String>,
        identity: Option<PathBuf>,
    ) -> Result<Self> {
        let (remote, kind) = match determine_repo_kind(git.as_ref()) {
            RepoKind::Invalid => {
                return Err(any_msg("Invalid git remote", &git));
            }
            RepoKind::LocalFolder => {
                let full_path = canonicalize_path(git.deref().as_ref())?;
                if !full_path.exists() {
                    return Err(any_msg("The git remote does not exist", &git));
                }
                (
                    full_path.display().to_string().into(),
                    RepoKind::LocalFolder,
                )
            }
            k => (git, k),
        };

        Ok(GitConfig {
            remote,
            kind,
            identity,
            branch: branch
                .map(GitReference::Branch)
                .unwrap_or(GitReference::DefaultBranch),
        })
    }

    /// Creates a new `GitConfig`, first with `new` and then as a GitHub `owner/repo` remote, like
    /// [hub].
    ///
    /// [hub]: https://github.com/github/hub
    pub fn new_abbr(
        git: Cow<'a, str>,
        branch: Option<String>,
        identity: Option<PathBuf>,
    ) -> Result<Self> {
        Self::new(git.clone(), branch.clone(), identity.clone()).or_else(|_| {
            let full_remote = format!("https://github.com/{}.git", &git);
            Self::new(full_remote.into(), branch, identity)
        })
    }
}

pub(crate) fn create(project_dir: &Path, args: GitConfig) -> Result<String> {
    let branch = git_clone_all(project_dir, args)?;
    remove_history(project_dir, None)?;

    Ok(branch)
}

fn canonicalize_path(p: &Path) -> Result<PathBuf> {
    let p = if p.to_str().unwrap().starts_with("~/") {
        home()?.join(p.strip_prefix("~/").unwrap())
    } else {
        p.to_path_buf()
    };

    p.canonicalize().context("path does not exist")
}

#[test]
fn should_canonicalize() {
    #[cfg(target_os = "macos")]
    assert!(canonicalize_path(&PathBuf::from("../"))
        .unwrap()
        .starts_with("/Users/"));
    #[cfg(target_os = "linux")]
    assert_eq!(
        canonicalize_path(&PathBuf::from("../")).ok(),
        std::env::current_dir()
            .unwrap()
            .parent()
            .map(|p| p.to_path_buf())
    );
    #[cfg(windows)]
    assert!(canonicalize_path(&PathBuf::from("../"))
        .unwrap()
        // not a bug, a feature:
        // https://stackoverflow.com/questions/41233684/why-does-my-canonicalized-path-get-prefixed-with
        .to_str()
        .unwrap()
        .starts_with("\\\\?\\"));
}

/// takes care of `~/` paths, defaults to `$HOME/.ssh/id_rsa` and resolves symlinks.
fn get_private_key_path(identity: Option<PathBuf>) -> Result<PathBuf> {
    let private_key = identity.unwrap_or(home()?.join(".ssh/id_rsa"));

    canonicalize_path(&private_key).context("private key path was incorrect")
}

fn git_ssh_credentials_callback<'a>(identity: Option<PathBuf>) -> Result<RemoteCallbacks<'a>> {
    let private_key = get_private_key_path(identity)?;
    println!(
        "{} {} `{}` {}",
        emoji::INFO,
        style("Using private key:").bold(),
        style(pretty_path(&private_key)?).bold().yellow(),
        style("for git-ssh checkout").bold()
    );
    let mut cb = RemoteCallbacks::new();
    cb.credentials(
        move |_url, username_from_url: Option<&str>, _allowed_types| {
            Cred::ssh_key(username_from_url.unwrap_or("git"), None, &private_key, None)
        },
    );
    Ok(cb)
}

/// home path wrapper
fn home() -> Result<PathBuf> {
    canonicalize_path(&dirs::home_dir().context("$HOME was not set")?)
}

#[test]
fn should_pretty_path() {
    let p = pretty_path(home().unwrap().as_path().join(".cargo").as_path()).unwrap();
    #[cfg(unix)]
    assert_eq!(p, "$HOME/.cargo");
    #[cfg(windows)]
    assert_eq!(p, "%userprofile%\\.cargo");
}

/// prevents from long stupid paths, and replace the home path by the literal `$HOME`
fn pretty_path(a: &Path) -> Result<String> {
    #[cfg(unix)]
    let home_var = "$HOME";
    #[cfg(windows)]
    let home_var = "%userprofile%";
    Ok(a.display()
        .to_string()
        .replace(&home()?.display().to_string(), home_var))
}

/// thanks to @extrawurst for pointing this out
/// <https://github.com/extrawurst/gitui/blob/master/asyncgit/src/sync/branch/mod.rs#L38>
fn get_branch_name_repo(repo: &Repository) -> Result<String> {
    let iter = repo.branches(None)?;

    for b in iter {
        let b = b?;

        if b.0.is_head() {
            let name = b.0.name()?.unwrap_or("");
            return Ok(name.into());
        }
    }

    anyhow::bail!("A repo has no Head")
}

fn init_all_submodules(repo: &Repository) -> Result<()> {
    for mut sub in repo.submodules().unwrap() {
        sub.update(true, None)?;
    }

    Ok(())
}

fn git_clone_all(project_dir: &Path, args: GitConfig) -> Result<String> {
    let mut builder = RepoBuilder::new();
    if let GitReference::Branch(branch_name) = &args.branch {
        builder.branch(branch_name.as_str());
    }

    let mut fo = FetchOptions::new();
    match args.kind {
        RepoKind::LocalFolder => {}
        RepoKind::RemoteHttp | RepoKind::RemoteHttps => {
            let mut proxy = ProxyOptions::new();
            proxy.auto();
            fo.proxy_options(proxy);
        }
        RepoKind::RemoteSsh => {
            let callbacks = git_ssh_credentials_callback(args.identity)?;
            fo.remote_callbacks(callbacks);
        }
        RepoKind::Invalid => {
            unreachable!()
        }
    }
    builder.fetch_options(fo);

    match builder.clone(args.remote.as_ref(), project_dir) {
        Ok(repo) => {
            let branch = get_branch_name_repo(&repo)?;
            init_all_submodules(&repo)?;
            Ok(branch)
        }
        Err(e) => {
            if e.code() != ErrorCode::NotFound {
                return Err(e.into());
            }

            let path = Path::new(&*args.remote);
            if !path.exists() || !path.is_dir() {
                return Err(e.into());
            }

            warn!("Template does not seem to be a git repository, using as a plain folder");
            copy_dir_all(path, project_dir)?;
            Ok("".to_string())
        }
    }
}

fn remove_history(project_dir: &Path, attempt: Option<u8>) -> Result<()> {
    let git_dir = project_dir.join(".git");
    if git_dir.exists() && git_dir.is_dir() {
        if let Err(e) = remove_dir_all(git_dir) {
            // see https://github.com/cargo-generate/cargo-generate/issues/375
            if e.to_string().contains(
                "The process cannot access the file because it is being used by another process.",
            ) {
                let attempt = attempt.unwrap_or(1);
                if attempt == 5 {
                    warn!("cargo-generate was not able to delete the git history after {} retries. Please delete the `.git` sub-folder manually", attempt);
                    return Ok(());
                }
                let wait_for = Duration::from_secs(2_u64.pow(attempt.sub(1) as u32));
                warn!("Git history cleanup failed with a windows process blocking error. [Retry in {:?}]", wait_for);
                sleep(wait_for);
                remove_history(project_dir, Some(attempt.add(1)))?
            }
        }
    }
    Ok(())
}

/* may add this in the future
pub fn init(project_dir: &Path, branch: &str) -> Result<Repository> {
    Repository::discover(project_dir).or_else(|_| {
        let mut opts = RepositoryInitOptions::new();
        opts.bare(false);
        opts.initial_head(branch);
        Repository::init_opts(project_dir, &opts).context("Couldn't init new repository")
    })
}
*/

/// determines what kind of repository we got
fn determine_repo_kind(remote_url: &str) -> RepoKind {
    if remote_url.starts_with("git@") {
        RepoKind::RemoteSsh
    } else if remote_url.starts_with("http://") {
        RepoKind::RemoteHttp
    } else if remote_url.starts_with("https://") {
        RepoKind::RemoteHttps
    } else if Path::new(remote_url).exists() {
        RepoKind::LocalFolder
    } else {
        RepoKind::Invalid
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use reqwest::Url;
    use std::env::current_dir;

    const REPO_URL: &str = "https://github.com/cargo-generate/cargo-generate.git";
    const REPO_URL_SSH: &str = "git@github.com:cargo-generate/cargo-generate.git";

    #[test]
    fn should_determine_repo_kind() {
        for (u, k) in &[
            (REPO_URL, RepoKind::RemoteHttps),
            (
                "http://github.com/cargo-generate/cargo-generate.git",
                RepoKind::RemoteHttp,
            ),
            (REPO_URL_SSH, RepoKind::RemoteSsh),
            ("./", RepoKind::LocalFolder),
            ("ftp://foobar.bak", RepoKind::Invalid),
        ] {
            let kind = determine_repo_kind(u);
            assert_eq!(&kind, k, "{} is not a {:?}", u, k);
        }
    }

    #[test]
    fn should_not_fail_for_ssh_remote_urls() {
        let config = GitConfig::new(REPO_URL_SSH.into(), None, None).unwrap();
        assert_eq!(config.kind, RepoKind::RemoteSsh);
    }

    #[test]
    #[should_panic(expected = "Invalid git remote")]
    fn should_fail_for_non_existing_local_path() {
        GitConfig::new("aslkdgjlaskjdglskj".into(), None, None).unwrap();
    }

    #[test]
    fn should_support_a_local_relative_path() {
        let remote: String = GitConfig::new("src".into(), None, None)
            .unwrap()
            .remote
            .into();
        #[cfg(unix)]
        assert!(
            remote.ends_with("/src"),
            "remote {} ends with /src",
            &remote
        );
        #[cfg(windows)]
        assert!(
            remote.ends_with("\\src"),
            "remote {} ends with \\src",
            &remote
        );

        #[cfg(unix)]
        assert!(remote.starts_with('/'), "remote {} starts with /", &remote);
        #[cfg(windows)]
        assert!(
            remote.starts_with("\\\\?\\"),
            "remote {} starts with \\\\?\\",
            &remote
        );
    }

    #[test]
    fn should_support_a_local_absolute_path() {
        // Absolute path.
        // If this fails because you cloned this repository into a non-UTF-8 directory... all
        // I can say is you probably had it comin'.
        let remote: String = GitConfig::new(
            current_dir().unwrap().display().to_string().into(),
            None,
            None,
        )
        .unwrap()
        .remote
        .into();
        #[cfg(unix)]
        assert!(remote.starts_with('/'), "remote {} starts with /", &remote);
        #[cfg(windows)]
        assert!(
            remote.starts_with("\\\\?\\"),
            "remote {} starts with \\\\?\\ then the drive letter",
            &remote
        );
    }

    #[test]
    fn should_test_happy_path() {
        // Remote HTTPS URL.
        let cfg = GitConfig::new(REPO_URL.into(), Some("main".to_owned()), None).unwrap();

        assert_eq!(cfg.remote.as_ref(), Url::parse(REPO_URL).unwrap().as_str());
        assert_eq!(cfg.branch, GitReference::Branch("main".to_owned()));
    }

    #[test]
    fn should_support_abbreviated_repository_short_urls_like() {
        assert_eq!(
            GitConfig::new_abbr("cargo-generate/cargo-generate".into(), None, None)
                .unwrap()
                .remote
                .as_ref(),
            Url::parse(REPO_URL).unwrap().as_str()
        );
    }
}