Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(clone): turbo clone #9904

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/turborepo-lib/src/cli/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ pub enum Error {
#[error(transparent)]
Boundaries(#[from] crate::boundaries::Error),
#[error(transparent)]
Clone(#[from] crate::commands::clone::Error),
#[error(transparent)]
Path(#[from] turbopath::PathError),
#[error(transparent)]
#[diagnostic(transparent)]
Expand Down
28 changes: 25 additions & 3 deletions crates/turborepo-lib/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ use turborepo_ui::{ColorConfig, GREY};
use crate::{
cli::error::print_potential_tasks,
commands::{
bin, boundaries, config, daemon, generate, info, link, login, logout, ls, prune, query,
run, scan, telemetry, unlink, CommandBase,
bin, boundaries, clone, config, daemon, generate, info, link, login, logout, ls, prune,
query, run, scan, telemetry, unlink, CommandBase,
},
get_version,
run::watch::WatchClient,
Expand Down Expand Up @@ -569,6 +569,17 @@ pub enum Command {
#[clap(short = 'F', long, group = "scope-filter-group")]
filter: Vec<String>,
},
#[clap(hide = true)]
Clone {
url: String,
dir: Option<String>,
#[clap(long, conflicts_with = "local")]
ci: bool,
#[clap(long, conflicts_with = "ci")]
local: bool,
#[clap(long)]
depth: Option<usize>,
},
/// Generate the autocompletion script for the specified shell
Completion { shell: Shell },
/// Runs the Turborepo background daemon
Expand Down Expand Up @@ -1274,7 +1285,6 @@ pub async fn run(
};

cli_args.command = Some(command);
cli_args.cwd = Some(repo_root.as_path().to_owned());
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as far as I can tell, we don't actually use the cwd as repo root anywhere. can correct if this isn't true

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a necessary change for this PR? repo_root looks like a bad name since it can get it's value from cli_args.cwd. This value will now no longer be made absolute if it is given as a relative value.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately it is necessary, although I can just save the old cwd instead. We don't want the repo root to be our cwd and in fact, we probably don't want to be in a repo in the first place for turbo clone. This is a pretty big departure from our other commands.


let root_telemetry = GenericEventBuilder::new();
root_telemetry.track_start();
Expand Down Expand Up @@ -1303,6 +1313,18 @@ pub async fn run(

Ok(boundaries::run(base, event).await?)
}
Command::Clone {
url,
dir,
ci,
local,
depth,
} => {
let event = CommandEventBuilder::new("clone").with_parent(&root_telemetry);
event.track_call();

Ok(clone::run(cwd, url, dir.as_deref(), *ci, *local, *depth)?)
}
#[allow(unused_variables)]
Command::Daemon { command, idle_time } => {
let event = CommandEventBuilder::new("daemon").with_parent(&root_telemetry);
Expand Down
53 changes: 53 additions & 0 deletions crates/turborepo-lib/src/commands/clone.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use std::env::current_dir;

use camino::Utf8Path;
use thiserror::Error;
use turbopath::AbsoluteSystemPathBuf;
use turborepo_ci::is_ci;
use turborepo_scm::clone::{CloneMode, Git};

#[derive(Debug, Error)]
pub enum Error {
#[error("path is not valid UTF-8")]
Path(#[from] camino::FromPathBufError),

#[error(transparent)]
Turbopath(#[from] turbopath::PathError),

#[error("failed to clone repository")]
Scm(#[from] turborepo_scm::Error),
}

pub fn run(
cwd: Option<&Utf8Path>,
url: &str,
dir: Option<&str>,
ci: bool,
local: bool,
depth: Option<usize>,
) -> Result<i32, Error> {
// We do *not* want to use the repo root but the actual, literal cwd for clone
let cwd = if let Some(cwd) = cwd {
cwd.to_owned()
} else {
current_dir()
.expect("could not get current directory")
.try_into()?
};
let abs_cwd = AbsoluteSystemPathBuf::from_cwd(cwd)?;

let clone_mode = if ci {
CloneMode::CI
} else if local {
CloneMode::Local
} else if is_ci() {
CloneMode::CI
} else {
CloneMode::Local
};

let git = Git::find()?;
git.clone(url, abs_cwd, dir, None, clone_mode, depth)?;

Ok(0)
}
1 change: 1 addition & 0 deletions crates/turborepo-lib/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use crate::{

pub(crate) mod bin;
pub(crate) mod boundaries;
pub(crate) mod clone;
pub(crate) mod config;
pub(crate) mod daemon;
pub(crate) mod generate;
Expand Down
4 changes: 2 additions & 2 deletions crates/turborepo-lib/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use tokio::{
};
use turbo_updater::check_for_updates;
use turbopath::AbsoluteSystemPathBuf;
use turborepo_scm::Git;
use turborepo_scm::GitRepo;

use crate::{
commands::{
Expand Down Expand Up @@ -157,7 +157,7 @@ impl Diagnostic for GitDaemonDiagnostic {
// get the current setting
let stdout = Stdio::piped();

let Ok(git_path) = Git::find_bin() else {
let Ok(git_path) = GitRepo::find_bin() else {
return Err("git not found");
};

Expand Down
88 changes: 88 additions & 0 deletions crates/turborepo-scm/src/clone.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
use std::{backtrace::Backtrace, process::Command};

use turbopath::AbsoluteSystemPathBuf;

use crate::{Error, GitRepo};

pub enum CloneMode {
/// Cloning locally, do a blobless clone (good UX and reasonably fast)
Local,
/// Cloning on CI, do a treeless clone (worse UX but fastest)
CI,
}

// Provide a sane maximum depth for cloning. If a user needs more history than
// this, they can override or fetch it themselves.
const MAX_CLONE_DEPTH: usize = 64;

/// A wrapper around the git binary that is not tied to a specific repo.
pub struct Git {
bin: AbsoluteSystemPathBuf,
}

impl Git {
pub fn find() -> Result<Self, Error> {
Ok(Self {
bin: GitRepo::find_bin()?,
})
}

pub fn spawn_git_command(
&self,
cwd: &AbsoluteSystemPathBuf,
args: &[&str],
pathspec: &str,
) -> Result<(), Error> {
let mut command = Command::new(self.bin.as_std_path());
command
.args(args)
.current_dir(cwd)
.env("GIT_OPTIONAL_LOCKS", "0");

if !pathspec.is_empty() {
command.arg("--").arg(pathspec);
}

let output = command.spawn()?.wait_with_output()?;

if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
Err(Error::Git(stderr, Backtrace::capture()))
} else {
Ok(())
}
}

pub fn clone(
&self,
url: &str,
cwd: AbsoluteSystemPathBuf,
dir: Option<&str>,
branch: Option<&str>,
mode: CloneMode,
depth: Option<usize>,
) -> Result<(), Error> {
let depth = depth.unwrap_or(MAX_CLONE_DEPTH).to_string();
let mut args = vec!["clone", "--depth", &depth];
if let Some(branch) = branch {
args.push("--branch");
args.push(branch);
}
match mode {
CloneMode::Local => {
args.push("--filter=blob:none");
}
CloneMode::CI => {
args.push("--filter=tree:0");
}
}
args.push(url);
if let Some(dir) = dir {
args.push(dir);
}

self.spawn_git_command(&cwd, &args, "")?;

Ok(())
}
}
12 changes: 6 additions & 6 deletions crates/turborepo-scm/src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use turbopath::{
};
use turborepo_ci::Vendor;

use crate::{Error, Git, SCM};
use crate::{Error, GitRepo, SCM};

#[derive(Debug, PartialEq, Eq)]
pub struct InvalidRange {
Expand Down Expand Up @@ -170,7 +170,7 @@ impl CIEnv {
}
}

impl Git {
impl GitRepo {
fn get_current_branch(&self) -> Result<String, Error> {
let output = self.execute_git_command(&["branch", "--show-current"], "")?;
let output = String::from_utf8(output)?;
Expand Down Expand Up @@ -323,7 +323,7 @@ impl Git {
Ok(files)
}

fn execute_git_command(&self, args: &[&str], pathspec: &str) -> Result<Vec<u8>, Error> {
pub fn execute_git_command(&self, args: &[&str], pathspec: &str) -> Result<Vec<u8>, Error> {
let mut command = Command::new(self.bin.as_std_path());
command
.args(args)
Expand Down Expand Up @@ -431,7 +431,7 @@ mod tests {
use super::{previous_content, CIEnv, InvalidRange};
use crate::{
git::{GitHubCommit, GitHubEvent},
Error, Git, SCM,
Error, GitRepo, SCM,
};

fn setup_repository(
Expand Down Expand Up @@ -1044,7 +1044,7 @@ mod tests {
repo.branch(branch, &commit, true).unwrap();
});

let thing = Git::find(&root).unwrap();
let thing = GitRepo::find(&root).unwrap();
let actual = thing.resolve_base(target_branch, CIEnv::none()).ok();

assert_eq!(actual.as_deref(), expected);
Expand Down Expand Up @@ -1280,7 +1280,7 @@ mod tests {
Err(VarError::NotPresent)
};

let actual = Git::get_github_base_ref(CIEnv {
let actual = GitRepo::get_github_base_ref(CIEnv {
is_github_actions: test_case.env.is_github_actions,
github_base_ref: test_case.env.github_base_ref,
github_event_path: temp_file
Expand Down
17 changes: 10 additions & 7 deletions crates/turborepo-scm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use thiserror::Error;
use tracing::debug;
use turbopath::{AbsoluteSystemPath, AbsoluteSystemPathBuf, PathError, RelativeUnixPathBuf};

pub mod clone;
pub mod git;
mod hash_object;
mod ls_tree;
Expand Down Expand Up @@ -166,7 +167,7 @@ pub(crate) fn wait_for_success<R: Read, T>(
}

#[derive(Debug, Clone)]
pub struct Git {
pub struct GitRepo {
root: AbsoluteSystemPathBuf,
bin: AbsoluteSystemPathBuf,
}
Expand All @@ -179,7 +180,7 @@ enum GitError {
Root(AbsoluteSystemPathBuf, Error),
}

impl Git {
impl GitRepo {
fn find(path_in_repo: &AbsoluteSystemPath) -> Result<Self, GitError> {
// If which produces an invalid absolute path, it's not an execution error, it's
// a programming error. We expect it to always give us an absolute path
Expand Down Expand Up @@ -231,17 +232,19 @@ fn find_git_root(turbo_root: &AbsoluteSystemPath) -> Result<AbsoluteSystemPathBu

#[derive(Debug, Clone)]
pub enum SCM {
Git(Git),
Git(GitRepo),
Manual,
}

impl SCM {
#[tracing::instrument]
pub fn new(path_in_repo: &AbsoluteSystemPath) -> SCM {
Git::find(path_in_repo).map(SCM::Git).unwrap_or_else(|e| {
debug!("{}, continuing with manual hashing", e);
SCM::Manual
})
GitRepo::find(path_in_repo)
.map(SCM::Git)
.unwrap_or_else(|e| {
debug!("{}, continuing with manual hashing", e);
SCM::Manual
})
}

pub fn is_manual(&self) -> bool {
Expand Down
4 changes: 2 additions & 2 deletions crates/turborepo-scm/src/ls_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ use std::{
use nom::Finish;
use turbopath::{AbsoluteSystemPathBuf, RelativeUnixPathBuf};

use crate::{package_deps::GitHashes, wait_for_success, Error, Git};
use crate::{package_deps::GitHashes, wait_for_success, Error, GitRepo};

impl Git {
impl GitRepo {
#[tracing::instrument(skip(self))]
pub fn git_ls_tree(&self, root_path: &AbsoluteSystemPathBuf) -> Result<GitHashes, Error> {
let mut hashes = GitHashes::new();
Expand Down
4 changes: 2 additions & 2 deletions crates/turborepo-scm/src/package_deps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use tracing::debug;
use turbopath::{AbsoluteSystemPath, AnchoredSystemPath, PathError, RelativeUnixPathBuf};
use turborepo_telemetry::events::task::{FileHashMethod, PackageTaskEventBuilder};

use crate::{hash_object::hash_objects, Error, Git, SCM};
use crate::{hash_object::hash_objects, Error, GitRepo, SCM};

pub type GitHashes = HashMap<RelativeUnixPathBuf, String>;

Expand Down Expand Up @@ -111,7 +111,7 @@ impl SCM {
}
}

impl Git {
impl GitRepo {
fn get_package_file_hashes<S: AsRef<str>>(
&self,
turbo_root: &AbsoluteSystemPath,
Expand Down
4 changes: 2 additions & 2 deletions crates/turborepo-scm/src/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ use std::{
use nom::Finish;
use turbopath::{AbsoluteSystemPath, RelativeUnixPathBuf};

use crate::{package_deps::GitHashes, wait_for_success, Error, Git};
use crate::{package_deps::GitHashes, wait_for_success, Error, GitRepo};

impl Git {
impl GitRepo {
#[tracing::instrument(skip(self, root_path, hashes))]
pub(crate) fn append_git_status(
&self,
Expand Down
Loading
Loading