Manifest.vala 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. using Invercargill;
  2. using Invercargill.Mapping;
  3. using Invercargill.DataStructures;
  4. namespace Usm {
  5. public errordomain ManifestError {
  6. MISSING_FIELD,
  7. INVALID_VERSION,
  8. INVALID_LICENCE_CATEGORY,
  9. INVALID_RESOURCE_TYPE,
  10. INVALID_FILE_TYPE,
  11. INVALID_REMOVE_TYPE,
  12. INVALID_INSTALL_TYPE,
  13. INVALID_PACKAGE,
  14. INVALID_PATH_BASE,
  15. INVALID_FILE_PATH,
  16. INVALID_FLAG,
  17. /** A dataPackage manifest defines a lifecycle executable (only acquire is permitted) */
  18. DATA_PACKAGE_WITH_EXECUTABLE,
  19. /** A "depends" phase is neither a flat array of refs nor an array of candidate groups (mixed forms, over-nested arrays or non-string entries) */
  20. INVALID_DEPENDENCIES,
  21. /** A candidate group in a "depends" phase is empty */
  22. EMPTY_DEPENDENCY_GROUP
  23. }
  24. public class Manifest {
  25. public string name { get; set; }
  26. public string summary { get; set; }
  27. public Version version { get; set; }
  28. public Vector<Licence> licences { get; set; }
  29. public Dictionary<ResourceRef, ManifestFile> provides { get; set; }
  30. public Dependencies dependencies { get; set; }
  31. public Executables executables { get; set; }
  32. public Set<ManifestFlag> flags { get; set; }
  33. public string? markdown_path { get; set; }
  34. public string? url { get; set; }
  35. public Vector<string>? screenshot_paths { get; set; }
  36. public string? icon_path { get; set; }
  37. public string? metainfo_path { get; set; }
  38. public Git? git { get; set; }
  39. public Properties? extra_properties { get; set; }
  40. /**
  41. * Whether the manifest declares {@link ManifestFlag.DATA_PACKAGE}:
  42. * a package with no lifecycle executables whose {@link provides}
  43. * are copied directly from the source tree at install time.
  44. */
  45. public bool is_data_package {
  46. get {
  47. return flags != null && flags.contains(ManifestFlag.DATA_PACKAGE);
  48. }
  49. }
  50. public static PropertyMapper<Manifest> get_mapper() {
  51. return PropertyMapper.build_for<Manifest>(cfg => {
  52. cfg.map<string>("name", o => o.name, (o, v) => o.name = v);
  53. cfg.map<string>("version", o => o.version.to_string(), (o, v) => o.version = new Version.from_string(v));
  54. cfg.map<string>("summary", o => o.summary, (o, v) => o.summary = v);
  55. cfg.map_property_groups_with<Licence>("licences", o => o.licences, (o, v) => o.licences = v.to_vector(), Licence.get_mapper());
  56. cfg.map<Properties>("provides", o => o.map_from_provides_dict(), (o, v) => o.build_provides_dict(v));
  57. cfg.map_properties_with<Dependencies>("depends", o => o.dependencies, (o, v) => o.dependencies = v, Dependencies.get_mapper());
  58. cfg.map_properties_with<Executables>("execs", o => o.executables, (o, v) => o.executables = v, Executables.get_mapper())
  59. .undefined_when(o => o.executables == null)
  60. .when_undefined(o => o.executables = new Executables());
  61. cfg.map_many<string>("flags", o => o.flags.select<string>(f => f.to_string()), (o, v) => o.flags = v.attempt_select<ManifestFlag>(f => ManifestFlag.from_string(f)).to_set());
  62. cfg.map<string>("md", o => o.markdown_path, (o, v) => o.markdown_path = v)
  63. .undefined_when(o => o.markdown_path == null)
  64. .when_undefined(o => o.markdown_path = null);
  65. cfg.map<string>("url", o => o.url, (o, v) => o.url = v)
  66. .undefined_when(o => o.url == null)
  67. .when_undefined(o => o.url = null);
  68. cfg.map_many<string>("screenshots", o => o.screenshot_paths, (o, v) => o.screenshot_paths = v.to_vector())
  69. .undefined_when(o => o.screenshot_paths == null)
  70. .when_undefined(o => o.screenshot_paths = null);
  71. cfg.map<string>("icon", o => o.icon_path, (o, v) => o.icon_path = v)
  72. .undefined_when(o => o.icon_path == null)
  73. .when_undefined(o => o.icon_path = null);
  74. cfg.map<string>("metainfo", o => o.metainfo_path, (o, v) => o.metainfo_path = v)
  75. .undefined_when(o => o.metainfo_path == null)
  76. .when_undefined(o => o.metainfo_path = null);
  77. // cfg.map_with<Git>("git", o => o.git, (o, v) => o.git = v, Git.get_mapper(), false);
  78. cfg.map<Properties>("extras", o => o.extra_properties, (o, v) => o.extra_properties = v)
  79. .undefined_when(o => o.extra_properties == null)
  80. .when_undefined(o => o.extra_properties = null);
  81. cfg.set_constructor(() => new Manifest());
  82. });
  83. }
  84. public Manifest.from_file(string path) throws Error {
  85. var element = new InvercargillJson.JsonElement.from_file(path);
  86. Manifest.get_mapper().map_into(this, element.as<Invercargill.Properties>());
  87. validate();
  88. }
  89. public Manifest.from_package(string path) throws Error {
  90. var archive = new Archive.Read();
  91. archive.support_format_tar();
  92. archive.support_filter_xz();
  93. var result = archive.open_filename(path, 10240);
  94. if(result != Archive.Result.OK) {
  95. throw new ManifestError.INVALID_PACKAGE("Could not read archive");
  96. }
  97. unowned Archive.Entry entry;
  98. while(archive.next_header(out entry) == Archive.Result.OK) {
  99. var path_name = entry.pathname();
  100. if(path_name != "./MANIFEST.usm") {
  101. continue;
  102. }
  103. var manifest_blob = new ByteComposition();
  104. uint8[] buffer;
  105. Posix.off_t offset;
  106. while (archive.read_data_block (out buffer, out offset) == Archive.Result.OK) {
  107. // buffer holds just this block; offset is the block's
  108. // position within the entry, so slicing would drop every
  109. // block after the first.
  110. manifest_blob.append_byte_array(buffer);
  111. }
  112. var element = new InvercargillJson.JsonElement.from_string(manifest_blob.to_raw_string());
  113. Manifest.get_mapper().map_into(this, element.as<Invercargill.Properties>());
  114. validate();
  115. return;
  116. }
  117. throw new ManifestError.INVALID_PACKAGE("MANIFEST.usm not found within archive");
  118. }
  119. /**
  120. * Validates cross-field constraints that parsing alone cannot catch.
  121. *
  122. * Currently enforces the {@link ManifestFlag.DATA_PACKAGE} contract:
  123. * a data package must not define any lifecycle executable (build,
  124. * install, rebuild, test, remove or postInstall); the acquire
  125. * executable remains honoured. Throws
  126. * {@link ManifestError.DATA_PACKAGE_WITH_EXECUTABLE} naming every
  127. * offending executable otherwise.
  128. */
  129. public void validate() throws Error {
  130. if(!is_data_package) {
  131. return;
  132. }
  133. var defined = new Vector<string>();
  134. // bump, like acquire, is a maintainer-side executable rather than
  135. // a lifecycle one (data packages have versions too, and their
  136. // version strings live in files the bump hook rewrites), so it is
  137. // deliberately absent from the forbidden list below
  138. if(executables.build != null) {
  139. defined.add("build");
  140. }
  141. if(executables.install != null) {
  142. defined.add("install");
  143. }
  144. if(executables.rebuild != null) {
  145. defined.add("rebuild");
  146. }
  147. if(executables.test != null) {
  148. defined.add("test");
  149. }
  150. if(executables.remove != null) {
  151. defined.add("remove");
  152. }
  153. if(executables.post_install != null) {
  154. defined.add("postInstall");
  155. }
  156. if(defined.any()) {
  157. throw new ManifestError.DATA_PACKAGE_WITH_EXECUTABLE(
  158. @"Manifest \"$name\" declares the dataPackage flag, but data packages cannot define lifecycle executables (found: $(string.joinv(", ", defined.to_array()))). Only the acquire executable is permitted."
  159. );
  160. }
  161. }
  162. private void build_provides_dict(Properties obj) throws Error {
  163. provides = new Dictionary<ResourceRef, ManifestFile>();
  164. var mapper = ManifestFile.get_mapper();
  165. foreach (var pair in obj) {
  166. ManifestFile file;
  167. if(pair.value.assignable_to<string>()) {
  168. file = new ManifestFile.from_string(pair.value.as<string>());
  169. }
  170. else {
  171. file = mapper.materialise(pair.value.as<Properties>());
  172. }
  173. // Validate the ManifestFile after creation
  174. file.validate();
  175. var key = new ResourceRef(pair.key);
  176. key.ensure_valid_provide();
  177. provides[key] = file;
  178. }
  179. }
  180. /**
  181. * Whether this manifest's provides satisfy the given dependency
  182. * ref: {@link ResourceRef.satisfied_by} against every provide
  183. * key (soname tails for `lib`, `==` declarations for `pc`),
  184. * plus the pc fallback — a `pc:` provide WITHOUT a `==`
  185. * declaration is assumed to carry this package's own version.
  186. */
  187. public bool satisfies(ResourceRef dependency) {
  188. if(provides.any(r => dependency.satisfied_by(r.key))) {
  189. return true;
  190. }
  191. if(dependency.constraint != null && dependency.resource_type == ResourceType.PKG_CONFIG) {
  192. return provides.any(r => r.key.resource_type == ResourceType.PKG_CONFIG
  193. && r.key.constraint == null
  194. && r.key.resource == dependency.base_name
  195. && dependency.constraint.satisfied_by(version));
  196. }
  197. return false;
  198. }
  199. /**
  200. * The provides keys as flat matching refs: `pc:` provides
  201. * without a `==` declaration are materialised as
  202. * `pc:<name>==<package version>`, so sets collected from this
  203. * (transaction lot scheduling, removal planning) match both
  204. * plain and constrained dependencies without carrying the
  205. * manifest along.
  206. */
  207. public Enumerable<ResourceRef> effective_provides() {
  208. return provides.select<ResourceRef>(p => {
  209. if(p.key.resource_type == ResourceType.PKG_CONFIG && p.key.constraint == null) {
  210. try {
  211. return new ResourceRef(@"pc:$(p.key.resource)==$(version.to_string())");
  212. }
  213. catch(Error e) {
  214. return p.key;
  215. }
  216. }
  217. return p.key;
  218. });
  219. }
  220. private Properties map_from_provides_dict() {
  221. var dict = new PropertyDictionary();
  222. var mapper = ManifestFile.get_mapper();
  223. foreach (var pair in provides) {
  224. try {
  225. // Handle special case: when pathBase is as-expected, path is empty, and type is reg
  226. // output string "as-expected" instead of full JSON object
  227. if(pair.value.path_base == ManifestFilePathBase.AS_EXPECTED &&
  228. pair.value.path == "" &&
  229. pair.value.file_type == ManifestFileType.REGULAR) {
  230. dict.set_native<string>(pair.key.to_string(), "as-expected");
  231. } else {
  232. dict.set_native<Properties>(pair.key.to_string(), mapper.map_from(pair.value));
  233. }
  234. }
  235. catch(Error e) {
  236. assert_not_reached();
  237. }
  238. }
  239. return dict;
  240. }
  241. /**
  242. * Whether package management-script output should stream to the
  243. * terminal instead of being silenced, requested via the USM_VERBOSE
  244. * environment variable (set by `usm --verbose`, inherited by nested
  245. * invocations and spawned scripts).
  246. */
  247. private static bool verbose_requested() {
  248. var value = Environment.get_variable("USM_VERBOSE");
  249. return value != null && value.length > 0;
  250. }
  251. /**
  252. * Strips the output-silencing and -piping flags when verbose output
  253. * was requested, so script output inherits the terminal unchanged.
  254. */
  255. private static SubprocessFlags verbose_flags(SubprocessFlags flags) {
  256. if(!verbose_requested()) {
  257. return flags;
  258. }
  259. var result = flags;
  260. if((result & SubprocessFlags.STDOUT_SILENCE) != 0) {
  261. result = result & ~SubprocessFlags.STDOUT_SILENCE;
  262. }
  263. if((result & SubprocessFlags.STDOUT_PIPE) != 0) {
  264. result = result & ~SubprocessFlags.STDOUT_PIPE;
  265. }
  266. if((result & SubprocessFlags.STDERR_SILENCE) != 0) {
  267. result = result & ~SubprocessFlags.STDERR_SILENCE;
  268. }
  269. return result;
  270. }
  271. public Subprocess run_build(string build_path, Paths paths, SubprocessFlags flags, owned ProgressDelegate? progress_delegate = null) throws Error {
  272. if(executables.build == null) {
  273. throw new ManifestError.MISSING_FIELD(@"Manifest \"$name\" defines no build executable");
  274. }
  275. // Handle SIMPLE_BUILD_ENVIRONMENT flag
  276. string original_working_dir = Environment.get_current_dir();
  277. string working_dir = original_working_dir;
  278. string effective_build_path = build_path;
  279. if (this.flags.contains(ManifestFlag.SIMPLE_BUILD_ENVIRONMENT)) {
  280. // Copy the full source tree to the build directory
  281. var source_dir = File.new_for_path(working_dir);
  282. var build_dir = File.new_for_path(build_path);
  283. // Copy all files from source to build directory
  284. copy_directory(source_dir, build_dir);
  285. // Use build directory as working directory
  286. working_dir = build_path;
  287. }
  288. var path = Path.build_filename(working_dir, executables.build);
  289. // Change to the working directory for subprocess execution
  290. Environment.set_current_dir(working_dir);
  291. paths.set_envs();
  292. // Check if NINJA_STYLE_PROGRESS flag is set and progress delegate is provided
  293. if (this.flags.contains(ManifestFlag.NINJA_STYLE_PROGRESS) && progress_delegate != null && !verbose_requested()) {
  294. // Set up subprocess to capture STDOUT for progress parsing
  295. var modified_flags = flags;
  296. // Ensure STDOUT is not silenced when we need to parse progress
  297. if ((modified_flags & SubprocessFlags.STDOUT_SILENCE) != 0) {
  298. modified_flags = modified_flags & ~SubprocessFlags.STDOUT_SILENCE;
  299. }
  300. modified_flags = modified_flags | SubprocessFlags.STDOUT_PIPE;
  301. var proc = new Subprocess.newv(new string[] { path, Paths.ensure_trailing_slash(effective_build_path) }, modified_flags);
  302. // Start a new thread to monitor STDOUT for progress information
  303. ThreadFunc<void> progress_thread_func = () => {
  304. try {
  305. var stdout_pipe = proc.get_stdout_pipe();
  306. if (stdout_pipe != null) {
  307. var dis = new DataInputStream(stdout_pipe);
  308. string line;
  309. // Read lines from STDOUT until the process ends
  310. while ((line = dis.read_line(null)) != null) {
  311. // Look for Ninja progress pattern: "[x/x] "
  312. if (line.has_prefix("[")) {
  313. var end_bracket = line.index_of("]");
  314. if (end_bracket > 1) {
  315. var progress_str = line.substring(1, end_bracket - 1);
  316. var parts = progress_str.split("/");
  317. if (parts.length == 2) {
  318. int current_task = 0;
  319. int total_tasks = 0;
  320. // Parse the current and total task numbers
  321. if (int.try_parse(parts[0], out current_task) &&
  322. int.try_parse(parts[1], out total_tasks) &&
  323. total_tasks > 0) {
  324. // Calculate progress as a float between 0.0 and 1.0
  325. float progress = (float)current_task / (float)total_tasks;
  326. // Ensure progress is within valid bounds
  327. progress = float.max(0.0f, float.min(1.0f, progress));
  328. // Call the progress delegate with the calculated progress
  329. progress_delegate(progress);
  330. }
  331. }
  332. }
  333. }
  334. }
  335. }
  336. } catch (Error e) {
  337. // Log any errors during progress monitoring but don't fail the build
  338. warning(@"Error monitoring build progress: $(e.message)");
  339. }
  340. };
  341. try {
  342. // Start the progress monitoring thread
  343. new Thread<void>(null, progress_thread_func);
  344. } catch (Error e) {
  345. // If we can't start the thread, log a warning but continue with the build
  346. warning(@"Failed to start progress monitoring thread: $(e.message)");
  347. }
  348. // Restore original working directory after subprocess completes
  349. Environment.set_current_dir(original_working_dir);
  350. return proc;
  351. } else {
  352. var proc = new Subprocess.newv(new string[] { path, Paths.ensure_trailing_slash(effective_build_path) }, verbose_flags(flags));
  353. // Restore original working directory after subprocess completes
  354. Environment.set_current_dir(original_working_dir);
  355. return proc;
  356. }
  357. }
  358. public Subprocess? run_rebuild(string build_path, SubprocessFlags flags) throws Error {
  359. if(executables.rebuild == null) {
  360. return null;
  361. }
  362. string original_working_dir = Environment.get_current_dir();
  363. string working_dir = original_working_dir;
  364. if (this.flags.contains(ManifestFlag.SIMPLE_BUILD_ENVIRONMENT)) {
  365. working_dir = build_path;
  366. }
  367. var path = Path.build_filename(working_dir, executables.rebuild);
  368. // Change to the working directory for subprocess execution
  369. Environment.set_current_dir(working_dir);
  370. var proc = new Subprocess.newv(new string[] { path, Paths.ensure_trailing_slash(build_path) }, verbose_flags(flags));
  371. // Restore original working directory after subprocess completes
  372. Environment.set_current_dir(original_working_dir);
  373. return proc;
  374. }
  375. public Subprocess? run_acquire(SubprocessFlags flags) throws Error {
  376. if(executables.acquire == null) {
  377. return null;
  378. }
  379. string working_dir = Environment.get_current_dir();
  380. // Note: acquire doesn't have a build_path parameter, so it can't use SIMPLE_BUILD_ENVIRONMENT
  381. var path = Path.build_filename(working_dir, executables.acquire);
  382. var proc = new Subprocess.newv(new string[] { path }, verbose_flags(flags));
  383. return proc;
  384. }
  385. /**
  386. * Spawns the manifest's install executable with
  387. * {@link InstallType} appended to the build and install paths.
  388. *
  389. * When the manifest carries {@link ManifestFlag.NINJA_STYLE_PROGRESS}
  390. * and a {@link progress_delegate} is supplied (and USM_VERBOSE is
  391. * unset), stdout is piped and each meson-style `Installing X to Y`
  392. * line reports `lines_parsed / estimated_total` — the estimate is
  393. * the manifest's provides count doubled, since meson commonly
  394. * installs several outputs per resource. Otherwise the flags pass
  395. * through {@link verbose_flags} unchanged (silenced by default).
  396. */
  397. public Subprocess? run_install(string build_path, string install_path, Paths paths, InstallType type, SubprocessFlags flags, owned ProgressDelegate? progress_delegate = null) throws Error {
  398. if(executables.install == null) {
  399. return null;
  400. }
  401. string original_working_dir = Environment.get_current_dir();
  402. string working_dir = original_working_dir;
  403. if (this.flags.contains(ManifestFlag.SIMPLE_BUILD_ENVIRONMENT)) {
  404. working_dir = build_path;
  405. }
  406. var path = Path.build_filename(working_dir, executables.install);
  407. // Override destination environment variable
  408. var new_paths = paths.clone();
  409. new_paths.destination = install_path;
  410. // Change to the working directory for subprocess execution
  411. Environment.set_current_dir(working_dir);
  412. new_paths.set_envs();
  413. var parse_install_progress = progress_delegate != null
  414. && this.flags != null
  415. && this.flags.contains(ManifestFlag.NINJA_STYLE_PROGRESS)
  416. && !verbose_requested();
  417. var spawn_flags = flags;
  418. if(parse_install_progress) {
  419. if ((spawn_flags & SubprocessFlags.STDOUT_SILENCE) != 0) {
  420. spawn_flags = spawn_flags & ~SubprocessFlags.STDOUT_SILENCE;
  421. }
  422. spawn_flags = spawn_flags | SubprocessFlags.STDOUT_PIPE;
  423. }
  424. else {
  425. spawn_flags = verbose_flags(flags);
  426. }
  427. var proc = new Subprocess.newv(new string[] { path, Paths.ensure_trailing_slash(build_path), Paths.ensure_trailing_slash(install_path), type.to_string() }, spawn_flags);
  428. if(parse_install_progress) {
  429. // Drain the pipe before returning: meson holds stdout
  430. // open until it exits, so EOF aligns with the caller's
  431. // wait_check
  432. uint estimated_total = provides.count() * 2;
  433. if(estimated_total < 1) {
  434. estimated_total = 1;
  435. }
  436. uint lines_parsed = 0;
  437. var output = new DataInputStream(proc.get_stdout_pipe());
  438. string line;
  439. while((line = output.read_line(null)) != null) {
  440. if(!line.has_prefix("Installing ")) {
  441. continue;
  442. }
  443. lines_parsed++;
  444. var fraction = (float)lines_parsed / (float)estimated_total;
  445. progress_delegate(fraction > 1.0f ? 1.0f : fraction);
  446. }
  447. }
  448. // Restore original working directory after subprocess completes
  449. Environment.set_current_dir(original_working_dir);
  450. return proc;
  451. }
  452. public Subprocess? run_post_install(string build_path, InstallType type, SubprocessFlags flags) throws Error {
  453. if(executables.post_install == null) {
  454. return null;
  455. }
  456. string original_working_dir = Environment.get_current_dir();
  457. string working_dir = original_working_dir;
  458. if (this.flags.contains(ManifestFlag.SIMPLE_BUILD_ENVIRONMENT)) {
  459. working_dir = build_path;
  460. }
  461. var path = Path.build_filename(working_dir, executables.post_install);
  462. // Change to the working directory for subprocess execution
  463. Environment.set_current_dir(working_dir);
  464. var proc = new Subprocess.newv(new string[] { path, Paths.ensure_trailing_slash(build_path), type.to_string() }, verbose_flags(flags));
  465. // Restore original working directory after subprocess completes
  466. Environment.set_current_dir(original_working_dir);
  467. return proc;
  468. }
  469. public Subprocess? run_remove(RemoveType type, SubprocessFlags flags) throws Error {
  470. if(executables.remove == null) {
  471. return null;
  472. }
  473. string working_dir = Environment.get_current_dir();
  474. // Note: remove doesn't have a build_path parameter, so it can't use SIMPLE_BUILD_ENVIRONMENT
  475. var path = Path.build_filename(working_dir, executables.remove);
  476. var proc = new Subprocess.newv(new string[] { path, type.to_string() }, verbose_flags(flags));
  477. return proc;
  478. }
  479. public Subprocess? run_test(string build_path, SubprocessFlags flags) throws Error {
  480. if(executables.test == null) {
  481. return null;
  482. }
  483. string original_working_dir = Environment.get_current_dir();
  484. string working_dir = original_working_dir;
  485. if (this.flags.contains(ManifestFlag.SIMPLE_BUILD_ENVIRONMENT)) {
  486. working_dir = build_path;
  487. }
  488. var path = Path.build_filename(working_dir, executables.test);
  489. // Change to the working directory for subprocess execution
  490. Environment.set_current_dir(working_dir);
  491. var proc = new Subprocess.newv(new string[] { path, Paths.ensure_trailing_slash(build_path) }, verbose_flags(flags));
  492. // Restore original working directory after subprocess completes
  493. Environment.set_current_dir(original_working_dir);
  494. return proc;
  495. }
  496. public delegate void ResourceProgressCallback(ResourceRef resource, uint current_resource, uint total_resources, float resource_frac);
  497. /**
  498. * The destination paths {@link install_resources} will affect,
  499. * split by what it will do to each: paths collected in
  500. * {@link created} do not exist yet and will appear, paths in
  501. * {@link overwritten} exist and will have their content
  502. * replaced. The same ordering and the same
  503. * {@link Paths.get_suggested_path_for_resource} resolution
  504. * drive both methods, so a transaction journal can record — and
  505. * back up — everything before the install runs. Directory
  506. * provides are not reported: an empty directory is neither worth
  507. * a backup nor worth deleting on rollback, and parent
  508. * directories created implicitly for new files are left behind
  509. * the same way.
  510. */
  511. public void report_install_resources(Paths paths, out Vector<string> created, out Vector<string> overwritten) {
  512. created = new Vector<string>();
  513. overwritten = new Vector<string>();
  514. var seen = new HashSet<string>();
  515. var install_order = provides.sort((a, b) => paths.get_suggested_path_for_resource(a.key).length - paths.get_suggested_path_for_resource(b.key).length);
  516. foreach(var resource in install_order) {
  517. if(resource.value.file_type == Usm.ManifestFileType.DIRECTORY) {
  518. continue;
  519. }
  520. var path = paths.get_suggested_path_for_resource(resource.key);
  521. if(seen.contains(path)) {
  522. continue;
  523. }
  524. seen.add(path);
  525. if(File.new_for_path(path).query_exists()) {
  526. overwritten.add(path);
  527. }
  528. else {
  529. created.add(path);
  530. }
  531. }
  532. }
  533. public void install_resources(string source_path, string build_path, string? install_path, Paths paths, ResourceProgressCallback callback, bool dry_run = false) throws Error {
  534. // Install each resource speficied by the manifest
  535. var resource_count = provides.count();
  536. var resources_installed = 0;
  537. // Install from shortest path to longest path, to ensure directories are created before children
  538. var install_order = provides.sort((a, b) => paths.get_suggested_path_for_resource(a.key).length - paths.get_suggested_path_for_resource(b.key).length);
  539. foreach (var resource in install_order) {
  540. callback(resource.key, resources_installed, resource_count, 0.0f);
  541. var path = paths.get_suggested_path_for_resource(resource.key);
  542. if(resource.key.resource_type == ResourceType.TAG) {
  543. // Ensure parent directories are created first
  544. var parent_dir = File.new_for_path(Path.get_basename(path));
  545. if(!parent_dir.query_exists() && !dry_run) {
  546. parent_dir.make_directory_with_parents();
  547. }
  548. }
  549. if(resource.value.file_type == Usm.ManifestFileType.REGULAR) {
  550. var base_path = "";
  551. if(is_data_package) {
  552. // Data packages ship every provide directly from the source
  553. // (or unpacked package) tree, regardless of declared path base
  554. base_path = source_path;
  555. }
  556. else {
  557. switch (resource.value.path_base) {
  558. case ManifestFilePathBase.BUILD:
  559. base_path = build_path;
  560. break;
  561. case ManifestFilePathBase.SOURCE:
  562. base_path = source_path;
  563. break;
  564. case ManifestFilePathBase.INSTALL:
  565. if(install_path == null) {
  566. throw new ManifestError.INVALID_FILE_PATH("Install path was not provided");
  567. }
  568. base_path = install_path;
  569. break;
  570. case ManifestFilePathBase.AS_EXPECTED:
  571. if(install_path == null) {
  572. throw new ManifestError.INVALID_FILE_PATH("Install path was not provided");
  573. }
  574. var install_paths = paths.clone();
  575. install_paths.destination = install_path;
  576. base_path = install_paths.get_suggested_path_for_resource(resource.key);
  577. break;
  578. default:
  579. assert_not_reached();
  580. }
  581. }
  582. var src = File.new_build_filename(base_path, resource.value.path ?? "");
  583. var dest = File.new_for_path(path);
  584. // Don't throw if an alternative format resource wasn't built
  585. var source_exists = src.query_exists();
  586. if(!source_exists) {
  587. throw new ManifestError.INVALID_FILE_PATH(@"Expected to find file listed in manifest at \"$(src.get_path())\", but no such file was found.");
  588. }
  589. // Don't copy an alternative format resource if it has the same path as the non-alternative resource
  590. if(source_exists && !dry_run) {
  591. if(dest.query_exists()) {
  592. dest.delete();
  593. }
  594. var parent = dest.get_parent();
  595. if(!parent.query_exists()) {
  596. parent.make_directory_with_parents(null);
  597. }
  598. src.copy(dest, FileCopyFlags.ALL_METADATA, null, (c, t) => callback(resource.key, resources_installed, resource_count, (float)c / (float)t));
  599. }
  600. }
  601. else if(resource.value.file_type == Usm.ManifestFileType.DIRECTORY) {
  602. var dest = File.new_for_path(path);
  603. if(!dry_run && !dest.query_exists()) {
  604. dest.make_directory();
  605. }
  606. }
  607. else if(resource.value.file_type == Usm.ManifestFileType.SYMBOLIC_LINK) {
  608. var dest = File.new_for_path(path);
  609. if(!dry_run && dest.query_exists()) {
  610. dest.delete();
  611. }
  612. if(!dry_run){
  613. dest.make_symbolic_link(resource.value.destination ?? "");
  614. }
  615. }
  616. else {
  617. throw new TransactionError.INSTALL_ERROR(@"Could not understand resource key \"$(resource.key)\"");
  618. }
  619. callback(resource.key, resources_installed, resource_count, 1.0f);
  620. resources_installed++;
  621. }
  622. }
  623. /**
  624. * The destination paths {@link remove_resources} will delete:
  625. * every non-directory provide that currently exists, files and
  626. * symbolic links alike, in the same files-before-directories
  627. * removal order. Paths whose destination is already gone (or a
  628. * dangling link, which {@link remove_resources} cannot see
  629. * either) are not reported — there is nothing to back up.
  630. */
  631. public Vector<string> report_remove_resources(Paths paths) {
  632. var removed = new Vector<string>();
  633. var non_directories = provides.where(r => r.value.file_type != Usm.ManifestFileType.DIRECTORY);
  634. foreach(var resource in non_directories) {
  635. var path = paths.get_suggested_path_for_resource(resource.key);
  636. if(File.new_for_path(path).query_exists()) {
  637. removed.add(path);
  638. }
  639. }
  640. return removed;
  641. }
  642. public void remove_resources(Paths paths, ResourceProgressCallback callback) throws Error {
  643. var non_directories = provides.where(r => r.value.file_type != Usm.ManifestFileType.DIRECTORY).cache();
  644. var directories = provides.where(r => r.value.file_type == Usm.ManifestFileType.DIRECTORY).cache();
  645. var total_operations = non_directories.count() + directories.count();
  646. var current_operation = 0;
  647. // Delete files and symlinks first
  648. foreach (var resource in non_directories) {
  649. callback(resource.key, current_operation, total_operations, 0.0f);
  650. var path = paths.get_suggested_path_for_resource(resource.key);
  651. var file = File.new_for_path(path);
  652. if(file.query_exists()) {
  653. file.delete();
  654. }
  655. callback(resource.key, current_operation, total_operations, 1.0f);
  656. current_operation++;
  657. }
  658. // Delete directories last
  659. foreach (var resource in directories) {
  660. callback(resource.key, current_operation, total_operations, 0.0f);
  661. var path = paths.get_suggested_path_for_resource(resource.key);
  662. try {
  663. var file = File.new_for_path(path);
  664. if(file.query_exists()) {
  665. file.delete();
  666. }
  667. }
  668. catch(IOError.NOT_EMPTY e) {
  669. warning(@"Did not remove resource \"$path\": directory is not empty\n");
  670. }
  671. callback(resource.key, current_operation, total_operations, 1.0f);
  672. current_operation++;
  673. }
  674. }
  675. private void copy_directory(File source, File destination) throws Error {
  676. // Ensure destination directory exists
  677. if (!destination.query_exists()) {
  678. destination.make_directory_with_parents();
  679. }
  680. var enumerator = source.enumerate_children(FileAttribute.STANDARD_NAME + "," + FileAttribute.STANDARD_TYPE, FileQueryInfoFlags.NONE);
  681. FileInfo file_info;
  682. while ((file_info = enumerator.next_file()) != null) {
  683. var source_child = source.get_child(file_info.get_name());
  684. var destination_child = destination.get_child(file_info.get_name());
  685. if (file_info.get_file_type() == FileType.DIRECTORY) {
  686. // Recursively copy subdirectories
  687. copy_directory(source_child, destination_child);
  688. } else {
  689. // Copy files
  690. source_child.copy(destination_child, FileCopyFlags.OVERWRITE | FileCopyFlags.ALL_METADATA);
  691. }
  692. }
  693. }
  694. }
  695. public enum InstallType {
  696. FRESH,
  697. UPGRADE,
  698. DOWNGRADE;
  699. public string to_string() {
  700. switch (this) {
  701. case InstallType.FRESH:
  702. return "fresh";
  703. case InstallType.UPGRADE:
  704. return "upgrade";
  705. case InstallType.DOWNGRADE:
  706. return "downgrade";
  707. default:
  708. assert_not_reached();
  709. }
  710. }
  711. public static InstallType from_string(string str) throws ManifestError {
  712. switch (str) {
  713. case "fresh":
  714. return InstallType.FRESH;
  715. case "upgrade":
  716. return InstallType.UPGRADE;
  717. case "downgrade":
  718. return InstallType.DOWNGRADE;
  719. default:
  720. throw new ManifestError.INVALID_REMOVE_TYPE(@"Unknown install type \"$str\".");
  721. }
  722. }
  723. }
  724. public enum RemoveType {
  725. FINAL,
  726. UPGRADE,
  727. DOWNGRADE;
  728. public string to_string() {
  729. switch (this) {
  730. case RemoveType.FINAL:
  731. return "final";
  732. case RemoveType.UPGRADE:
  733. return "upgrade";
  734. case RemoveType.DOWNGRADE:
  735. return "downgrade";
  736. default:
  737. assert_not_reached();
  738. }
  739. }
  740. public static RemoveType from_string(string str) throws ManifestError {
  741. switch (str) {
  742. case "final":
  743. return RemoveType.FINAL;
  744. case "upgrade":
  745. return RemoveType.UPGRADE;
  746. case "downgrade":
  747. return RemoveType.DOWNGRADE;
  748. default:
  749. throw new ManifestError.INVALID_REMOVE_TYPE(@"Unknown remove type \"$str\".");
  750. }
  751. }
  752. }
  753. public delegate void ProgressDelegate(float progress);
  754. public enum ManifestFlag {
  755. BUILD_IN_SOURCE_TREE,
  756. SET_MANIFEST_PROPERTY_ENVS,
  757. NINJA_STYLE_PROGRESS,
  758. SIMPLE_BUILD_ENVIRONMENT,
  759. DATA_PACKAGE,
  760. /**
  761. * Installing or updating this package also rebuilds every installed
  762. * package whose "depends" refs match any of its provides keys (see
  763. * {@link SystemState.find_dependant_names}); the flag lives on the
  764. * dependency, not on its dependants.
  765. */
  766. REBUILD_DEPENDANTS;
  767. public string to_string() {
  768. switch (this) {
  769. case ManifestFlag.BUILD_IN_SOURCE_TREE:
  770. return "buildInSourceTree";
  771. case ManifestFlag.SET_MANIFEST_PROPERTY_ENVS:
  772. return "setManifestPropertyEnvs";
  773. case ManifestFlag.NINJA_STYLE_PROGRESS:
  774. return "ninjaStyleProgress";
  775. case ManifestFlag.SIMPLE_BUILD_ENVIRONMENT:
  776. return "simpleBuildEnvironment";
  777. case ManifestFlag.DATA_PACKAGE:
  778. return "dataPackage";
  779. case ManifestFlag.REBUILD_DEPENDANTS:
  780. return "rebuildDependants";
  781. default:
  782. assert_not_reached();
  783. }
  784. }
  785. public static ManifestFlag from_string(string str) throws ManifestError {
  786. switch (str) {
  787. case "buildInSourceTree":
  788. return ManifestFlag.BUILD_IN_SOURCE_TREE;
  789. case "setManifestPropertyEnvs":
  790. return ManifestFlag.SET_MANIFEST_PROPERTY_ENVS;
  791. case "ninjaStyleProgress":
  792. return ManifestFlag.NINJA_STYLE_PROGRESS;
  793. case "simpleBuildEnvironment":
  794. return ManifestFlag.SIMPLE_BUILD_ENVIRONMENT;
  795. case "dataPackage":
  796. return ManifestFlag.DATA_PACKAGE;
  797. case "rebuildDependants":
  798. return ManifestFlag.REBUILD_DEPENDANTS;
  799. default:
  800. throw new ManifestError.INVALID_FLAG(@"Unknown flag \"$str\".");
  801. }
  802. }
  803. }
  804. }