Skip to content
Merged
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 rust/execution/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,8 @@ pub fn relevant_tests(files: &[String]) -> Result<Vec<String>, Error> {
if let Some((dir, _)) = file.rsplit_once('/') {
candidates.push(format!("{dir}/{base}.test.ts"));
candidates.push(format!("{dir}/{base}.spec.ts"));
candidates.push(format!("{dir}/test.ts"));
candidates.push(format!("{dir}/spec.ts"));
}
for candidate in candidates {
if !tests.contains(&candidate) {
Expand Down
18 changes: 18 additions & 0 deletions rust/execution/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2380,6 +2380,9 @@ fn polyglot_intake_extracts_csharp_java_and_typescript_paths() -> Result<(), Err
let monorepo_ts = policy::relevant_tests(&["library/src/actions/ip/ip.ts".to_owned()])?;
assert!(monorepo_ts.contains(&"library/src/actions/ip/ip.test.ts".to_owned()));
assert!(monorepo_ts.contains(&"library/src/actions/ip/ip.spec.ts".to_owned()));
let folder_ts = policy::relevant_tests(&["pkgs/core/src/parseISO/index.ts".to_owned()])?;
assert!(folder_ts.contains(&"pkgs/core/src/parseISO/test.ts".to_owned()));
assert!(folder_ts.contains(&"pkgs/core/src/parseISO/spec.ts".to_owned()));
Ok(())
}

Expand Down Expand Up @@ -2427,3 +2430,18 @@ fn maven_offline_and_resolution_error_detection_separates_cache_miss_from_test_f
));
assert!(!tools::Boundary::is_maven_resolution_error(test_failure));
}

#[test]
fn cargo_offline_resolution_error_detection_separates_cache_miss_from_compile_failure() {
let offline_miss = "error: no matching package named `dot-parser` found\nlocation searched: crates.io index\nnote: offline mode (via `--offline`) can sometimes cause surprising resolution failures";
assert!(tools::Boundary::is_cargo_offline_resolution_error(
offline_miss
));
assert!(tools::Boundary::is_cargo_offline_resolution_error(
"error: attempting to make an HTTP request, but --offline was specified"
));
let compile_err = "error[E0308]: mismatched types\ntest result: FAILED. 0 passed; 1 failed;";
assert!(!tools::Boundary::is_cargo_offline_resolution_error(
compile_err
));
}
92 changes: 90 additions & 2 deletions rust/execution/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ fn environment_allowed(name: &str) -> bool {
.contains(&name.to_ascii_lowercase().as_str())
}

