Skip to content

Commit

Permalink
Merge branch 'main' into patch-2
Browse files Browse the repository at this point in the history
  • Loading branch information
zsh77 committed Mar 5, 2024
2 parents 8d36c4b + 167a9f0 commit f4f6625
Show file tree
Hide file tree
Showing 118 changed files with 9,426 additions and 6,411 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 9 additions & 8 deletions crates/turbopack-core/src/resolve/mod.rs
Expand Up @@ -1744,6 +1744,12 @@ async fn resolve_into_folder(
}
let request = Request::parse(Value::new(normalized_request.into()));

// main field will always resolve not fully specified
let options = if options_value.fully_specified {
options.with_fully_specified(false).resolve().await?
} else {
options
};
let result = &*resolve_internal_inline(package_path, request, options)
.await?
.await?;
Expand Down Expand Up @@ -2035,8 +2041,6 @@ async fn resolve_module_request(
.into());
}

let package_options = options.with_fully_specified(false).resolve().await?;

// There may be more than one package with the same name. For instance, in a
// TypeScript project, `compilerOptions.baseUrl` can declare a path where to
// resolve packages. A request to "foo/bar" might resolve to either
Expand All @@ -2049,7 +2053,7 @@ async fn resolve_module_request(
Value::new(path.clone()),
package_path,
query,
package_options,
options,
));
}
FindPackageItem::PackageFile(package_path) => {
Expand Down Expand Up @@ -2112,8 +2116,6 @@ async fn resolve_into_package(
let is_root_match = path.is_match("") || path.is_match("/");
let could_match_others = path.could_match_others("");

let mut has_match = false;

for resolve_into_package in options_value.into_package.iter() {
match resolve_into_package {
// handled by the `resolve_into_folder` call below
Expand Down Expand Up @@ -2155,14 +2157,13 @@ async fn resolve_into_package(

// other options do not apply anymore when an exports
// field exist
has_match = true;
break;
return Ok(merge_results(results));
}
}
}

// apply main field(s) or fallback to index.js if there's no subpath
if is_root_match && !has_match {
if is_root_match {
results.push(resolve_into_folder(package_path, options));
}

Expand Down
81 changes: 81 additions & 0 deletions crates/turbopack-core/src/resolve/parse.rs
Expand Up @@ -355,6 +355,87 @@ impl Request {
})
}

#[turbo_tasks::function]
pub async fn append_path(self: Vc<Self>, suffix: String) -> Result<Vc<Self>> {
Ok(match &*self.await? {
Request::Raw {
path,
query,
force_in_lookup_dir,
} => {
let mut pat = Pattern::concat([path.clone(), suffix.into()]);
pat.normalize();
Self::raw(Value::new(pat), *query, *force_in_lookup_dir)
}
Request::Relative {
path,
query,
force_in_lookup_dir,
} => {
let mut pat = Pattern::concat([path.clone(), suffix.into()]);
pat.normalize();
Self::relative(Value::new(pat), *query, *force_in_lookup_dir)
}
Request::Module {
module,
path,
query,
} => {
let mut pat = Pattern::concat([path.clone(), suffix.into()]);
pat.normalize();
Self::module(module.clone(), Value::new(pat), *query)
}
Request::ServerRelative { path, query } => {
let mut pat = Pattern::concat([path.clone(), suffix.into()]);
pat.normalize();
Self::ServerRelative {
path: pat,
query: *query,
}
.cell()
}
Request::Windows { path, query } => {
let mut pat = Pattern::concat([path.clone(), suffix.into()]);
pat.normalize();
Self::Windows {
path: pat,
query: *query,
}
.cell()
}
Request::Empty => Self::parse(Value::new(suffix.into())),
Request::PackageInternal { path } => {
let mut pat = Pattern::concat([path.clone(), suffix.into()]);
pat.normalize();
Self::PackageInternal { path: pat }.cell()
}
Request::Uri {
protocol,
remainder,
} => {
let remainder = format!("{}{}", remainder, suffix);
Self::Uri {
protocol: protocol.clone(),
remainder,
}
.cell()
}
Request::Unknown { path } => {
let mut pat = Pattern::concat([path.clone(), suffix.into()]);
pat.normalize();
Self::Unknown { path: pat }.cell()
}
Request::Dynamic => self,
Request::Alternatives { requests } => {
let requests = requests
.iter()
.map(|req| req.append_path(suffix.clone()))
.collect();
Request::Alternatives { requests }.cell()
}
})
}

#[turbo_tasks::function]
pub fn query(&self) -> Vc<String> {
match self {
Expand Down
1 change: 1 addition & 0 deletions crates/turbopack-tests/tests/execution.rs
Expand Up @@ -288,6 +288,7 @@ async fn run_test(prepared_test: Vc<PreparedTest>) -> Result<Vc<RunTestResult>>
.cell(),
)],
browser: true,
module: true,
..Default::default()
}
.cell(),
Expand Down
Expand Up @@ -41,16 +41,34 @@ it("should not bundle the other exports conditions", () => {
});

