codebase 0.11.0

Manage your codebase like a boss!
Documentation
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

use git2::build::RepoBuilder;
use walkdir::WalkDir;

use crate::manifest::Manifest;
pub use crate::project::Project;
use crate::project::ProjectOpts;
use crate::{archetype, git_util, manifest};

const DOT_CODEBASE_DIR: &str = ".codebase";
const DEFAULT_REMOTE: &str = "origin";

const README_MD: &str = r#"
# dot-codebase

This repository contains a custom .codebase configuration.

See [this repository](https://github.com/codebase-rs/codebase) for more details.

## How to use it

One can restore this codebase by issuing the following command:

```sh
codebase clone {{REMOTE}} Codebase
```
"#;

pub struct Codebase {
    // Full path where the codebase is located
    // f.e `/home/creekorful/Documents/Codebase`
    root_path: PathBuf,
    // Relative path within the codebase
    // f.e `/` or `Contributing/Debian`
    local_path: PathBuf,
    // Full path to the `.codebase-config` directory
    // f.e /home/creekorful/.codebase-config
    config_path: PathBuf,
    // The .codebase Git repository
    repo: git2::Repository,
}

impl Codebase {
    fn new<A: AsRef<Path>, B: AsRef<Path>, C: AsRef<Path>>(
        root_path: A,
        local_path: B,
        config_path: C,
        repo: git2::Repository,
    ) -> Self {
        Codebase {
            root_path: root_path.as_ref().to_path_buf(),
            local_path: local_path.as_ref().to_path_buf(),
            config_path: config_path.as_ref().to_path_buf(),
            repo,
        }
    }

    /// Initialize a new codebase into given directory
    ///
    /// # Arguments
    ///
    /// * `directory` - the directory where the codebase should be initialized
    /// * `remote` - the optional remote to be set for remote saving
    /// * `import` - if true, import all found Git repositories into newly created codebase
    /// * `config_dir` - path to the .codebase-config directory
    pub fn init<A: AsRef<Path>, B: AsRef<Path>>(
        directory: A,
        remote: &Option<&str>,
        import: bool,
        config_dir: B,
    ) -> anyhow::Result<Codebase> {
        if Codebase::exists(&directory) {
            return Err(anyhow::anyhow!(format!(
                "A codebase already exists at {}",
                directory.as_ref().display()
            )));
        }

        // Create .codebase-config if needed
        fs::create_dir_all(&config_dir)?;

        let mut manifest = Manifest::new();

        // If we want to import existing Git repositories & target folder exist
        if import && directory.as_ref().exists() {
            for entry in WalkDir::new(&directory)
                .into_iter()
                .filter_map(Result::ok)
                .filter(|e| e.file_name().to_str().unwrap() == ".git")
            {
                let path: &Path = entry.path().parent().unwrap();
                let repo = git2::Repository::open(path)?;
                let local_path = path.strip_prefix(&directory)?;

                manifest.add_project(local_path, Project::from(repo))?;
            }
        }

        // Create any missing directories
        fs::create_dir_all(&directory)?;

        // Create .codebase git directory
        let conf_dir = directory.as_ref().join(DOT_CODEBASE_DIR);
        let repo = git2::Repository::init(&conf_dir)?;

        // If a remote is provided, set as origin
        if let Some(value) = remote {
            repo.remote(DEFAULT_REMOTE, value)?;
        }

        // Create initial empty manifest.json
        let codebase = Codebase::new(directory, PathBuf::new(), config_dir, repo);
        codebase.write_manifest(&manifest)?;

        // Create default README.md
        let mut file = fs::File::create(conf_dir.join("README.md"))?;
        file.write_all(
            README_MD
                .replace("{{REMOTE}}", remote.unwrap_or("YOUR_REMOTE"))
                .as_bytes(),
        )?;

        // ... And initial commit!
        git_util::commit_all_changes(&codebase.repo, "Initial commit")?;

        Ok(codebase)
    }

    /// Clone a remote codebase into given directory
    ///
    /// # Arguments
    ///
    /// * `directory` - the directory where the codebase should be cloned
    /// * `remote` - the remote where the codebase is saved
    /// * `callback` - callback to get cloned status progress
    /// * `config_dir` - path to the .codebase-config directory
    pub fn clone<'a, A: AsRef<Path>, B: AsRef<Path>>(
        directory: A,
        remote: &str,
        callback: impl Fn(&str, &Project) + 'a,
        config_dir: B,
    ) -> anyhow::Result<Codebase> {
        if Codebase::exists(&directory) {
            return Err(anyhow::anyhow!(format!(
                "A codebase already exists at {}",
                directory.as_ref().display()
            )));
        }

        // Create .codebase-config if needed
        fs::create_dir_all(&config_dir)?;

        // Create any missing directories
        fs::create_dir_all(&directory)?;

        // Create an authentication callback to allow pulling trough SSH
        let mut callbacks = git2::RemoteCallbacks::new();
        callbacks.credentials(|_url, username_from_url, _allowed_types| {
            git_util::get_ssh_key(&username_from_url)
        });

        let mut opts = git2::FetchOptions::new();
        opts.remote_callbacks(callbacks);

        let mut repo_builder = RepoBuilder::new();
        repo_builder.fetch_options(opts);

        let dot_codebase = directory.as_ref().join(DOT_CODEBASE_DIR);
        let repo = repo_builder.clone(&remote, &dot_codebase)?;

        let codebase = Codebase::new(&directory, &PathBuf::new(), config_dir, repo);

        // Restore previously installed projects
        let manifest = codebase.read_manifest()?;
        for (path, project) in manifest.projects.iter() {
            codebase.install_project(
                &path,
                &project.remote,
                &ProjectOpts::from(project.clone()),
            )?;
            callback(&path, &project);
        }

        Ok(codebase)
    }

    /// Open codebase located at given directory
    ///
    /// # Arguments
    ///
    /// * `directory` - the directory where the codebase is located
    /// * `config_dir` - path to the .codebase-config directory
    pub fn open<A: AsRef<Path>, B: AsRef<Path>>(
        directory: A,
        config_dir: B,
    ) -> anyhow::Result<Codebase> {
        // Search for .codebase in current & parent directories
        let root_dir = directory
            .as_ref()
            .ancestors()
            .find(|path| Codebase::exists(&path))
            .map(|path| path.to_path_buf());

        if root_dir.is_none() {
            return Err(anyhow::anyhow!(format!(
                "No codebase found at {}",
                directory.as_ref().display()
            )));
        }

        // Create .codebase-config if needed
        fs::create_dir_all(&config_dir)?;

        let root_dir = root_dir.unwrap();
        let config_repo = git2::Repository::open(root_dir.join(DOT_CODEBASE_DIR))?;
        let local_path = directory.as_ref().strip_prefix(&root_dir)?.to_path_buf();

        Ok(Codebase::new(root_dir, local_path, config_dir, config_repo))
    }

    /// Determinate if there is an existing codebase located at given directory
    ///
    /// # Arguments
    ///
    /// * `directory` - the directory that should be checked
    pub fn exists<P: AsRef<Path>>(directory: P) -> bool {
        let config_dir = directory.as_ref().join(DOT_CODEBASE_DIR);
        config_dir.exists()
    }

    /// Add project to the codebase
    ///
    /// # Arguments
    ///
    /// * `directory` - the directory where the project should be cloned.
    /// Default to project name if not provided.
    /// * `remote` - the repository remote
    /// * `options` - the project options
    pub fn add_project<P: AsRef<Path>>(
        &self,
        directory: &Option<P>,
        remote: &str,
        options: &ProjectOpts,
    ) -> anyhow::Result<Project> {
        let project_name = get_repo_name(remote)?;
        let mut project_path = self.get_local_path();

        if directory.is_some() {
            project_path = project_path.join(directory.as_ref().unwrap());
        }

        project_path = project_path.join(project_name);

        let project = self.install_project(&project_path, &remote, &options)?;

        // Add project to the manifest
        let mut manifest = self.read_manifest()?;
        manifest.add_project(&project_path, project.clone())?;
        self.write_manifest(&manifest)?;

        // Everything looks good, commit changes
        git_util::commit_all_changes(
            &self.repo,
            &format!(
                "Add project {} in {}",
                &project.remote,
                project_path.display()
            ),
        )?;

        Ok(project)
    }

    /// Remove project from the codebase
    ///
    /// # Arguments
    ///
    /// * `directory` - the project directory
    /// * `remove_from_disk` - if true remove from disk
    pub fn remove_project<P: AsRef<Path>>(
        &self,
        directory: P,
        remove_from_disk: bool,
    ) -> anyhow::Result<()> {
        // Determinate if project exist
        let project = self.find_project(&directory)?;

        if project.is_none() {
            return Err(anyhow::anyhow!(format!(
                "No project with path `{}` found",
                directory.as_ref().display()
            )));
        }

        // If exist, remove it from the manifest
        let mut manifest = self.read_manifest()?;
        manifest.remove_project(&directory)?;
        self.write_manifest(&manifest)?;

        // If remove_from_disk flag is provided, remove from disk too
        if remove_from_disk {
            let path = self.root_path.clone().join(&directory);
            fs::remove_dir_all(&path)?;
        }

        // Everything looks good, commit changes
        git_util::commit_all_changes(
            &self.repo,
            &format!("Remove project {}", project.unwrap().remote),
        )?;

        Ok(())
    }

    /// Read the codebase manifest
    pub fn read_manifest(&self) -> anyhow::Result<Manifest> {
        let manifest_path = self
            .root_path
            .clone()
            .join(DOT_CODEBASE_DIR)
            .join(manifest::MANIFEST_FILE);

        Manifest::read_file(&manifest_path)
    }

    /// Push the change to the configured remote
    pub fn push(&self) -> anyhow::Result<()> {
        // Create an authentication callback to allow pushing trough SSH
        let mut callbacks = git2::RemoteCallbacks::new();
        callbacks.credentials(|_url, username_from_url, _allowed_types| {
            git_util::get_ssh_key(&username_from_url)
        });

        let mut opts = git2::PushOptions::new();
        opts.remote_callbacks(callbacks);

        // Push master refspec to the default remote
        let mut remote = self.repo.find_remote(DEFAULT_REMOTE)?;
        remote.push(&["refs/heads/master"], Some(&mut opts))?;
        Ok(())
    }

    /// Pull the change from the configured remote
    ///
    /// # Arguments
    ///
    /// * `remove_from_disk` - if true remove from disk
    pub fn pull(&self, remove_from_disk: bool) -> anyhow::Result<(Vec<Project>, Vec<Project>)> {
        let old_manifest = self.read_manifest()?;

        // execute `git pull`
        git_util::pull(&self.repo, DEFAULT_REMOTE, "master")?;

        let new_manifest = self.read_manifest()?;

        let mut add_projects: Vec<Project> = Vec::new();
        let mut rm_projects: Vec<Project> = Vec::new();

        // Collect new/added projects
        for (path, project) in &new_manifest.projects {
            if !old_manifest.projects.contains_key(path) {
                add_projects.push(project.clone());
                self.install_project(&path, &project.remote, &ProjectOpts::from(project.clone()))?;
            }

            // No matter what we should reconfigure the Git repository using new configuration
            let mut project = project.clone();
            let repo = git2::Repository::open(self.root_path.clone().join(path))?;
            project.configure(
                &repo,
                &ProjectOpts::from(project.clone()),
                self.config_path.clone(),
            )?;
        }

        // Collect old/removed projects
        for (path, project) in &old_manifest.projects {
            if !new_manifest.projects.contains_key(path) {
                rm_projects.push(project.clone());

                if remove_from_disk {
                    let path = self.root_path.clone().join(&path);
                    fs::remove_dir_all(path)?;
                }
            }
        }

        Ok((add_projects, rm_projects))
    }

    /// Update all projects within the codebase
    ///
    /// # Arguments
    /// * `callback` - callback to get cloned status progress
    pub fn update_projects<'a>(&self, callback: impl Fn(&Project) + 'a) -> anyhow::Result<()> {
        let manifest = self.read_manifest()?;

        for (path, project) in manifest.projects {
            let path = self.root_path.clone().join(&path);
            let repo = git2::Repository::open(path)?;

            git_util::pull(&repo, DEFAULT_REMOTE, &project.branch)?;

            callback(&project);
        }

        Ok(())
    }

    /// Change the configuration of the project at path
    ///
    /// # Arguments
    /// * `directory` - the directory where the project is
    /// * `options` - the project options
    pub fn config_project<P: AsRef<Path>>(
        &self,
        directory: P,
        options: &ProjectOpts,
    ) -> anyhow::Result<Project> {
        let mut manifest = self.read_manifest()?;

        let directory = self.get_local_path().join(&directory);
        let project = manifest.find_project(&directory);

        if project.is_none() {
            return Err(anyhow::anyhow!(format!(
                "No project with path `{}` found",
                directory.display()
            )));
        }

        let mut project = project.unwrap();

        let repo = git2::Repository::open(self.root_path.clone().join(&directory))?;
        project.configure(&repo, options, self.config_path.clone())?;

        manifest.update_project(&directory, project.clone())?;

        self.write_manifest(&manifest)?;

        git_util::commit_all_changes(&self.repo, &format!("Configure project {}", project.remote))?;

        Ok(project)
    }

    /// Move project from old_directory to new_directory
    ///
    /// # Arguments
    ///
    /// * `src_directory` - project previous directory
    /// * `dst_directory` - project new directory
    pub fn move_project<P: AsRef<Path>>(
        &self,
        src_directory: P,
        dst_directory: P,
    ) -> anyhow::Result<()> {
        let src_directory = self.get_local_path().join(&src_directory);
        let dst_directory = self.get_local_path().join(&dst_directory);

        let project = self.find_project(&src_directory)?;

        if project.is_none() {
            return Err(anyhow::anyhow!(format!(
                "No project with path `{}` found",
                src_directory.display()
            )));
        }

        // Move project to new path
        fs::create_dir_all(&self.root_path.join(&dst_directory))?;
        fs::rename(
            self.root_path.join(&src_directory),
            self.root_path.join(&dst_directory),
        )?;

        // Update manifest
        let mut manifest = self.read_manifest()?;
        manifest.move_project(&src_directory, &dst_directory)?;
        self.write_manifest(&manifest)?;

        let project = project.unwrap();
        git_util::commit_all_changes(
            &self.repo,
            &format!(
                "Move project {} from {} to {}",
                project.remote,
                src_directory.display(),
                dst_directory.display()
            ),
        )?;

        Ok(())
    }

    /// Create a new project inside the codebase
    ///
    /// # Arguments
    /// * `directory` - the directory where the project will be created
    /// * `remote` - the repository remote
    /// * `options` - the project options
    /// * `archetype_name` - the name of the archetype to use to create project
    /// * `archetype_config` - the archetype configuration
    pub fn create_project<P: AsRef<Path>>(
        &self,
        directory: P,
        remote: &str,
        options: &ProjectOpts,
        archetype_name: &Option<&str>,
        archetype_config: &BTreeMap<String, String>,
    ) -> anyhow::Result<(String, Project)> {
        let directory = self.get_local_path().join(directory);

        if self.find_project(&directory)?.is_some() {
            return Err(anyhow::anyhow!(format!(
                "A project already exist at {}",
                directory.display()
            )));
        }

        let project_path = self.root_path.clone().join(&directory);

        // If there is parent directories create them
        if let Some(parents_dir) = project_path.parent() {
            fs::create_dir_all(parents_dir)?;
        }

        // If an archetype is provided, find it
        if let Some(archetype_name) = archetype_name {
            let project_name = directory.file_name().unwrap().to_str().unwrap();

            // Populate default variables here
            let mut archetype_config = archetype_config.clone();
            archetype_config.insert("NAME".to_string(), project_name.to_string());

            let parent_directory = project_path
                .parent()
                .unwrap_or_else(|| self.root_path.as_path());

            archetype::execute(
                &archetype_name,
                &archetype_config,
                &parent_directory,
                self.config_path.clone(),
            )?;
        }

        // Project should be created right now, create the git repository & set remote
        let branch = options
            .branch
            .clone()
            .unwrap_or_else(|| "master".to_string());
        let mut opts = git2::RepositoryInitOptions::new();
        opts.origin_url(remote);
        opts.initial_head(&format!("refs/heads/{}", branch));

        let repo = git2::Repository::init_opts(&project_path, &opts)?;
        git_util::commit_all_changes(&repo, "Initial commit")?;

        // Configure project
        let options = ProjectOpts {
            branch: Some(branch),
            configuration: options.configuration.clone(),
            hook: options.hook.clone(),
        };

        let mut project = Project::empty(remote);
        project.configure(&repo, &options, self.config_path.clone())?;

        let mut manifest = self.read_manifest()?;
        manifest.add_project(&directory, project.clone())?;
        self.write_manifest(&manifest)?;

        git_util::commit_all_changes(
            &self.repo,
            &format!(
                "Create project {} in {}",
                project.remote,
                directory.display()
            ),
        )?;

        Ok((directory.to_str().unwrap().to_string(), project))
    }

    /// Retrieve codebase local path.
    /// f.e the path your are inside the codebase
    pub fn local_path(&self) -> PathBuf {
        self.local_path.clone()
    }

    /// Write given manifest to the codebase configuration directory
    ///
    /// # Arguments
    ///
    /// * `manifest` - manifest to be written
    fn write_manifest(&self, manifest: &Manifest) -> anyhow::Result<()> {
        let manifest_path = self
            .root_path
            .clone()
            .join(DOT_CODEBASE_DIR)
            .join(manifest::MANIFEST_FILE);

        manifest.write_file(&manifest_path)
    }

    /// Install given project in the codebase
    ///
    /// # Arguments
    ///
    /// * `directory` - the project install directory
    /// * `remote` - the repository remote
    /// * `options` - the project options
    fn install_project<P: AsRef<Path>>(
        &self,
        directory: P,
        remote: &str,
        options: &ProjectOpts,
    ) -> anyhow::Result<Project> {
        let project_path = self.root_path.clone().join(&directory);

        // Create any missing directories
        fs::create_dir_all(&project_path)?;

        // Create an authentication callback to allow pulling trough SSH
        let mut callbacks = git2::RemoteCallbacks::new();
        callbacks.credentials(|_url, username_from_url, _allowed_types| {
            git_util::get_ssh_key(&username_from_url)
        });

        let mut opts = git2::FetchOptions::new();
        opts.remote_callbacks(callbacks);

        let mut repo_builder = RepoBuilder::new();
        repo_builder.fetch_options(opts);

        // Use provided branch if any
        if let Some(branch) = &options.branch {
            repo_builder.branch(branch);
        }

        // Clone the project in given path
        let repo = repo_builder.clone(remote, &project_path)?;

        // Get active branch name
        let branch = options.branch.clone().or_else(|| {
            if let Some(branch) = git_util::get_active_branch(&repo).unwrap() {
                return Some(branch);
            }

            // There is no active branch at this time, it is time to create a unborn one
            repo.set_head("refs/heads/master").unwrap();
            Some("master".to_string())
        });

        if branch.is_none() {
            return Err(anyhow::anyhow!("Unable to retrieve active branch name"));
        }

        // Configure project
        let options = ProjectOpts {
            branch,
            configuration: options.configuration.clone(),
            hook: options.hook.clone(),
        };
        let mut project = Project::empty(remote);
        project.configure(&repo, &options, self.config_path.clone())?;

        Ok(project)
    }

    /// Find project located at given path
    ///
    /// # Arguments
    /// * `directory` - project directory
    fn find_project<P: AsRef<Path>>(&self, directory: P) -> anyhow::Result<Option<Project>> {
        let manifest = self.read_manifest()?;
        Ok(manifest.find_project(directory))
    }

    fn get_local_path(&self) -> PathBuf {
        self.local_path.clone() // TODO
    }
}

/// Get repo name from given repo URI
///
/// # Arguments
///
/// * `remote` - the repo remote uri
fn get_repo_name(remote: &str) -> anyhow::Result<String> {
    let parts: Vec<&str> = remote.split('/').collect();
    let repo_name = parts
        .last()
        .ok_or_else(|| anyhow::anyhow!("Malformed repo URI"))?;
    Ok(repo_name.replace(".git", ""))
}

#[cfg(test)]
mod tests {
    use crate::codebase::get_repo_name;

    #[test]
    fn test_get_repo_name() {
        assert_eq!(
            get_repo_name("https://github.com/codebase-rs/codebase.git").unwrap(),
            "codebase"
        );
        assert_eq!(
            get_repo_name("git@github.com:codebase-rs/codebase.git").unwrap(),
            "codebase"
        );
    }
}