pub(crate) const TS_IMPORT_HOOK: &str = r#"data:text/javascript,import{registerHooks}from"node:module";import*as T from"node:test";import*as A from"node:assert/strict";import{inspect}from"node:util";const S=Symbol("m");const mk=f=>({[S]:f});const eq=(a,b,st)=>{if(b&&typeof b==="object"&&typeof b[S]==="function")return b[S](a);if(Object.is(a,b))return true;if(!a||!b||typeof a!=="object"||typeof b!=="object")return false;if(a instanceof RegExp&&b instanceof RegExp)return a.source===b.source&&a.flags===b.flags;if(a instanceof Date&&b instanceof Date)return Object.is(a.getTime(),b.getTime());if(Array.isArray(a)!==Array.isArray(b))return false;if(Array.isArray(a))return a.length===b.length&&a.every((v,i)=>eq(v,b[i],st));if(st&&Object.getPrototypeOf(a)!==Object.getPrototypeOf(b))return false;const ka=Object.keys(a),kb=Object.keys(b);const ea=st?ka:ka.filter(k=>a[k]!==undefined),eb=st?kb:kb.filter(k=>b[k]!==undefined);if(ea.length!==eb.length)return false;return eb.every(k=>Object.prototype.hasOwnProperty.call(a,k)&&eq(a[k],b[k],st));};const cmp=(a,b,st,neg)=>{const ok=eq(a,b,st);if(neg?ok:!ok)A.fail(`Expected ${inspect(a,{depth:6})} ${neg?"not ":""}to equal ${inspect(b,{depth:6})}`);};const m=(a,neg)=>({toBe:b=>neg?A.notStrictEqual(a,b):A.strictEqual(a,b),toEqual:b=>cmp(a,b,false,neg),toStrictEqual:b=>cmp(a,b,true,neg),toBeUndefined:()=>neg?A.notStrictEqual(a,undefined):A.strictEqual(a,undefined),toBeNull:()=>neg?A.notStrictEqual(a,null):A.strictEqual(a,null),toBeTruthy:()=>A.ok(neg?!a:Boolean(a)),toBeFalsy:()=>A.ok(neg?Boolean(a):!a),toBeNaN:()=>A.ok(neg?!Number.isNaN(a):Number.isNaN(a)),toBeGreaterThan:b=>A.ok(neg?!(a>b):a>b),toBeGreaterThanOrEqual:b=>A.ok(neg?!(a>=b):a>=b),toBeLessThan:b=>A.ok(neg?!(a<b):a<b),toBeLessThanOrEqual:b=>A.ok(neg?!(a<=b):a<=b),toBeCloseTo:(b,p=2)=>{const ok=Math.abs(a-b)<Math.pow(10,-p)/2;A.ok(neg?!ok:ok);},toBeInstanceOf:c=>A.ok(neg?!(a instanceof c):a instanceof c),toContain:b=>{const ok=typeof a==="string"?a.includes(b):Array.isArray(a)&&a.includes(b);A.ok(neg?!ok:ok);},toHaveLength:b=>neg?A.notStrictEqual(a.length,b):A.strictEqual(a.length,b),toMatch:b=>{const ok=b instanceof RegExp?b.test(String(a)):String(a).includes(String(b));A.ok(neg?!ok:ok);},toHaveProperty:(k,v)=>{const parts=Array.isArray(k)?k:String(k).split(".");let cur=a,has=true;for(const p of parts){if(cur!=null&&Object.prototype.hasOwnProperty.call(Object(cur),p))cur=cur[p];else{has=false;break;}}const ok=arguments.length>1?has&&eq(cur,v,false):has;A.ok(neg?!ok:ok);},toThrow:b=>neg?A.doesNotThrow(a,b):A.throws(a,b)});const expect=Object.assign(a=>Object.assign(m(a,false),{not:m(a,true)}),{any:c=>mk(v=>c===String?typeof v==="string"||v instanceof String:c===Number?typeof v==="number"||v instanceof Number:c===Boolean?typeof v==="boolean"||v instanceof Boolean:c===Function?typeof v==="function":c===Object?v!==null&&typeof v==="object":c===Symbol?typeof v==="symbol":c===BigInt?typeof v==="bigint":v instanceof c),anything:()=>mk(v=>v!==null&&v!==undefined),objectContaining:o=>mk(v=>v!==null&&typeof v==="object"&&Object.keys(o).every(k=>k in v&&eq(v[k],o[k],false))),arrayContaining:arr=>mk(v=>Array.isArray(v)&&arr.every(x=>v.some(y=>eq(y,x,false)))),stringContaining:s=>mk(v=>typeof v==="string"&&v.includes(s))});const api={describe:T.describe,it:T.it,test:T.test,beforeEach:T.beforeEach,afterEach:T.afterEach,beforeAll:T.before,afterAll:T.after,expect};globalThis.__rosterTestApi=api;if(!globalThis.describe)Object.assign(globalThis,api);registerHooks({resolve(s,c,n){try{return n(s,c);}catch(e){if(s==="vitest"||s==="@jest/globals")return{shortCircuit:true,url:"data:text/javascript,export const{describe,it,test,beforeEach,afterEach,beforeAll,afterAll,expect}=globalThis.__rosterTestApi;"};if(c.parentURL&&c.parentURL.startsWith("file:")){const xs=s.endsWith(".js")?[s.slice(0,-3)+".ts"]:(s.startsWith(".")&&!/\.[cm]?[jt]s$/.test(s)?[s+".ts",s+"/index.ts"]:[]);for(const x of xs){try{return n(x,c);}catch{}}}throw e;}}});"#;
pub(crate) const TS_IMPORT_HOOK: &str = r#"data:text/javascript,import{registerHooks}from"node:module";import*as T from"node:test";import*as A from"node:assert/strict";import{inspect}from"node:util";import*as F from"node:fs";import*as P from"node:path";import{fileURLToPath,pathToFileURL}from"node:url";const S=Symbol("m");const mk=f=>({[S]:f});const eq=(a,b,st)=>{if(b&&typeof b==="object"&&typeof b[S]==="function")return b[S](a);if(Object.is(a,b))return true;if(!a||!b||typeof a!=="object"||typeof b!=="object")return false;if(a instanceof RegExp&&b instanceof RegExp)return a.source===b.source&&a.flags===b.flags;if(a instanceof Date&&b instanceof Date)return Object.is(a.getTime(),b.getTime());if(Array.isArray(a)!==Array.isArray(b))return false;if(Array.isArray(a))return a.length===b.length&&a.every((v,i)=>eq(v,b[i],st));if(st&&Object.getPrototypeOf(a)!==Object.getPrototypeOf(b))return false;const ka=Object.keys(a),kb=Object.keys(b);const ea=st?ka:ka.filter(k=>a[k]!==undefined),eb=st?kb:kb.filter(k=>b[k]!==undefined);if(ea.length!==eb.length)return false;return eb.every(k=>Object.prototype.hasOwnProperty.call(a,k)&&eq(a[k],b[k],st));};const cmp=(a,b,st,neg)=>{const ok=eq(a,b,st);if(neg?ok:!ok)A.fail(`Expected ${inspect(a,{depth:6})} ${neg?"not ":""}to equal ${inspect(b,{depth:6})}`);};const m=(a,neg)=>({toBe:b=>neg?A.notStrictEqual(a,b):A.strictEqual(a,b),toEqual:b=>cmp(a,b,false,neg),toStrictEqual:b=>cmp(a,b,true,neg),toBeUndefined:()=>neg?A.notStrictEqual(a,undefined):A.strictEqual(a,undefined),toBeNull:()=>neg?A.notStrictEqual(a,null):A.strictEqual(a,null),toBeTruthy:()=>A.ok(neg?!a:Boolean(a)),toBeFalsy:()=>A.ok(neg?Boolean(a):!a),toBeNaN:()=>A.ok(neg?!Number.isNaN(a):Number.isNaN(a)),toBeGreaterThan:b=>A.ok(neg?!(a>b):a>b),toBeGreaterThanOrEqual:b=>A.ok(neg?!(a>=b):a>=b),toBeLessThan:b=>A.ok(neg?!(a<b):a<b),toBeLessThanOrEqual:b=>A.ok(neg?!(a<=b):a<=b),toBeCloseTo:(b,p=2)=>{const ok=Math.abs(a-b)<Math.pow(10,-p)/2;A.ok(neg?!ok:ok);},toBeInstanceOf:c=>A.ok(neg?!(a instanceof c):a instanceof c),toContain:b=>{const ok=typeof a==="string"?a.includes(b):Array.isArray(a)&&a.includes(b);A.ok(neg?!ok:ok);},toHaveLength:b=>neg?A.notStrictEqual(a.length,b):A.strictEqual(a.length,b),toMatch:b=>{const ok=b instanceof RegExp?b.test(String(a)):String(a).includes(String(b));A.ok(neg?!ok:ok);},toHaveProperty:(k,v)=>{const parts=Array.isArray(k)?k:String(k).split(".");let cur=a,has=true;for(const p of parts){if(cur!=null&&Object.prototype.hasOwnProperty.call(Object(cur),p))cur=cur[p];else{has=false;break;}}const ok=arguments.length>1?has&&eq(cur,v,false):has;A.ok(neg?!ok:ok);},toThrow:b=>neg?A.doesNotThrow(a,b):A.throws(a,b)});const expect=Object.assign(a=>Object.assign(m(a,false),{not:m(a,true)}),{any:c=>mk(v=>c===String?typeof v==="string"||v instanceof String:c===Number?typeof v==="number"||v instanceof Number:c===Boolean?typeof v==="boolean"||v instanceof Boolean:c===Function?typeof v==="function":c===Object?v!==null&&typeof v==="object":c===Symbol?typeof v==="symbol":c===BigInt?typeof v==="bigint":v instanceof c),anything:()=>mk(v=>v!==null&&v!==undefined),objectContaining:o=>mk(v=>v!==null&&typeof v==="object"&&Object.keys(o).every(k=>k in v&&eq(v[k],o[k],false))),arrayContaining:arr=>mk(v=>Array.isArray(v)&&arr.every(x=>v.some(y=>eq(y,x,false)))),stringContaining:s=>mk(v=>typeof v==="string"&&v.includes(s))});const RealDate=Date;let fakeNow=null;class FakeDate extends RealDate{constructor(...xs){if(xs.length===0&&fakeNow!==null)super(fakeNow);else super(...xs);}static now(){return fakeNow!==null?fakeNow:RealDate.now();}}const vi={fn:(impl)=>{const f=(...xs)=>{f.mock.calls.push(xs);return impl?impl(...xs):undefined;};f.mock={calls:[]};return f;},useFakeTimers:()=>{globalThis.Date=FakeDate;return vi;},useRealTimers:()=>{fakeNow=null;globalThis.Date=RealDate;return vi;},setSystemTime:d=>{fakeNow=d instanceof RealDate?d.getTime():typeof d==="number"?d:new RealDate(d).getTime();globalThis.Date=FakeDate;return vi;},clearAllMocks:()=>vi,restoreAllMocks:()=>{fakeNow=null;globalThis.Date=RealDate;return vi;}};const api={describe:T.describe,it:T.it,test:T.test,beforeEach:T.beforeEach,afterEach:T.afterEach,beforeAll:T.before,afterAll:T.after,expect,vi};globalThis.__rosterTestApi=api;if(!globalThis.describe)Object.assign(globalThis,api);let wsMap=null;const loadWs=start=>{if(wsMap)return wsMap;wsMap=new Map();let d=start;for(let i=0;i<10;i++){for(const sub of["pkgs","packages","libs"]){const base=P.join(d,sub);if(F.existsSync(base)&&F.statSync(base).isDirectory()){for(const ent of F.readdirSync(base)){const pj=P.join(base,ent,"package.json");if(F.existsSync(pj)){try{const pkg=JSON.parse(F.readFileSync(pj,"utf8"));if(pkg&&typeof pkg.name==="string")wsMap.set(pkg.name,{dir:P.join(base,ent),pkg});}catch{}}}}}const up=P.dirname(d);if(up===d)break;d=up;}return wsMap;};const pickExp=v=>typeof v==="string"?v:(v&&typeof v==="object"?pickExp(v.import||v.default||v.module||v.types):null);registerHooks({resolve(s,c,n){try{return n(s,c);}catch(e){if(s==="vitest"||s==="@jest/globals")return{shortCircuit:true,url:"data:text/javascript,export const{describe,it,test,beforeEach,afterEach,beforeAll,afterAll,expect,vi}=globalThis.__rosterTestApi;"};if(c.parentURL&&c.parentURL.startsWith("file:")){const xs=s.endsWith(".js")?[s.slice(0,-3)+".ts"]:(s.startsWith(".")&&!/\.[cm]?[jt]s$/.test(s)?[s+".ts",s+"/index.ts"]:[]);for(const x of xs){try{return n(x,c);}catch{}}if(!s.startsWith(".")&&!s.startsWith("/")&&!s.startsWith("node:")){const map=loadWs(P.dirname(fileURLToPath(c.parentURL)));for(const[name,info]of map){if(s===name||s.startsWith(name+"/")){const sub=s===name?".":"."+s.slice(name.length);let target=info.pkg.exports&&typeof info.pkg.exports==="object"?pickExp(info.pkg.exports[sub]):null;if(!target&&sub===".")target=info.pkg.module||info.pkg.main||"./src/index.ts";if(target){const full=P.resolve(info.dir,target);const cands=full.endsWith(".js")?[full.slice(0,-3)+".ts",full]:[full,full+".ts",P.join(full,"index.ts")];for(const f of cands){if(F.existsSync(f))return{shortCircuit:true,url:pathToFileURL(f).href};}}}}}}throw e;}}});"#;