it("should not bundle the other alternatives", () => {
require("package-with-exports/entry3");
require("package-without-exports/entry3");
const modules = Object.keys(__turbopack_modules__);
expect(modules).toContainEqual(
expect.stringMatching(
/input\/node_modules\/package-with-exports\/entry3\.js/
/input\/node_modules\/package-without-exports\/entry3\.js/
)
);
expect(modules).not.toContainEqual(
expect.stringMatching(
/input\/node_modules\/package-with-exports\/entry3\/index/
/input\/node_modules\/package-without-exports\/entry3\/index/
)
);
});

it("should not bundle the other alternatives", () => {
require("package-without-exports");
const modules = Object.keys(__turbopack_modules__);
expect(modules).toContainEqual(
expect.stringMatching(
/input\/node_modules\/package-without-exports\/module\.js/
)
);
expect(modules).not.toContainEqual(
expect.stringMatching(
/input\/node_modules\/package-without-exports\/main\.js/
)
);
expect(modules).not.toContainEqual(
expect.stringMatching(/input\/node_modules\/package-without-exports\/index/)
);
});

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 3 additions & 5 deletions crates/turborepo-auth/src/auth/sso.rs
Expand Up @@ -68,11 +68,9 @@ pub async fn sso_login<'a, T: Client + TokenClient + CacheClient>(
{
return Ok(token);
}
}

