#! @file workspace.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the workspace: the project a command is given, and every project it #! requires, read depth first, each once, from a folder beside it or from the #! store, where a remote is cloned the first time it's required; and every #! library they hold, by name, which their programs read through `--lib`. import std; import std::io; import std::process; import system; import blossom::models; module blossom::management; #! Why a command can't go on, and the status it ends with: 1 where something #! failed, as a clone, and 2 where a blossomfile or the command is wrong. pub struct failure { pub var status: i32; pub var message: string; } #! A library some project of the workspace holds. pub struct library { pub var name: string; #! Its name, as `hello.geometry`. pub var project: u64; #! The project holding it. pub var target: u64; #! The target it is, among the project's. } #! A requirement a command came to: a folder beside the project requiring it, #! or a remote's clone in the store, and whether the command cloned it. pub struct requirement_found { pub var remote: string; #! The remote, or the folder as its blossomfile writes it. pub var branch: string; #! The branch or tag cloned, or empty for a folder. pub var folder: path; #! Where it is. pub var local: bool; #! Whether it's a folder rather than a remote. pub var cloned: bool; #! Whether the command cloned it. pub var updated: bool; #! Whether that clone took the place of one the store held. } #! The projects a command reads: the one given first, then those it requires. pub struct workspace { pub var projects: vector; pub var libraries: vector; pub var platform: string; #! What `--target` says, or empty. pub var verbose: bool; #! Whether each command run is printed. pub var found: vector; #! Each requirement come to, in the order it was. pub var missing: vector; #! Each remote the store is missing, as `REMOTE@BRANCH`, where nothing is cloned. var offline: bool; #! Whether nothing is cloned: what the store is missing is noted, and not read. var update: bool; #! Whether what the store holds is cloned again, as a branch that moved wants. var wanted: vector; #! The given project's own requirements read, by name; all where empty. } #! Reads a project and everything it requires, then indexes their libraries. #! @param folder The project's folder. #! @param overrides Values for its options, as `-o` gives them. #! @param platform What `--target` says, or empty. #! @param verbose Whether each command run is printed. #! @returns The workspace, whose first project is the one given, or why it #! can't be read. pub def open_workspace( folder: &path, overrides: span, platform: strview, verbose: bool ): result { return open_workspace_with(folder, overrides, platform, verbose, false, false, span::::empty()); } #! Reads a project and what it requires, as `open_workspace` does, coming to #! what it requires as asked: cloning nothing, cloning again what the store #! holds, or reading only some of what the project itself requires. #! @param folder The project's folder. #! @param overrides Values for its options, as `-o` gives them. #! @param platform What `--target` says, or empty. #! @param verbose Whether each command run is printed. #! @param offline Whether nothing is cloned: a remote the store is missing is #! noted in `missing`, and neither it nor what it requires is #! read. #! @param update Whether each remote the store holds is cloned again. #! @param wanted The project's own requirements to read, each named as #! `names_requirement` takes it, or none for every one. #! @returns The workspace, or why it can't be read, as where a name given is #! none of the project's requirements. pub def open_workspace_with( folder: &path, overrides: span, platform: strview, verbose: bool, offline: bool, update: bool, wanted: span ): result { var made := workspace { projects = vector::::new(), libraries = vector::::new(), platform = string::from(platform, nothing {}), verbose = verbose, found = vector::::new(), missing = vector::::new(), offline = offline, update = update, wanted = vector::::new() }; for each in wanted { made.wanted.append(string::from(each, nothing {})); } var loaded := made.load(folder, overrides, strview::empty(), true); if loaded is error(&mut why) { return move(why); } var indexed := made.index(); if indexed is error(&mut why) { return move(why); } return move(made); } #! The project the command was given. #! @param this The workspace. #! @returns It. pub def workspace::root(&this): &models::project { return &this.projects[0]; } # Reads the project in a folder, then each it requires, giving where it is # among the projects. One read before is given again, where its options are # the same. A project another requires reads what it requires only where its # libraries read what it doesn't hold itself, so what only its tests or # programs need is never fetched for those requiring it. def workspace::load(&mut this, folder: &path, overrides: span, by: strview, root: bool): result { val absolute := io::absolute(folder) else (why) { return failure { status = 2, message = $"`{folder.view()}` can't be found: {why}." }; }; val file := absolute.join("blossomfile"); val text := io::read_file(&file) else (why) { val whose := by.length != 0 ? $", which {by} requires," : string::new(nothing {}); return failure { status = 2, message = $"`{absolute.view()}`{whose.view()} holds no blossomfile to read: {why}." }; }; var read := models::read_project(text.view(), &file, overrides, this.platform.view()); if read is error(&problem) { return failure { status = 2, message = problem.describe() }; } if read is not value(&mut made) { return failure { status = 2, message = string::from("The blossomfile couldn't be read.", nothing {}) }; } # A project is read once, and given one set of values for its options, since # each set builds its own outputs. for k in 0..this.projects.length { val prior := &this.projects[k]; continue if prior.folder != made.folder; if !same_options(prior.options.view(), made.options.view()) { return failure { status = 2, message = $"{made.identity.view()} is required with two sets of option values: {described(prior.options.view()).view()}, and {described(made.options.view()).view()} by {by}." }; } return k; } val index := this.projects.length; this.projects.append(move(made)); return index if !root && !needs_requirements(&this.projects[index]); # Each name given for the project's own requirements names one of them. if root { for &name in this.wanted { var named := false; for &each in this.projects[index].requires { named = named || names_requirement(name.view(), &each); } if !named { return failure { status = 2, message = $"`{name.view()}` is no requirement of {this.projects[index].identity.view()}: {requirements_of(&this.projects[index]).view()}." }; } } } # Each requirement is taken out before the next is read, since reading one # adds projects, which may move those before it. val count := this.projects[index].requires.length; for k in 0..count { val required := &this.projects[index].requires[k]; continue if root && !this.wants(required); val remote := string::copy_of(&required.remote); val branch := string::copy_of(&required.branch); val local := required.local; val line := required.line; var options := vector::::new(); for &each in required.options { options.append(models::setting { name = string::copy_of(&each.name), value = string::copy_of(&each.value) }); } val requirer := this.projects[index].identity; var found := path::new(); if local { val named := path::parse(remote.view()) else (_) { return failure { status = 2, message = $"{this.projects[index].file.view()}:{line}: `{remote.view()}` is no folder." }; }; found = this.projects[index].folder.join(&named); this.found.append(requirement_found { remote = string::copy_of(&remote), branch = string::new(nothing {}), folder = path::copy_of(&found), local = true }); } else { # Cloning nothing, a remote the store is missing is noted, and neither it # nor what it requires is read. if this.offline { var stored := store_path(remote.view(), branch.view()); if stored is error(&mut why) { return move(why); } val at := stored.unwrap(); if !io::exists(&at) { this.note_missing(remote.view(), branch.view()); continue; } } var fetched := this.fetch(remote.view(), branch.view()); if fetched is error(&mut why) { return move(why); } found = fetched.unwrap(); } var loaded := this.load(&found, options.view(), requirer.view(), false); if loaded is error(&mut why) { return move(why); } } return index; } # The folder of the store a remote's branch is cloned into. def store_path(remote: strview, branch: strview): result { val folder := cache_folder() else { when os == windows { return failure { status = 2, message = string::from("There's no store to clone into: `LOCALAPPDATA` isn't set.", nothing {}) }; } return failure { status = 2, message = string::from("There's no store to clone into: neither `XDG_CACHE_HOME` nor `HOME` is set.", nothing {}) }; }; val key := store_key(remote, branch); val stored := path::parse(key.view()) else (_) { return failure { status = 2, message = $"`{remote}` can't name a folder of the store." }; }; return folder.join(&stored); } # Finds a remote's clone in the store, cloning it where it's missing, or where # it's asked to be cloned again: into a folder beside it first, renamed once the # clone is whole, so one stopped halfway is never taken for a clone. A clone # made again takes the old one's place only once it's whole, too. A remote # required twice is come to once. def workspace::fetch(&mut this, remote: strview, branch: strview): result { for &each in this.found { return path::copy_of(&each.folder) if !each.local && each.remote.view() == remote && each.branch.view() == branch; } var stored := store_path(remote, branch); if stored is error(&mut why) { return move(why); } val into := stored.unwrap(); val there := io::exists(&into); if there && !this.update { this.found.append(requirement_found { remote = string::from(remote, nothing {}), branch = string::from(branch, nothing {}), folder = path::copy_of(&into) }); return into; } val partial := path::parse($"{into.view()}.partial".view()) else (_) { return failure { status = 2, message = $"`{remote}` can't name a folder of the store." }; }; _ = remove_tree(&partial); if partial.parent() is some(&above) { _ = io::create_directories(above); } val saying := there ? $"Cloning {remote}@{branch} again" : $"Cloning {remote}@{branch}"; io::println(saying.view()); # A tag's clone is of no branch, which git explains at length even when quiet. var git := process::command::new("git"); git.arguments(["-c", "advice.detachedHead=false", "clone", "--quiet", "-b", branch, "--depth", "1", remote, partial.view()]); if this.verbose { io::println($"git -c advice.detachedHead=false clone --quiet -b {branch} --depth 1 {remote} {partial.view()}".view()); } val status := git.run() else (why) { return failure { status = 1, message = $"git can't be run, to clone `{remote}`: {why}." }; }; if !status.succeeded { _ = remove_tree(&partial); return failure { status = 1, message = $"Cloning {remote}@{branch} failed." }; } if there { # The store's clone is put aside for the new one, and given back where the # new one can't take its place. val aside := path::parse($"{into.view()}.old".view()) else (_) { return failure { status = 2, message = $"`{remote}` can't name a folder of the store." }; }; _ = remove_tree(&aside); if io::rename(&into, &aside) is error(why) { _ = remove_tree(&partial); return failure { status = 1, message = $"The clone of `{remote}` at `{into.view()}` can't be moved aside: {why}." }; } if io::rename(&partial, &into) is error(why) { _ = io::rename(&aside, &into); return failure { status = 1, message = $"The clone of `{remote}` can't be moved to `{into.view()}`: {why}." }; } _ = remove_tree(&aside); } else if io::rename(&partial, &into) is error(why) { return failure { status = 1, message = $"The clone of `{remote}` can't be moved to `{into.view()}`: {why}." }; } this.found.append(requirement_found { remote = string::from(remote, nothing {}), branch = string::from(branch, nothing {}), folder = path::copy_of(&into), cloned = true, updated = there }); return into; } # Notes a remote the store is missing, once. def workspace::note_missing(&mut this, remote: strview, branch: strview): void { var named := $"{remote}@{branch}"; for &each in this.missing { return if each == named; } this.missing.append(move(&mut named)); } # Whether a requirement of the given project is one to read: one a name given # names, or any where none is. def workspace::wants(&this, required: &models::requirement): bool { return true if this.wanted.length == 0; for &name in this.wanted { return true if names_requirement(name.view(), required); } return false; } #! Whether a name names a requirement: its remote or folder as its blossomfile #! writes it, a remote with its branch after `@`, or the last part of its path, #! without `.git`, with or without the branch, as `sakura-analyzer` or #! `sakura-analyzer@v1.0.0` of `https://host/malunal/sakura-analyzer@v1.0.0`. #! @param name The name. #! @param required The requirement. #! @returns Whether it names it. pub def names_requirement(name: strview, required: &models::requirement): bool { val remote := required.remote.view(); val last := last_part(remote); return true if name == remote || name == last; return false if required.local; val full := $"{remote}@{required.branch.view()}"; val short := $"{last}@{required.branch.view()}"; return name == full.view() || name == short.view(); } # The last part of a remote's path or a folder's, without `.git`. def last_part(text: strview): strview { var end := text.length; while end > 0 && (text[end - 1] == '/' || text[end - 1] == '\\') { end--; } var start := end; while start > 0 && text[start - 1] != '/' && text[start - 1] != '\\' && text[start - 1] != ':' { start--; } val part := text.substr(start, end - start); return part.ends_with(".git") ? part.substr(0, part.length - 4) : part; } # What a project requires, as a failure lists it: `it requires A, B`, or that # it requires nothing. def requirements_of(holder: &models::project): string { if holder.requires.length == 0 { return string::from("it requires nothing", nothing {}); } var made := string::from("it requires ", nothing {}); for k in 0..holder.requires.length { if k != 0 { made.append(", "); } val each := &holder.requires[k]; made.push('`'); made.append(each.remote.view()); if !each.local { made.push('@'); made.append(each.branch.view()); } made.push('`'); } return made; } # Whether a project's libraries read one it doesn't hold, which one it requires # must, so what it requires is read. def needs_requirements(holder: &models::project): bool { for &each in holder.targets { continue if each.kind != models::target_kind::library; for &name in each.deps { continue if name == "std"; var own := false; for &other in holder.targets { own = own || (other.kind == models::target_kind::library && other.name == name); } return true if !own; } } return false; } # Indexes every library of the workspace's projects by name, refusing a name # two projects give. def workspace::index(&mut this): result { for p in 0..this.projects.length { val holder := &this.projects[p]; for t in 0..holder.targets.length { val each := &holder.targets[t]; continue if each.kind != models::target_kind::library; for &prior in this.libraries { if prior.name == each.name { return failure { status = 2, message = $"`{each.name.view()}` is a library of both {this.projects[prior.project].identity.view()} and {holder.identity.view()}." }; } } this.libraries.append(library { name = string::copy_of(&each.name), project = p, target = t }); } } return; } #! Finds a library by its name. #! @param this The workspace. #! @param name The name. #! @returns Where it is among the libraries, or `nothing`. pub def workspace::library_named(&this, name: strview): maybe { for k in 0..this.libraries.length { return k if this.libraries[k].name.view() == name; } return nothing {}; } #! Gathers every library a target reads, through the `deps` of each, each once: #! those of its own project, and those other projects export. #! @param this The workspace. #! @param project The project holding the target. #! @param deps The target's `deps`. #! @param who The target's name, for what's said where one is wrong. #! @param into Where each library's place among the libraries is added. #! @param lenient Whether a library no project holds is passed over, as one a #! requirement missing from the store may hold. #! @returns Why one can't be read, where one can't. pub def workspace::reach( &this, project: u64, deps: span, who: strview, into: &mut vector, lenient: bool = false ): result { for &name in deps { continue if name == "std"; val found := this.library_named(name.view()) else { continue if lenient; return failure { status = 2, message = $"`{name.view()}`, which `{who}` reads, is no library of {this.projects[project].identity.view()} or of what it requires." }; }; val held := &this.libraries[found]; if held.project != project && !this.projects[held.project].exported(name.view()) { return failure { status = 2, message = $"`{name.view()}`, which `{who}` reads, isn't exported by {this.projects[held.project].identity.view()}." }; } var seen := false; for &prior in into { seen = seen || prior == found; } continue if seen; into.append(found); val target := &this.projects[held.project].targets[held.target]; var reached := this.reach(held.project, target.deps.view(), name.view(), into, lenient); if reached is error(&mut why) { return move(why); } } return; } #! Gathers every library a project holds or reads, each once: its own, then #! those its targets and tests read through their `deps`, each followed by what #! it reads in turn, as `reach` finds them. Where a requirement is missing from #! the store, a library no project holds is passed over, as it may hold it. #! @param this The workspace. #! @param project The project. #! @param into Where each library's place among the libraries is added. #! @returns Why one can't be read, where one can't. pub def workspace::read_by(&this, project: u64, into: &mut vector): result { val holder := &this.projects[project]; var own := vector::::new(); for &each in holder.targets { if each.kind == models::target_kind::library { own.append(string::copy_of(&each.name)); } } val lenient := this.missing.length != 0; var reached := this.reach(project, own.view(), holder.identity.view(), into, lenient); if reached is error(&mut why) { return move(why); } for &each in holder.targets { reached = this.reach(project, each.deps.view(), each.name.view(), into, lenient); if reached is error(&mut why) { return move(why); } } for &each in holder.tests { reached = this.reach(project, each.deps.view(), each.name.view(), into, lenient); if reached is error(&mut why) { return move(why); } } return; } #! The folder a library's modules are in. #! @param this The workspace. #! @param index Where the library is among the libraries. #! @param from The project whose folder `sakura` runs in, which its own #! libraries are written relative to. #! @returns The folder: relative to that project's where it's that project's #! own, and absolute otherwise. pub def workspace::library_folder(&this, index: u64, from: u64): path { val held := &this.libraries[index]; val holder := &this.projects[held.project]; val root := path::parse(holder.targets[held.target].root.view()) else (_) { return path::new(); }; if held.project == from { return root; } return holder.folder.join(&root); } #! The `--lib` a library is given by: its module, with `::` for `.`, and its #! folder. #! @param this The workspace. #! @param index Where the library is among the libraries. #! @param from The project whose folder `sakura` runs in. #! @returns As `hello::geometry=hello.geometry`. pub def workspace::lib_option(&this, index: u64, from: u64): string { var made := this.module_of(index); made.push('='); made.append(this.library_folder(index, from).view()); return made; } #! The `--lib` a library is given by, its folder absolute with no `..` left, as #! a program running anywhere, as an editor's language server, wants it. #! @param this The workspace. #! @param index Where the library is among the libraries. #! @returns As `hello::geometry=/home/me/hello/hello.geometry`. pub def workspace::absolute_lib_option(&this, index: u64): string { # No project is the one past the last, so the folder is joined onto its own # project's, which is absolute. val joined := this.library_folder(index, this.projects.length); val folder := joined.resolve(&joined); var made := this.module_of(index); made.push('='); made.append(folder.view()); return made; } # A library's module, its name with `::` for `.`. def workspace::module_of(&this, index: u64): string { var made := string::new(nothing {}); for k in 0..this.libraries[index].name.length { val byte := this.libraries[index].name[k]; if byte == '.' { made.append("::"); } else { made.push(byte); } } return made; } #! The folder of the store a remote's branch is cloned into: its host and path, #! then `@` and the branch, as `git.malunal.studio/malunal/json@v1.0.0`, with #! any scheme, user, and `.git` left out, and anything that's no name's taken #! out, so no remote reaches outside the store. #! @param remote The remote, as `https://host/path`, `git@host:path`, or #! `file:///path`. #! @param branch The branch or tag. #! @returns The folder, relative to the store. pub def store_key(remote: strview, branch: strview): string { var rest := remote; var scheme := strview::empty(); if rest.find("://") is some(at) { scheme = rest.substr(0, at); rest = rest.substr(at + 3, rest.length - at - 3); } else if rest.find(":") is some(at) { # `user@host:path`, as ssh writes it. var host := rest.substr(0, at); if host.find("@") is some(user) { host = host.substr(user + 1, host.length - user - 1); } var joined := string::from(host, nothing {}); joined.push('/'); joined.append(rest.substr(at + 1, rest.length - at - 1)); return finished_key(joined.view(), strview::empty(), branch); } if scheme != "file" { val slash := rest.find("/") else { return finished_key(rest, scheme, branch); }; var host := rest.substr(0, slash); if host.find("@") is some(user) { host = host.substr(user + 1, host.length - user - 1); var joined := string::from(host, nothing {}); joined.append(rest.substr(slash, rest.length - slash)); return finished_key(joined.view(), scheme, branch); } } return finished_key(rest, scheme, branch); } # A store's folder from a remote's host and path: each segment a name, `.` and # `..` left out, and `.git` taken off the end, then `@` and the branch. def finished_key(text: strview, scheme: strview, branch: strview): string { var made := string::new(nothing {}); if scheme == "file" { made.append("file"); } for part in text.split('/') { continue if part.length == 0 || part == "." || part == ".."; if made.length != 0 { made.push('/'); } for k in 0..part.length { val byte := part[k]; made.push(byte.is_alnum || byte == '.' || byte == '-' || byte == '_' || byte == '+' ? byte : '_'); } } if made.view().ends_with(".git") { made.resize(made.length - 4); } made.push('@'); for k in 0..branch.length { val byte := branch[k]; made.push(byte.is_alnum || byte == '.' || byte == '-' || byte == '_' || byte == '+' ? byte : '_'); } return made; } # Whether two projects' option values are the same. def same_options(a: span, b: span): bool { return false if a.length != b.length; for k in 0..a.length { return false if a[k].name != b[k].name || a[k].value != b[k].value; } return true; } # Option values, as `level=2 debug=false`. def described(options: span): string { var made := string::new(nothing {}); for &each in options { if made.length != 0 { made.push(' '); } made.append($"{each.name.view()}={each.value.view()}".view()); } if made.length == 0 { made.append("none"); } return made; } #! Removes a file, or a folder and everything in it. Links are removed, not #! followed. #! @param at What to remove. #! @returns Why it couldn't all be removed, where it couldn't. pub def remove_tree(at: &path): result { val found := io::info(at, false) else (why) { if why == io_error::not_found { return; } return why; }; if found.kind == file_kind::directory { var names := vector::::new(); var listing := io::directory::open(at) else (why) { return why; }; while listing.next() is some(entry) { val name := path::parse(entry.name) else (_) { return io_error::invalid; }; names.append(at.join(&name)); } for &each in names { var removed := remove_tree(each); return removed if removed is error; } } return io::remove(at); }