pub(crate) fn unverified_cleanup(failure: &process::Failure, descendants_possible: bool) -> bool {
!failure.cleanup_complete
Expand Down Expand Up @@ -3479,6 +3479,7 @@ impl Boundary {
if let Some(cache) = nuget_cache {
restore_args.push("--source".to_owned());
restore_args.push(cache.display().to_string());
restore_args.push("-p:NuGetAudit=false".to_owned());
}
let restore_out = self
.process(
Expand Down Expand Up @@ -3751,6 +3752,13 @@ impl Boundary {
|| output.contains("Unresolveable build extension")
}

pub(crate) fn is_cargo_offline_resolution_error(output: &str) -> bool {
output.contains("offline mode (via `--offline`)")
|| output.contains("attempting to make an HTTP request, but --offline was specified")
|| (output.contains("no matching package named") && output.contains("--offline"))
|| (output.contains("failed to select a version") && output.contains("--offline"))
}

async fn node_checks(&self, scope: &[String], full: bool) -> Result<NodeChecks, Error> {
if !self.root.join("package.json").is_file()
&& scope
Expand Down Expand Up @@ -3824,6 +3832,35 @@ impl Boundary {
available.push(file.clone());
}
}
if available.is_empty() {
for file in &effective_scope {
let norm = file.replace('\\', "/");
if !(norm.ends_with(".ts") || norm.ends_with(".mts") || norm.ends_with(".cts")) {
continue;
}
let mut cur = norm.as_str();
for _ in 0..3 {
let Some((dir, _)) = cur.rsplit_once('/') else {
break;
};
if dir.is_empty() || dir == "src" {
break;
}
for name in ["test.ts", "spec.ts"] {
let cand = format!("{dir}/{name}");
if regular(&self.root, &cand, MAX_FILE_BYTES)?.is_some() {
if !relevant.contains(&cand) {
relevant.push(cand.clone());
}
if !available.contains(&cand) {
available.push(cand);
}
}
}
cur = dir;
}
}
}
match fs::read_dir(&tests_root) {
Ok(entries) => {
for entry in entries {
Expand Down Expand Up @@ -3864,7 +3901,10 @@ impl Boundary {
commands: Vec::new(),
syntax_file: None,
};
if !full && tests.is_empty() {
let has_ts_scope = effective_scope
.iter()
.any(|file| file.ends_with(".ts") || file.ends_with(".mts") || file.ends_with(".cts"));
if tests.is_empty() && (!full || (has_ts_scope && !tests_root.is_dir())) {
result.skipped = true;
result.output.stdout = b"no relevant tests exist for the changed files".to_vec();
return Ok(result);
Expand Down Expand Up @@ -4468,6 +4508,7 @@ impl Boundary {
.files
.iter()
.any(|file| file.starts_with("benches/") || file.contains("/benches/"));
let mut fetched_online = false;
for args in cargo_steps {
let is_metadata = args.first().map(String::as_str) == Some("metadata");
let is_all_targets_check = args.first().map(String::as_str) == Some("check")
Expand All @@ -4482,6 +4523,53 @@ impl Boundary {
4 * 1024 * 1024,
)
.await?;
if output.exit != 0 && !is_roster_self && !fetched_online {
let combined_err = format!(
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
if Self::is_cargo_offline_resolution_error(&combined_err) {
fetched_online = true;
let mut online_env = environment.clone();
online_env.remove("CARGO_NET_OFFLINE");
let mut fetch_args = vec!["fetch".to_owned()];
if let Some(ref sc) = sub_crate {
fetch_args.push("--manifest-path".to_owned());
fetch_args.push(format!("{sc}/Cargo.toml"));
if had_sub_lock {
fetch_args.push("--locked".to_owned());
}
} else if had_root_lock {
fetch_args.push("--locked".to_owned());
}
commands.push(format!("cargo {}", fetch_args.join(" ")));
let fetch_out = self
.process(
&approved.executable,
&fetch_args,
&online_env,
policy::FULL_TEST_TIMEOUT_MS,
2 * 1024 * 1024,
)
.await?;
if fetch_out.exit != 0 {
return Err(unsupported(
"Rust Cargo test runner could not fetch required crates into the local cache",
));
}
commands.push(format!("cargo {}", args.join(" ")));
output = self
.process(
&approved.executable,
&args,
&environment,
policy::FULL_TEST_TIMEOUT_MS,
4 * 1024 * 1024,
)
.await?;
}
}
if output.exit != 0 && is_all_targets_check && !has_bench_scope {
let err_text = bytes_text(&output.stderr)?;
if err_text.contains("E0554") && err_text.contains("benches/") {
Expand Down
2 changes: 1 addition & 1 deletion rust/planning/grounding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -577,7 +577,7 @@ pub fn normalize_design(input: Option<&Value>) -> Result<Option<Value>, Error> {
("extend", Value::Array(extend)),
("new_exports", Value::Array(new_exports)),
]);
for (field, limit) in [("outline", 10), ("edge_cases", 8), ("out_of_scope", 6)] {
for (field, limit) in [("outline", 16), ("edge_cases", 16), ("out_of_scope", 12)] {
domain::put(
&mut result,
field,
Expand Down
Loading
Loading