// No existing turbo token found. If the user is logging into Vercel, check for
// an existing `vc` token with correct scope.
if login_url_configuration.contains("vercel.com") {
// No existing turbo token found. If the user is logging into Vercel,
// check for an existing `vc` token with correct scope.
} else if login_url_configuration.contains("vercel.com") {
if let Ok(Some(token)) = extract_vercel_token() {
let token = Token::existing(token);
if token
Expand Down
2 changes: 1 addition & 1 deletion crates/turborepo-lib/src/commands/telemetry.rs
Expand Up @@ -38,7 +38,7 @@ pub fn configure(
base: &mut CommandBase,
telemetry: CommandEventBuilder,
) {
let config = TelemetryConfig::new();
let config = TelemetryConfig::with_default_config_path();
let mut config = match config {
Ok(config) => config,
Err(e) => {
Expand Down
2 changes: 2 additions & 0 deletions crates/turborepo-telemetry/Cargo.toml
Expand Up @@ -11,6 +11,7 @@ workspace = true

[dev-dependencies]
serde_json = { workspace = true }
tempfile = { workspace = true }
test-case = { workspace = true }
turborepo-vercel-api-mock = { workspace = true }

Expand All @@ -30,6 +31,7 @@ sha2 = "0.10.8"
thiserror = { workspace = true }
tokio = { workspace = true, features = ["full", "time"] }
tracing = { workspace = true }
turbopath = { workspace = true }
turborepo-api-client = { workspace = true }
turborepo-dirs = { path = "../turborepo-dirs" }
turborepo-ui = { workspace = true }
Expand Down
84 changes: 41 additions & 43 deletions crates/turborepo-telemetry/src/config.rs
@@ -1,4 +1,4 @@
use std::{env, fs, path::Path};
use std::env;

use chrono::{DateTime, Utc};
pub use config::{Config, ConfigError, File, FileFormat};
Expand All @@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize};
use serde_json;
use sha2::{Digest, Sha256};
use tracing::{debug, error};
use turbopath::{AbsoluteSystemPath, AbsoluteSystemPathBuf};
use turborepo_dirs::config_dir;
use turborepo_ui::{color, BOLD, GREY, UI, UNDERLINE};
use uuid::Uuid;
Expand Down Expand Up @@ -48,20 +49,24 @@ impl Default for TelemetryConfigContents {

#[derive(Debug)]
pub struct TelemetryConfig {
config_path: String,
config_path: AbsoluteSystemPathBuf,
config: TelemetryConfigContents,
}

impl TelemetryConfig {
pub fn new() -> Result<TelemetryConfig, ConfigError> {
let file_path = &get_config_path()?;
debug!("Telemetry config path: {}", file_path);
if !Path::new(file_path).try_exists().unwrap_or(false) {
write_new_config()?;
pub fn with_default_config_path() -> Result<TelemetryConfig, ConfigError> {
let config_path = default_config_path()?;
TelemetryConfig::new(config_path)
}

pub fn new(config_path: AbsoluteSystemPathBuf) -> Result<TelemetryConfig, ConfigError> {
debug!("Telemetry config path: {}", config_path);
if !config_path.exists() {
write_new_config(&config_path)?;
}

let mut settings = Config::builder();
settings = settings.add_source(File::new(file_path, FileFormat::Json));
settings = settings.add_source(File::new(config_path.as_str(), FileFormat::Json));
let settings = settings.build();

// If this is a FileParse error, we assume something corrupted the file or
Expand All @@ -71,16 +76,18 @@ impl TelemetryConfig {
let config = match settings {
Ok(settings) => settings.try_deserialize::<TelemetryConfigContents>()?,
Err(ConfigError::FileParse { .. }) => {
fs::remove_file(file_path).map_err(|e| ConfigError::Message(e.to_string()))?;
write_new_config()?;
config_path
.remove_file()
.map_err(|e| ConfigError::Message(e.to_string()))?;
write_new_config(&config_path)?;
return Err(settings.unwrap_err());
}
// Propagate other errors
Err(err) => return Err(err),
};

let config = TelemetryConfig {
config_path: file_path.to_string(),
config_path,
config,
};

Expand All @@ -90,13 +97,14 @@ impl TelemetryConfig {
fn write(&self) -> Result<(), ConfigError> {
let serialized = serde_json::to_string_pretty(&self.config)
.map_err(|e| ConfigError::Message(e.to_string()))?;
fs::write(&self.config_path, serialized)
self.config_path
.create_with_contents(serialized)
.map_err(|e| ConfigError::Message(e.to_string()))?;
Ok(())
}

pub fn one_way_hash(input: &str) -> String {
match TelemetryConfig::new() {
match TelemetryConfig::with_default_config_path() {
Ok(config) => config.one_way_hash_with_config_salt(input),
Err(_) => TelemetryConfig::one_way_hash_with_tmp_salt(input),
}
Expand Down Expand Up @@ -219,44 +227,34 @@ impl TelemetryConfig {
}
}

fn get_config_path() -> Result<String, ConfigError> {
if cfg!(test) {
let tmp_dir = env::temp_dir();
let config_path = tmp_dir.join("test-telemetry.json");
Ok(config_path.to_str().unwrap().to_string())
} else {
let config_dir = config_dir().ok_or(ConfigError::Message(
"Unable to find telemetry config directory".to_string(),
))?;
// stored as a sibling to the turbo global config
let config_path = config_dir.join("turborepo").join("telemetry.json");
Ok(config_path.to_str().unwrap().to_string())
}
fn default_config_path() -> Result<AbsoluteSystemPathBuf, ConfigError> {
let config_dir = config_dir().ok_or(ConfigError::Message(
"Unable to find telemetry config directory".to_string(),
))?;
let abs_config_dir = AbsoluteSystemPathBuf::try_from(config_dir.as_path()).map_err(|e| {
ConfigError::Message(format!(
"Invalid config directory {}: {}",
config_dir.display(),
e
))
})?;
// stored as a sibling to the turbo global config
Ok(abs_config_dir.join_components(&["turborepo", "telemetry.json"]))
}

fn write_new_config() -> Result<(), ConfigError> {
let file_path = get_config_path()?;
fn write_new_config(file_path: &AbsoluteSystemPath) -> Result<(), ConfigError> {
let serialized = serde_json::to_string_pretty(&TelemetryConfigContents::default())
.map_err(|e| ConfigError::Message(e.to_string()))?;

// Extract the directory path from the file path
let dir_path = Path::new(&file_path).parent().ok_or_else(|| {
ConfigError::Message("Failed to extract directory path from file path".to_string())
})?;

// Create the directory if it doesn't exist
if !dir_path.try_exists().unwrap_or(false) {
fs::create_dir_all(dir_path).map_err(|e| {
ConfigError::Message(format!(
"Failed to create directory {}: {}",
dir_path.display(),
e
))
})?;
}
file_path
.ensure_dir()
.map_err(|_| ConfigError::Message("Failed to create directory".to_string()))?;

// Write the file
fs::write(&file_path, serialized).map_err(|e| ConfigError::Message(e.to_string()))?;
file_path
.create_with_contents(serialized)
.map_err(|e| ConfigError::Message(e.to_string()))?;
Ok(())
}

Expand Down

0 comments on commit f4f6625

Please sign in to comment.