Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-11-14 15:31:15 -06:00
commit ab8208d6c6
28 files changed
+6914

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
+1
View File
@@ -0,0 +1 @@
.blossom
+63
View File
@@ -0,0 +1,63 @@
# Changelog
Each version's changes, newest first. Versions follow [semantic
versioning](https://semver.org).
## Unreleased
- A blossomfile's `members` lists folders of the project, each holding a member's
blossomfile, which says `member:` of which project it is and holds `requires`, `targets`,
and `tests`, its paths its own folder's. Members are merged into the project: one name
for each target, `build`, `check`, and `test` covering them all, `-o` reaching them,
`exports` naming their libraries, and a project requiring it reading theirs. Run in a
member's folder, blossom finds the project above it and keeps to the member's targets
and tests. A library's files leave out another member's folder within it, and what its
member's tests and programs list. Mistakes in a member's blossomfile name its file, and
it changing builds the project again.
- `blossom test --suite TEXT` runs the suites, the project's `tests`, whose names hold the
text, as `--only` did, which is renamed, and `--test TEXT` runs only the tests whose
names hold it, of each suite run, giving each `--only TEXT` after its own `args`, as
`std::testing` reads it. A suite that ran none says so, and none running one ends with 2,
as a suite named by none does. Breaking: `--only` is gone.
- A program may be shown as a desktop's program: its `title`, its `icon`'s files, PNGs of
any size, an SVG, or an icon file, and `windowed: true`. Built for Windows, `sakura
build` is given them, with the project's `semv`, as `--title`, `--icon`, `--semv`, and
`--windowed`, so the executable holds its icon, title, and version, and opens no
console. Built for Linux, `install` and `package` put each PNG and SVG in the icon
theme, `share/icons/hicolor`, and write its desktop entry,
`share/applications/NAME.desktop`, running it where the prefix holds it. Each may be an
option's value, an empty title or icon being none, and an icon's text naming several
files with `,` between them, as `-o icon=a.png,b.png`. A program giving none of them is
built as before.
- What it reads of `core`'s containers and views, and of std's, it reads by
their properties, as `.span` rather than `.view()`, `.last` rather than
`.last()`, and `blank()` rather than `empty()`, as the compiler and std now
name them.
- The standard library is required as the package `sakura/std`, of which it
reads `std::io`, `std::process`, `std::time`, `std::args`, and `std::yaml`,
and `std::io::glob`, which was `malunal::glob`, so it requires nothing else. A
target's `deps` naming `std` alone still reads the standard library the
compiler finds.
- The config's `std` is given to `sakura` as `--lib std=DIR`, since `--std` is
gone, and what blossom runs is no longer given `SAKURA_STD`.
- `blossom libraries` prints the `--lib` of each library a project holds or reads, with its
folder absolute, for an editor to give its language server. It clones nothing, and names
each requirement the store is missing on a `--missing` line instead.
- `blossom pull` clones what a project requires, or the requirements named, without
building. With `--update`, it clones again what the store already holds.
- Where the config names no `sakura`, blossom runs `sakurac`, the compiler's name, beside
it or on `PATH`, where it ran `sakura` before.
- MD5 and SHA-256 add their words through `std::math`'s `wrapping_add`, so blossom
built or run with `--checks`, which stops where arithmetic overflows, doesn't stop
where they wrap on purpose. Its unit tests are run so.
- The tests of its commands give the projects they make the standard library blossom's
own project reads, as `blossom libraries` lists it, as their config's `std`, so they
pass where the `sakurac` they run finds no std of its own.
## 1.0.0 - 2026-10-24
- The first version: `build`, `check`, `run`, `test`, `clean`, `install`, and
`package`, from a project's `blossomfile`, with its requirements cloned once
into a store, and outputs built again only where what made them changed.
- Requirements are cloned into `~/.cache/blossom`, or `XDG_CACHE_HOME`, and
`LOCALAPPDATA` on Windows, beside the config's `~/.config/blossom`.
+18
View File
@@ -0,0 +1,18 @@
MIT License
Copyright (c) 2026 Malunal Studios, LLC.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
+344
View File
@@ -0,0 +1,344 @@
# blossom
blossom builds Sakura projects, as chinook builds C ones. A `blossomfile` in a project's
folder says who the project is, what it requires, and its targets and tests. blossom reads
it and those of what it requires, then runs `sakura` for each step: one command a program.
```sh
blossom build # check the project's libraries, then build its programs
blossom check # check each target, writing nothing
blossom run -- 3 4 # run the project's program on the machine, given `3 4`
blossom test --suite geometry # build, then run the suites whose names hold `geometry`
blossom test --test cubes # build, then run the tests whose names hold `cubes`
blossom clean --all # remove .blossom
blossom install --prefix ~/.local
blossom package -f tar,deb # write packages into .blossom/<key>/dist
blossom pull binary # clone a requirement, or with no name, all of them
blossom libraries # print the --lib of each library the project reads
```
## Building blossom
Until blossom has built itself once, the compiler builds it, given the standard library it
reads, checked out beside this repository:
```sh
sakurac build -O2 -o blossom --lib std=../std \
entry.sakura models/*.sakura management/*.sakura pipeline/*.sakura
```
After that, `blossom build` builds it from its blossomfile, and `blossom test` runs its
tests: those of its parts, and those of its commands, which run the blossom just built on
projects made in a folder of each test's own. The command tests run `git`, `sh`, and
`tar`, so they run on Linux.
## Commands
| Command | Does |
|---|---|
| `build [PROJECT]` | Checks the project's libraries, then builds each program into `.blossom/<key>/bin`, where it isn't up to date |
| `check [PROJECT]` | Checks each target, libraries and programs, writing nothing |
| `run [TARGET] [-- ARG...]` | Runs a program on the machine, `sakura run`: the one named, or the project's only one |
| `test [PROJECT] [--suite TEXT] [--test TEXT]` | Builds, then runs each suite, the project's `tests`, or those whose names hold the suite's text, showing what they write; of each, only the tests whose names hold the test's text |
| `clean [PROJECT] [--all]` | Removes the outputs of these option values, `.blossom/<key>`, or with `--all`, all of `.blossom` |
| `install [PROJECT] [--prefix DIR] [--destdir DIR]` | Builds, then installs into `~/.local` or the prefix, under the destination folder where given |
| `package [PROJECT] [-f FORMAT[,FORMAT]] [--prefix DIR]` | Installs into `.blossom/<key>/stage`, then writes `tar`, `zip`, `deb`, `arch`, or `rpm` packages into `dist` |
| `pull [REQUIREMENT...] [--project DIR] [--update]` | Clones what the project requires, or the requirements named, and what their libraries read, where the store is missing them; with `--update`, clones them again |
| `libraries [PROJECT]` | Prints the `--lib` of each library the project holds or reads, a line each, with its folder absolute, then `--missing` for each requirement the store is missing |
Each takes:
- `-o NAME=VALUE`, giving the project's option a value;
- `--target linux-x86_64|windows-x86_64`, building every target for that system;
- `-j N`, given to `sakura`;
- `-v`, printing each command run.
Each step says how it went, a line each, with what `sakura` and the tests write passed on
as they write it:
```
[1/3] Checked hello.geometry
[2/3] Built hello (.blossom/3f2a9c01d4e5b677/bin/hello)
3 passed, 0 failed, 0 skipped
[3/3] Tested hello.tests (3 passed)
Tested malunal/hello@1.0.0
```
A step that fails says `Failed NAME`, and a program reading a library that failed to check
says `Skipped NAME`. blossom ends with 0 where everything worked, 1 where a build, a test,
or a clone failed, and 2 where the command or a blossomfile is wrong, with the file and the
line. `run` ends with the program's own status.
**`pull`** clones what a project requires, as a build would, without building anything. A
requirement is named as its blossomfile writes it, with or without `@REF`, or by the last
part of its path:
- `binary` names `https://git.malunal.studio/sakura/binary@v1.0.0`;
- `shapes` names `../shapes`.
What a requirement's libraries read is pulled with it. It says where each requirement is,
whether it was there already, cloned, or with `--update` cloned again, which a branch that
moved wants. A tag doesn't move. A clone made again takes the old one's place only once
it's whole:
```
$ blossom pull
Cloning https://git.malunal.studio/sakura/binary@v1.0.0
[1/2] Present https://git.malunal.studio/sakura/std@v1.0.0 (/home/me/.cache/blossom/...)
[2/2] Cloned https://git.malunal.studio/sakura/binary@v1.0.0 (/home/me/.cache/blossom/...)
Pulled what malunal/hello@1.0.0 requires
```
**`libraries`** is for tools, as the Sakura extension for VS Code, which gives each library
to its language server. Each line is a `--lib` as `sakura` takes it:
- the project's own libraries come first;
- then those its targets and tests read through `deps`, each followed by what it reads in
turn.
It clones nothing. Each remote the store is missing gets a line `--missing REMOTE@REF`
after them, and the libraries it holds are left out until `pull` clones it. It needs no
`sakura`, since it runs none, and otherwise refuses what a build refuses:
```
$ blossom libraries
--lib hello::geometry=/home/me/hello/geometry
--lib std::io=/home/me/.cache/blossom/git.malunal.studio/sakura/std@v1.0.0/io
--missing https://git.malunal.studio/sakura/binary@v1.0.0
```
## The blossomfile
YAML, in the project's folder:
```yaml
name: hello # required; the identity is gpid/name@semv
gpid: malunal # required
semv: 1.0.0 # required; a version, as 1.2.0 or 1.2.0-alpha
options: # NAME: value, any scalar; ${NAME} anywhere after; -o NAME=VALUE
level: 2 # ${bin} is given too: this option set's .blossom/<key>/bin
debug: false
members: # folders of the project, each holding a member's blossomfile
- shapes
requires:
- https://git.malunal.studio/sakura/std@v1.0.0 # REMOTE@REF; `main` without a ref
- ../shapes # a folder, relative to this file
- remote: https://git.malunal.studio/sakura/binary # a block, where it's given options
branch: v1.0.0
options:
strict: true
targets:
- name: hello # a program
type: program
level: ${level} # -O: 0, 1, or 2; 2 unless given
petal: ${debug} # -g, writing hello.petal beside it
target: windows-x86_64 # --target; the system blossom runs on unless given
deps: [std.io, std.yaml, hello.geometry] # libraries it reads; `std` alone is what the compiler finds
srcs: [main.sakura, util/**/*.sakura] # files, folders (each .sakura in them), globs
opts: [--inline, "24"] # given to `sakura build` as written
title: Hello # how a desktop's program is shown: its name,
icon: [hello.png, hello.svg] # its icon's files, .png, .svg, or .ico,
windowed: true # and in windows of its own, not a console
- name: hello.geometry # a library: the module hello::geometry
type: library
root: ./hello.geometry # ./<name> unless given
deps: [std.math] # libraries its modules import
tests:
- name: hello.tests # the keys of targets, and these
type: program
runs: machine # machine, by `sakura run`, unless native: built, then run
checks: true # `--checks`; on unless given, on the machine
deps: [hello.geometry]
srcs: [tests/**/*.sakura] # tests/**/*.sakura unless given
args: [--only, geometry] # what the test is given
exports: # the libraries other projects may read
- hello.geometry
install: # beside the programs and the exported libraries
- !include ./share # to <prefix>/share
- !include ./docs:share/doc/hello # to <prefix>/share/doc/hello
package:
lic: MIT
desc: Says hello.
auth: Me <me@example.com>
url: https://example.com/hello
```
- **Every key is checked:** one blossom doesn't know, or one written twice in a mapping,
which YAML would keep only one of, is refused by its line.
- **A library's name is its module's,** with `.` for `::`. Its folder is given to
`sakura` with `--lib`, as `--lib hello::geometry=hello.geometry`, and the compiler reads
only the modules a program imports. Two projects giving a library one name is refused,
as is a program reading a library another project doesn't export.
- **A program shown as a desktop's program** gives a `title`, an `icon`, or `windowed:
true`; one run in a terminal, as a tool, gives none of them and is built as ever.
- `title` is its name where it's shown, its own `name` unless given.
- `icon` names its icon's files, relative to the project: a file, a list of them, or
several in one text with `,` between them, as an option's value names them, since
`${NAME}` is replaced in a value's text once the YAML is read, so `-o
icon=[a.png,b.png]` is one text, never a list. Each is a PNG, of any size, an SVG, or
an icon file, `.ico`; an empty text names none.
- `windowed` is `true` or `false`, as written or as an option gives it.
- Built for Windows, the program holds them itself: blossom gives `sakura build` its
`--title`, the project's `semv` as `--semv`, each PNG and icon file as `--icon`, and
`--windowed`, so Explorer, its shortcuts, and its windows show its icon, Task
Manager and its properties its title and version, and no console opens for it. A PNG
wider or taller than 256 pixels, as one meant for Linux, is left out there.
- Built for Linux, `install` and `package` put them beside it, as [Installing and
packaging](#installing-and-packaging) says.
- Each may be an option, so what builds the program, as an editor exporting a game,
gives them with `-o`: `title: ${title}`, `icon: ${icon}`, `windowed: ${windowed}`.
An empty title or icon is none.
- **`install`'s steps** are each tagged with what they do. `!include SOURCE` copies a
file or folder to its own place under the prefix, and `!include SOURCE:DEST` to `DEST`.
A step without a tag, with one blossom doesn't know, or reaching outside the project or
the prefix, is refused.
## Members
A project too large for one blossomfile is split among members: folders within it, each
holding a blossomfile of its own that says what that part holds, what it needs, and what
tests it. The project's blossomfile lists them in `members`, and each says whose member it
is, so a blossomfile is clearly a member's from either side:
```yaml
# shapes/blossomfile
member: hello # required: the project whose `members` lists this folder
requires: # as a project's; a folder relative to this file
- ../../extra
targets:
- name: hello.shapes # paths are the member's: this library's root is shapes/
type: library
root: .
deps: [extra.numbers]
tests:
- name: hello.shapes.tests # srcs: tests/**/*.sakura, within shapes/
type: program
deps: [hello.shapes]
```
- **A member's blossomfile** takes `member`, `requires`, `targets`, and `tests`, and nothing
else: the project's name, version, options, exports, installing, and packaging are the
project's. A member's own `${NAME}` are the project's options, and `-o` reaches them.
- **Members are merged into the project,** as though its own blossomfile wrote them: one
name for each target and test across them all, `build`, `check`, and `test` covering
every member, `--suite` and `--test` choosing among them, `exports` naming their
libraries, and a project requiring this one reading every member's. Their paths are
their own folders', but their programs and tests run in the project's folder, as every
target's do, and their outputs are the project's, in its `.blossom`.
- **Run in a member's folder,** blossom finds the project above it whose `members` lists
it, and `build`, `check`, `run`, and `test` keep to that member's targets and tests;
`clean`, `install`, `package`, `pull`, and `libraries` take the whole project.
- **A library's files** are those within its root, but those within another member's
folder, and those its member's tests and programs list in their `srcs`, which are
theirs, so a member's tests sit beside its library in its folder.
- **A member's blossomfile changing** builds its project again, as the project's does.
## Requirements
- **A remote** is what `git` clones, as `https://host/path`, `git@host:path`, or
`file:///path`, and is cloned once, `git clone -b REF --depth 1`, into the store:
`~/.cache/blossom/<host>/<path>@<ref>`, or `$XDG_CACHE_HOME/blossom/...`, and
`%LOCALAPPDATA%\blossom\...` on Windows. A clone stopped halfway is never taken for
one, and where git fails, what it says is shown. The store can be removed at any time:
what's missing is cloned again. `pull` clones without building, and `pull --update`
clones again what the store holds.
- **A folder** is read where it is, relative to the blossomfile naming it.
- **One project, two sets of option values,** is refused, since each set builds outputs of
its own.
- **What a requirement requires** is read 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.
## Outputs and building again
Each project's outputs go to `.blossom/<key>`, the key being the hash of its identity, its
option values, and `--target`, so each set builds apart. A program is built again only
where:
- its executable is missing;
- the command building it changed, which is kept beside it in `<name>.command`, with the
`sakura` that ran it and when that was written;
- a file `sakura` read building it, as `--deps` lists them in `<name>.deps`, or the
blossomfile, is newer than it.
A library's check is kept the same way, in `.blossom/<key>/check`.
## Tests
A suite, each of the project's `tests`, runs on the machine, `sakura run --checks ... --
ARGS`, unless it says `runs: native`, where it's built, then run. It passes where it ends
with 0. Each runs in the project's folder, with `SAKURA` naming the `sakura` blossom runs,
so a test can run the compiler as blossom does.
- **`--suite TEXT`** runs only the suites whose names hold the text; none holding it is a
mistake in the command, ending with 2.
- **`--test TEXT`** gives each suite run `--only TEXT` after its own `args`, so a suite of
`std::testing`'s runs only the tests whose names hold the text, as `std::testing` reads
it; a later `--only` takes the place of one its `args` gave. A suite that says it ran
none is said as `Tested NAME (none named with `TEXT`)`, and none of them running one is
a mistake in the command, ending with 2, as a suite named by none is. A suite of its
own runner is given the same, and reads it or not.
## Installing and packaging
`install` builds, then copies each program to `<prefix>/bin`, with its `.petal`, each
exported library to `<prefix>/share/sakura/<name>`, as source another project's `--lib`
reads, then does each step of `install`.
A program built for Linux and shown as a desktop's program, by its `title`, `icon`, or
`windowed`, is installed as Linux's desktops find one, by the freedesktop.org
specifications, its file's name its own:
- each PNG of its `icon` goes into the icon theme every desktop reads,
`<prefix>/share/icons/hicolor/<W>x<H>/apps/<name>.png`, by the size its header says, and
an SVG into `.../hicolor/scalable/apps/<name>.svg`; an icon file is Windows' alone;
- its desktop entry, `<prefix>/share/applications/<name>.desktop`, names it by its title,
runs `<prefix>/bin/<name>`, the prefix and not `--destdir`, quoted where it must be, and
shows its icon, in a terminal unless it's `windowed`:
```ini
[Desktop Entry]
Type=Application
Name=Hello
Exec=/usr/bin/hello
Icon=hello
Terminal=false
StartupWMClass=hello
```
A window naming itself by the program's name, as its `app_id` on Wayland or its
`WM_CLASS` on X11, is matched with the entry, so a desktop's dock and task switcher show
its icon. A program built for Windows holds its icon, title, and version itself, so
nothing's put beside it.
`package` installs into `.blossom/<key>/stage`, then writes each package into `dist`,
dating every entry `SOURCE_DATE_EPOCH`, where it's set, so the same stage writes the same
bytes:
- `tar`, compressed by `gzip`, and `zip`, its files stored, each under a folder of the
project's name, version, and target. `tar` unless asked, or `zip` for Windows;
- `deb` and `arch`, under `--prefix`, `/usr` unless given, compressed by `gzip`, `xz`, and
`zstd`, with the digests each lists;
- `rpm`, built by `rpmbuild` from a spec blossom writes.
A desktop entry in a package runs its program where the package installs it,
`--prefix`'s `bin`, `/usr/bin` unless given, whichever package it's in.
## The config
`config` in `~/.config/blossom`, or `$XDG_CONFIG_HOME/blossom`, and `%APPDATA%\blossom`
on Windows, is optional:
```yaml
sakura: /opt/sakura/bin/sakurac # the sakura to run
std: /opt/sakura/std # the standard library it's given, as --lib std=DIR
```
Without `sakura`, blossom runs the `sakurac` beside it, or else the first on `PATH`.
Without `std`, `sakura` finds its own.
+53
View File
@@ -0,0 +1,53 @@
name: blossom
gpid: malunal
semv: 1.0.0
options:
level: 2
debug: false
# A requirement given no options is written on a line of its own: a block names
# one requirement, and is written where it gives options.
requires:
- https://git.malunal.studio/sakura/std@v1.0.0
targets:
- name: blossom
type: program
level: ${level}
petal: ${debug}
deps:
- std.io # With `std::io::glob`, which expands `srcs`
- std.process
- std.time
- std.args
- std.yaml
- std.math # Whose `wrapping_add` the digests add with
srcs:
- management/**/*.sakura
- models/**/*.sakura
- pipeline/**/*.sakura
- entry.sakura
tests:
- name: blossom.units
type: program
deps: [std.args, std.yaml, std.io, std.process, std.time, std.math, std.testing]
srcs:
- management/**/*.sakura
- models/**/*.sakura
- pipeline/**/*.sakura
- tests/units/**/*.sakura
- name: blossom.commands
type: program
deps: [std.io, std.process, std.testing]
srcs:
- tests/commands/**/*.sakura
args: ["${bin}/blossom"]
package:
lic: MIT
desc: Build tool for Sakura programming language.
auth: John Christman <sorakatadzuma@gmail.com>
url: https://git.malunal.studio/sakura/blossom
+407
View File
@@ -0,0 +1,407 @@
#! @file entry.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains blossom's command line: `build`, `check`, `run`, `test`, `clean`,
#! `install`, and `package`, each reading the blossomfile of a project and those
#! of what it requires, then running the `sakura` it finds for each step;
#! `pull`, which clones what a project requires; and `libraries`, which says what
#! `--lib` each library the project reads is given, as an editor wants to know.
#!
#! It ends with 0 where everything worked, 1 where a build, a test, or a clone
#! failed, and 2 where the command or a blossomfile is wrong. `run` ends with
#! the status of the program it runs.
import std::args;
import std::io;
import system;
import blossom::models;
import blossom::management;
import blossom::pipeline;
#! What every command takes.
@group
struct common_args {
@option{ name = "option", short = 'o', value = "NAME=VALUE", help = "Gives the project's option a value; given again for each." }
var options: vector<strview>;
@option{ value = "TARGET", help = "Builds every target for `linux-x86_64` or `windows-x86_64`, whatever its own `target` says." }
var target: strview;
@option{ short = 'j', value = "N", help = "How many threads `sakura` compiles each program on." }
var threads: maybe<u32>;
@option{ short = 'v', help = "Prints each command run." }
var verbose: bool;
}
@args::command
struct build_args {
@group
var common: common_args;
@argument{ value = "PROJECT", help = "The folder of the project's blossomfile, `.` unless given." }
var project: maybe<strview>;
}
@args::command
struct check_args {
@group
var common: common_args;
@argument{ value = "PROJECT", help = "The folder of the project's blossomfile, `.` unless given." }
var project: maybe<strview>;
}
@args::command
struct run_args {
@group
var common: common_args;
@argument{ value = "TARGET", help = "The program to run, unless the project has only one." }
var name: maybe<strview>;
@argument{ value = "ARGUMENT", rest = true, help = "What the program is given." }
var arguments: vector<strview>;
}
@args::command
struct test_args {
@group
var common: common_args;
@option{ value = "NAME", help = "Runs only the suites, the project's `tests`, whose names hold the text." }
var suite: strview;
@option{ name = "test", value = "NAME", help = "Runs only the tests whose names hold the text, of each suite run, giving each suite `--only NAME`, as `std::testing` reads it." }
var named: strview;
@argument{ value = "PROJECT", help = "The folder of the project's blossomfile, `.` unless given." }
var project: maybe<strview>;
}
@args::command
struct clean_args {
@group
var common: common_args;
@option{ help = "Removes the outputs of every set of option values, the whole `.blossom` folder." }
var all: bool;
@argument{ value = "PROJECT", help = "The folder of the project's blossomfile, `.` unless given." }
var project: maybe<strview>;
}
@args::command
struct install_args {
@group
var common: common_args;
@option{ value = "DIR", help = "Where it's installed: `~/.local` unless given." }
var prefix: strview;
@option{ value = "DIR", help = "Puts what's installed under the folder, as DIR/PREFIX, for packaging." }
var destdir: strview;
@argument{ value = "PROJECT", help = "The folder of the project's blossomfile, `.` unless given." }
var project: maybe<strview>;
}
@args::command
struct pull_args {
@group
var common: common_args;
@option{ value = "DIR", help = "The folder of the project's blossomfile, `.` unless given." }
var project: strview;
@option{ help = "Clones again what the store already holds, as a branch that moved wants." }
var update: bool;
@argument{ value = "REQUIREMENT", help = "What to pull: a remote or folder as the blossomfile writes it, or the last part of its path, as `binary`; everything the project requires unless given." }
var names: vector<strview>;
}
@args::command
struct libraries_args {
@group
var common: common_args;
@argument{ value = "PROJECT", help = "The folder of the project's blossomfile, `.` unless given." }
var project: maybe<strview>;
}
@args::command
struct package_args {
@group
var common: common_args;
@option{ name = "format", short = 'f', value = "FORMAT[,FORMAT]", help = "The packages written: `tar`, `zip`, `deb`, `arch`, and `rpm`; `tar` unless given, or `zip` for Windows." }
var formats: vector<strview>;
@option{ value = "DIR", help = "Where a system's package installs: `/usr` unless given." }
var prefix: strview;
@argument{ value = "PROJECT", help = "The folder of the project's blossomfile, `.` unless given." }
var project: maybe<strview>;
}
@args::command{ name = "blossom", help = "Builds Sakura projects, as their blossomfiles say.", version = "blossom 1.0.0" }
union commands {
@args::command{ help = "Checks the project's libraries, then builds its programs into `.blossom`." }
var build: build_args;
@args::command{ help = "Checks each target of the project, writing nothing." }
var check: check_args;
@args::command{ help = "Runs a program of the project on the machine." }
var run: run_args;
@args::command{ help = "Builds the project, then runs its tests, showing what they write." }
var test: test_args;
@args::command{ help = "Removes the outputs of these option values, or with `--all`, of every set." }
var clean: clean_args;
@args::command{ help = "Builds the project, then installs its programs, exported libraries, and `install` steps." }
var install: install_args;
@args::command{ help = "Installs the project into its stage, then writes packages of it." }
var package: package_args;
@args::command{ help = "Clones what the project requires, or the requirements named, where the store is missing them." }
var pull: pull_args;
@args::command{ help = "Prints the `--lib` of each library the project holds or reads, its folder absolute, and `--missing` for each requirement the store is missing." }
var libraries: libraries_args;
}
def main(args: span<strview>): void {
val chosen := args::parse_or_exit::<commands>(args);
match chosen {
build(&b) => {
var session := opened(&b.common, b.project);
session.build(false, "");
exit(finished(&session, "Built"));
}
check(&c) => {
var session := opened(&c.common, c.project);
session.check();
exit(finished(&session, "Checked"));
}
run(&r) => {
var session := opened(&r.common, nothing {});
var name := strview::blank();
if r.name is some(named) {
name = named;
}
exit(session.run_program(name, r.arguments.span));
}
test(&t) => {
var session := opened(&t.common, t.project);
session.build(true, t.suite, t.named);
exit(finished(&session, "Tested"));
}
clean(&c) => exit(cleaned(&c));
install(&i) => {
var session := opened(&i.common, i.project);
exit(session.install_command(i.prefix, i.destdir));
}
package(&p) => {
var session := opened(&p.common, p.project);
exit(session.package_command(p.formats.span, p.prefix));
}
pull(&p) => exit(pulled(&p));
libraries(&l) => exit(listed(&l));
}
}
# Reads the project a command is given, and everything it requires, and finds
# the `sakura` to run, stopping with what's wrong where any of that fails.
def opened(common: &common_args, project: maybe<strview>): pipeline::session {
var overrides := overrides_of(common);
if common.target.length != 0 && !models::is_platform(common.target) {
pipeline::fatal(2, $"`--target {common.target}` is no target: write `linux-x86_64` or `windows-x86_64`.".span);
}
var config := management::read_config();
if config is error(&problem) {
pipeline::fatal(2, problem.describe().span);
}
var given := config.unwrap();
var sakura := management::find_sakura(&given) else {
pipeline::fatal(2, "No `sakurac` is found: name a `sakura` as `sakura:` in blossom's config, or put `sakurac` beside blossom or on `PATH`.");
return pipeline::session {};
};
var std := string::new(nothing {});
if given.std.length != 0 {
val named := path::parse(given.std.span) else (_) {
pipeline::fatal(2, $"The config's `std`, `{given.std.span}`, is no path.".span);
return pipeline::session {};
};
val at := io::absolute(&named) else (_) { return pipeline::session {}; };
std = string::from(at.span, nothing {});
}
var folder_text: strview = ".";
if project is some(named) {
folder_text = named;
}
val folder := path::parse(folder_text) else (_) {
pipeline::fatal(2, "The project's folder is no path.");
return pipeline::session {};
};
var space := management::open_workspace(&folder, overrides.span, common.target, common.verbose);
if space is error(&why) {
pipeline::fatal(why.status, why.message.span);
}
var made := pipeline::session { sakura = move(sakura), std = move(std) };
if common.threads is some(count) {
made.threads = $"{count}";
}
if space is value(&mut opened) {
made.space = move(opened);
}
return made;
}
# The options `-o` gives, as `NAME=VALUE` each.
def overrides_of(common: &common_args): vector<models::setting> {
var made := vector::<models::setting>::new();
for &each in common.options {
val equals := each.find("=") else {
pipeline::fatal(2, $"`-o {each}` names no value: write `-o NAME=VALUE`.".span);
return made;
};
if equals == 0 {
pipeline::fatal(2, $"`-o {each}` names no option: write `-o NAME=VALUE`.".span);
}
made.append(models::setting {
name = string::from(each.substr(0, equals), nothing {}),
value = string::from(each.substr(equals + 1, each.length - equals - 1), nothing {})
});
}
return made;
}
# The status a command ends with, after its last line, as `Built
# malunal/hello@1.0.0`.
def finished(session: &pipeline::session, verb: strview): i32 {
return 1 if session.failed;
io::println($"{verb} {session.space.projects[0].identity.span}".span);
return 0;
}
# Removes the outputs of these option values, or with `--all`, the whole
# `.blossom` folder, reading only the project's own blossomfile and its
# members'.
def cleaned(given: &clean_args): i32 {
var overrides := overrides_of(&given.common);
var folder_text: strview = ".";
if given.project is some(named) {
folder_text = named;
}
val named := path::parse(folder_text) else (_) {
pipeline::fatal(2, "The project's folder is no path.");
return 2;
};
# A member's folder cleans its project's outputs, which are its own.
val place := management::project_of(&named);
if place is error(&why) {
pipeline::fatal(why.status, why.message.span);
}
if place is not value(&found) {
return 2;
}
val folder := path::copy_of(&found.folder);
val file := folder.join("blossomfile");
val text := io::read_file(&file) else (why) {
pipeline::fatal(2, $"`{folder.span}` holds no blossomfile to read: {why}.".span);
return 2;
};
var read := models::read_project(text.span, &file, overrides.span, given.common.target);
if read is error(&problem) {
pipeline::fatal(2, problem.describe().span);
}
if read is not value(&project) {
return 2;
}
var removed := project.output;
if given.all {
removed = folder.join(".blossom");
}
if !io::exists(&removed) {
io::println($"Nothing to clean for {project.identity.span}".span);
return 0;
}
if management::remove_tree(&removed) is error(why) {
pipeline::fatal(1, $"`{removed.span}` can't be removed: {why}.".span);
}
io::println($"Cleaned {project.identity.span} ({removed.span})".span);
return 0;
}
# Clones what the project requires, or the requirements named, and what their
# libraries read in turn, where the store is missing them, or with `--update`
# where it holds them, then says where each is. No `sakura` is needed, since
# none is run.
def pulled(given: &pull_args): i32 {
var overrides := overrides_of(&given.common);
checked_target(&given.common);
var folder_text: strview = ".";
if given.project.length != 0 {
folder_text = given.project;
}
val folder := project_folder(folder_text);
var space := management::open_workspace_with(&folder, overrides.span, given.common.target, given.common.verbose, false, given.update, given.names.span);
if space is error(&why) {
pipeline::fatal(why.status, why.message.span);
}
if space is not value(&opened) {
return 2;
}
val identity := opened.root().identity;
val total := opened.found.length;
if total == 0 {
io::println($"Nothing to pull for {identity.span}".span);
return 0;
}
for k in 0..total {
val each := &opened.found[k];
if each.local {
io::println($"[{k + 1}/{total}] Found {each.remote.span} ({each.folder.span})".span);
continue;
}
val verb := each.updated ? "Updated" : each.cloned ? "Cloned" : "Present";
io::println($"[{k + 1}/{total}] {verb} {each.remote.span}@{each.branch.span} ({each.folder.span})".span);
}
io::println($"Pulled what {identity.span} requires".span);
return 0;
}
# Prints the `--lib` of each library the project holds or reads, a line each,
# its folder absolute: its own, then those its targets and tests read, and what
# those read in turn. Nothing is cloned: each remote the store is missing is
# printed as `--missing REMOTE@BRANCH` after them, for `pull` to clone, and the
# libraries it would give are left out. No `sakura` is needed, since none is
# run.
def listed(given: &libraries_args): i32 {
var overrides := overrides_of(&given.common);
checked_target(&given.common);
var folder_text: strview = ".";
if given.project is some(named) {
folder_text = named;
}
val folder := project_folder(folder_text);
var space := management::open_workspace_with(&folder, overrides.span, given.common.target, given.common.verbose, true, false, span::<strview>::blank());
if space is error(&why) {
pipeline::fatal(why.status, why.message.span);
}
if space is not value(&opened) {
return 2;
}
var read := vector::<u64>::new();
var reached := opened.read_by(0, &mut read);
if reached is error(&why) {
pipeline::fatal(why.status, why.message.span);
}
for index in read {
io::println($"--lib {opened.absolute_lib_option(index).span}".span);
}
for &each in opened.missing {
io::println($"--missing {each.span}".span);
}
if opened.missing.length != 0 {
val said := opened.missing.length == 1
? string::from("blossom: 1 requirement isn't in the store, so what it holds is left out: `blossom pull` clones it.\n", nothing {})
: $"blossom: {opened.missing.length} requirements aren't in the store, so what they hold is left out: `blossom pull` clones them.\n";
system::fd::stderr.put(said.span);
}
return 0;
}
# Stops where `--target` names no target.
def checked_target(common: &common_args): void {
if common.target.length != 0 && !models::is_platform(common.target) {
pipeline::fatal(2, $"`--target {common.target}` is no target: write `linux-x86_64` or `windows-x86_64`.".span);
}
}
# The project's folder, stopping where the text is no path.
def project_folder(text: strview): path {
val folder := path::parse(text) else (_) {
pipeline::fatal(2, "The project's folder is no path.");
return path::new();
};
return folder;
}
+198
View File
@@ -0,0 +1,198 @@
#! @file config.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains where blossom keeps what it fetches and what it's told, and how it
#! finds the `sakura` it runs: the one the config names, else the `sakurac`
#! beside blossom, else the first `sakurac` on `PATH`.
import std::io;
import std::process;
import std::yaml;
import system;
import blossom::models;
module blossom::management;
#! What blossom's config says, from `config` in its folder, where there's one.
pub struct config {
pub var sakura: string; #! The `sakura` to run, or empty to look for one.
pub var std: string; #! The standard library `sakura` is given, or empty for the one it finds.
}
#! The folder blossom keeps its config in: `blossom` in `XDG_CONFIG_HOME`, else
#! in `~/.config`, and on Windows in `APPDATA`.
#! @returns The folder, or `nothing` where the environment names no home.
pub def config_folder(): maybe<path> {
return user_folder("APPDATA", "XDG_CONFIG_HOME", ".config");
}
#! The folder blossom keeps its store of requirements in, which it can always
#! clone again: `blossom` in `XDG_CACHE_HOME`, else in `~/.cache`, and on
#! Windows in `LOCALAPPDATA`.
#! @returns The folder, or `nothing` where the environment names no home.
pub def cache_folder(): maybe<path> {
return user_folder("LOCALAPPDATA", "XDG_CACHE_HOME", ".cache");
}
# `blossom` in the folder a variable names: on Windows the first, elsewhere the
# second, else the home's folder of the third name.
def user_folder(on_windows: strview, elsewhere: strview, in_home: strview): maybe<path> {
when os == windows {
if process::variable(on_windows) is some(data) {
if data.length != 0 {
var at := path::parse(data) else (_) { return nothing {}; };
return at.join("blossom");
}
}
return nothing {};
}
if process::variable(elsewhere) is some(named) {
if named.length != 0 {
var at := path::parse(named) else (_) { return nothing {}; };
return at.join("blossom");
}
}
val home := process::variable("HOME") else { return nothing {}; };
var at := path::parse(home) else (_) { return nothing {}; };
return at.join(in_home).join("blossom");
}
#! Reads blossom's config: `sakura` and `std`, each a path, both optional.
#! @returns The config, which says nothing where there's no file, or why the
#! file can't be read.
pub def read_config(): result<config, models::problem> {
var made := config {};
val folder := config_folder() else { return made; };
val file := folder.join("config");
return made if !io::exists(&file);
val text := io::read_file(&file) else (why) {
return models::problem { file = string::from(file.span, nothing {}), message = $"It can't be read: {why}." };
};
val doc := yaml::parse(text.span) else (e) {
return models::problem { file = string::from(file.span, nothing {}), line = e.line, message = string::from(yaml::describe(e.kind), nothing {}) };
};
val root := doc.root;
return made if root.is_null;
if root.kind != yaml::kind::mapping {
return models::problem { file = string::from(file.span, nothing {}), line = 1, message = string::from("The config is a mapping of `sakura` and `std`.", nothing {}) };
}
for each in root.members() {
val text := each.value.as_scalar() else (_) {
return models::problem { file = string::from(file.span, nothing {}), line = each.key.place.line, message = $"`{each.name}` is a path." };
};
if each.name == "sakura" {
made.sakura = string::from(text, nothing {});
} else if each.name == "std" {
made.std = string::from(text, nothing {});
} else {
return models::problem { file = string::from(file.span, nothing {}), line = each.key.place.line, message = $"`{each.name}` is no key of the config: it takes `sakura` and `std`." };
}
}
return made;
}
#! Finds the `sakura` blossom runs: the one the config names, else `sakurac`
#! beside blossom's executable, else the first `sakurac` on `PATH`.
#! @param given The config.
#! @returns Its path, absolute, or `nothing` where there's none.
pub def find_sakura(given: &config): maybe<string> {
if given.sakura.length != 0 {
val named := path::parse(given.sakura.span) else (_) { return nothing {}; };
val at := io::absolute(&named) else (_) { return nothing {}; };
return io::exists(&at) ? string::from(at.span, nothing {}) : nothing {};
}
val own := executable_path();
if own.length != 0 {
if path::parse(own.span) is value(&mine) {
if mine.parent() is some(&beside) {
val next := beside.join(program_file("sakurac").span);
if is_file(&next) {
return string::from(next.span, nothing {});
}
}
}
}
val searched := process::variable("PATH") else { return nothing {}; };
for each in searched.split(path_separator) {
continue if each.length == 0;
val folder := path::parse(each) else (_) { continue; };
val next := folder.join(program_file("sakurac").span);
if is_file(&next) {
val at := io::absolute(&next) else (_) { continue; };
return string::from(at.span, nothing {});
}
}
return nothing {};
}
#! A program's file name on the system blossom runs on: as it is, or with
#! `.exe` on Windows.
#! @param name The program's name.
#! @returns The file's name.
pub def program_file(name: strview): string {
when os == windows {
return $"{name}.exe";
}
return string::from(name, nothing {});
}
#! Whether a regular file is at a path, following links.
#! @param at The path.
#! @returns Whether one is.
pub def is_file(at: &path): bool {
return match io::info(at) {
value(&found) => found.kind == file_kind::regular,
error(_) => false,
};
}
when os == windows {
# What separates the folders of `PATH`.
val path_separator: u8 = ';';
} else {
# What separates the folders of `PATH`.
val path_separator: u8 = ':';
}
when os == linux {
# The call reading where a link leads, as Linux numbers it on x86-64.
val call_readlink: i64 = 89;
#! The path of blossom's own executable.
#! @returns The path, or empty text where the system doesn't say.
pub def executable_path(): string {
val link: strview = "/proc/self/exe";
var name: u8[16];
for i in 0..link.length {
name[i] = link[i];
}
name[link.length] = 0;
var text: u8[4096];
val from := (&mut name) as *mut u8;
val into := (&mut text) as *mut u8;
val length := system::linux::syscall(call_readlink, from as u64, into as u64, 4095, 0, 0, 0);
return string::new(nothing {}) if length <= 0;
return string::from(span::<u8>::over(into as *u8, length as u64), nothing {});
}
} else when os == windows {
# The code page of UTF-8, as Windows numbers it.
val utf8_page: u32 = 65001;
#! The path of blossom's own executable, in UTF-8.
#! @returns The path, or empty text where the system doesn't say.
pub def executable_path(): string {
var wide: u16[4096];
var text: u8[16384];
val units := (&mut wide) as *mut u16;
val into := (&mut text) as *mut u8;
val count := system::windows::GetModuleFileNameW(0, units, 4096);
return string::new(nothing {}) if count == 0 || count >= 4096;
val length := system::windows::WideCharToMultiByte(utf8_page, 0, units as *u16, count as i32, into, 16384, null, null);
return string::new(nothing {}) if length <= 0;
return string::from(span::<u8>::over(into as *u8, length as u64), nothing {});
}
}
+148
View File
@@ -0,0 +1,148 @@
#! @file sources.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains how a target's `srcs` become the files `sakura` is given: a file as
#! it is, a folder as each `.sakura` file within it, and a glob as what it
#! matches, each relative to the project, in the order written, each once.
import std::io;
import system;
import std::io::glob;
import blossom::models;
module blossom::management;
#! The files a program target is built from.
#! @param holder The project.
#! @param each The target.
#! @returns The files, relative to the project's folder, or why one of its
#! `srcs` names none.
pub def sources_of(holder: &models::project, each: &models::target): result<vector<string>, failure> {
var made := vector::<string>::new();
for &written in each.srcs {
val pattern := glob::pattern::parse(written.span) else (e) {
return failure { status = 2, message = $"{each.file.span}:{each.line}: `{written.span}` in `{each.name.span}`'s `srcs`: {e.describe().span}" };
};
var found := vector::<path>::new();
if pattern.is_literal {
val named := path::parse(written.span) else (_) {
return failure { status = 2, message = $"{each.file.span}:{each.line}: `{written.span}` is no path." };
};
found.append(holder.folder.join(&named));
} else {
var matched := pattern.find(&holder.folder);
if matched is error(&why) {
return failure { status = 1, message = why.describe() };
}
if matched is value(&mut paths) {
found = move(paths);
}
}
var any := false;
for &at in found {
if at.is_directory {
var within := sakura_files(at);
if within is error(&why) {
return failure { status = 1, message = why.describe() };
}
if within is value(&files) {
for &file in files {
add_relative(&mut made, &holder.folder, file);
any = true;
}
}
} else if io::exists(at) {
add_relative(&mut made, &holder.folder, at);
any = true;
}
}
if !any {
return failure { status = 2, message = $"{each.file.span}:{each.line}: `{written.span}`, in `{each.name.span}`'s `srcs`, names no file." };
}
}
return made;
}
#! The files of a library, which `check` is given: every `.sakura` file within
#! its root, but those of another member's folder within it, and those its
#! member's tests and programs list in their `srcs`, which are theirs, so a
#! member's tests sit beside its library in its folder.
#! @param holder The project.
#! @param each The library.
#! @returns The files, relative to the project's folder, or why its folder
#! can't be read.
pub def library_files(holder: &models::project, each: &models::target): result<vector<string>, failure> {
val root := path::parse(each.root.span) else (_) {
return failure { status = 2, message = $"{each.file.span}:{each.line}: `{each.root.span}` is no path." };
};
val folder := holder.folder.join(&root);
if !folder.is_directory {
return failure { status = 2, message = $"{each.file.span}:{each.line}: `{each.name.span}`'s folder, `{each.root.span}`, isn't there." };
}
var found := vector::<string>::new();
var within := sakura_files(&folder);
if within is error(&why) {
return failure { status = 1, message = why.describe() };
}
if within is value(&files) {
for &file in files {
add_relative(&mut found, &holder.folder, file);
}
}
# What the member's tests and programs list is theirs. One whose `srcs` name
# nothing says so as it's built, not here.
var theirs := vector::<string>::new();
for k in 0..holder.targets.length + holder.tests.length {
val other := &holder.at(k);
continue if other.kind != models::target_kind::program || other.member != each.member;
if sources_of(holder, other) is value(&listed) {
for &file in listed {
theirs.append(string::copy_of(file));
}
}
}
var made := vector::<string>::new();
for &mut file in found {
continue if holder.member_holding(file.span) != each.member.span;
var listed := false;
for &other in theirs {
listed = listed || same_file(other.span, file.span);
}
continue if listed;
made.append(move(file));
}
return made;
}
# Whether two paths relative to the project name one file, whichever of `/` and
# `\` is between their names.
def same_file(a: strview, b: strview): bool {
return false if a.length != b.length;
for k in 0..a.length {
val x := a[k] == '\\' ? '/' as u8 : a[k];
val y := b[k] == '\\' ? '/' as u8 : b[k];
return false if x != y;
}
return true;
}
# Every `.sakura` file within a folder, at any depth, in order.
def sakura_files(folder: &path): result<vector<path>, glob::search_error> {
val all := glob::pattern::parse("**/*.sakura") else (_) { return vector::<path>::new(); };
return all.find(folder);
}
# Adds a file, relative to the project's folder, unless it's there already.
def add_relative(into: &mut vector<string>, folder: &path, file: &path): void {
var text := string::from(file.span, nothing {});
if file.relative_to(folder) is some(&relative) {
text = string::from(relative.span, nothing {});
}
for &prior in into {
return if prior == text;
}
into.append(move(text));
}
+760
View File
@@ -0,0 +1,760 @@
#! @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::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<models::project>;
pub var libraries: vector<library>;
pub var platform: string; #! What `--target` says, or empty.
pub var verbose: bool; #! Whether each command run is printed.
pub var found: vector<requirement_found>; #! Each requirement come to, in the order it was.
pub var missing: vector<string>; #! Each remote the store is missing, as `REMOTE@BRANCH`, where nothing is cloned.
pub var member: string; #! The member of the project given the command was run in, whose targets and tests alone it builds, checks, runs, and tests, or empty for the whole project.
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<string>; #! 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<models::setting>,
platform: strview,
verbose: bool
): result<workspace, failure> {
return open_workspace_with(folder, overrides, platform, verbose, false, false, span::<strview>::blank());
}
#! 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<models::setting>,
platform: strview,
verbose: bool,
offline: bool,
update: bool,
wanted: span<strview>
): result<workspace, failure> {
var made := workspace {
projects = vector::<models::project>::new(),
libraries = vector::<library>::new(),
platform = string::from(platform, nothing {}),
verbose = verbose,
found = vector::<requirement_found>::new(),
missing = vector::<string>::new(),
member = string::new(nothing {}),
offline = offline,
update = update,
wanted = vector::<string>::new()
};
for each in wanted {
made.wanted.append(string::from(each, nothing {}));
}
# A member's folder is read as its project's, the command keeping to it.
var place := project_of(folder);
if place is error(&mut why) {
return move(why);
}
var found := place.unwrap();
made.member = move(found.member);
var loaded := made.load(&found.folder, overrides, strview::blank(), 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];
}
#! Whether a command takes a target of the project given: every one, unless it
#! was run in a member's folder, where only the member's own.
#! @param this The workspace.
#! @param each The target or test.
#! @returns Whether it does.
pub def workspace::takes(&this, each: &models::target): bool {
return this.member.length == 0 || each.member == this.member;
}
#! Where a command finds the project of a folder: the folder itself, or, where
#! its blossomfile is a member's, the project above it whose `members` lists it.
pub struct project_place {
pub var folder: path; #! The project's folder, absolute.
pub var member: string; #! The member's folder, relative to the project's, or empty where the folder is the project's own.
}
#! Finds the project of a folder: the folder's own, unless its blossomfile says
#! it's a member, as `member: hello`, where it's the nearest folder above whose
#! blossomfile lists it in `members`.
#! @param folder The folder a command was given, or run in.
#! @returns Where the project is, or why a member's is nowhere above it.
pub def project_of(folder: &path): result<project_place, failure> {
val absolute := io::absolute(folder) else (why) {
return failure { status = 2, message = $"`{folder.span}` can't be found: {why}." };
};
val file := absolute.join("blossomfile");
# A folder holding none is said to as the project's read.
val text := io::read_file(&file) else (_) {
return project_place { folder = path::copy_of(&absolute), member = string::new(nothing {}) };
};
val of := models::member_of(text.span) else {
return project_place { folder = path::copy_of(&absolute), member = string::new(nothing {}) };
};
var current := path::copy_of(&absolute);
while true {
val up := current.parent() else { break; };
val above := up.join("blossomfile");
if io::read_file(&above) is value(&upper) {
if absolute.relative_to(&up) is some(&relative) {
var written := string::new(nothing {});
for k in 0..relative.span.length {
written.push(relative.span[k] == '\\' ? '/' as u8 : relative.span[k]);
}
if models::lists_member(upper.span, written.span) {
return project_place { folder = path::copy_of(&up), member = move(written) };
}
}
}
current = path::copy_of(&up);
}
return failure { status = 2, message = $"`{file.span}` says it's a member of `{of.span}`, but no blossomfile above it lists its folder in `members`." };
}
# 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<models::setting>, by: strview, root: bool): result<u64, failure> {
val absolute := io::absolute(folder) else (why) {
return failure { status = 2, message = $"`{folder.span}` 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.span}`{whose.span} holds no blossomfile to read: {why}." };
};
var read := models::read_project(text.span, &file, overrides, this.platform.span);
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.span, made.options.span) {
return failure { status = 2, message = $"{made.identity.span} is required with two sets of option values: {described(prior.options.span).span}, and {described(made.options.span).span} 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.span, &each);
}
if !named {
return failure { status = 2, message = $"`{name.span}` is no requirement of {this.projects[index].identity.span}: {requirements_of(&this.projects[index]).span}." };
}
}
}
# 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;
val written := path::copy_of(&required.file);
var options := vector::<models::setting>::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.span) else (_) {
return failure { status = 2, message = $"{written.span}:{line}: `{remote.span}` 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.span, branch.span);
if stored is error(&mut why) {
return move(why);
}
val at := stored.unwrap();
if !io::exists(&at) {
this.note_missing(remote.span, branch.span);
continue;
}
}
var fetched := this.fetch(remote.span, branch.span);
if fetched is error(&mut why) {
return move(why);
}
found = fetched.unwrap();
}
var loaded := this.load(&found, options.span, requirer.span, 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<path, failure> {
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.span) 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<path, failure> {
for &each in this.found {
return path::copy_of(&each.folder) if !each.local && each.remote.span == remote && each.branch.span == 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.span}.partial".span) 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.span);
# 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.span]);
if this.verbose {
io::println($"git -c advice.detachedHead=false clone --quiet -b {branch} --depth 1 {remote} {partial.span}".span);
}
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.span}.old".span) 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.span}` 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.span}`: {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.span}`: {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.span, 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.span;
val last := last_part(remote);
return true if name == remote || name == last;
return false if required.local;
val full := $"{remote}@{required.branch.span}";
val short := $"{last}@{required.branch.span}";
return name == full.span || name == short.span;
}
# 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.span);
if !each.local {
made.push('@');
made.append(each.branch.span);
}
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<void, failure> {
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.span}` is a library of both {this.projects[prior.project].identity.span} and {holder.identity.span}." };
}
}
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<u64> {
for k in 0..this.libraries.length {
return k if this.libraries[k].name.span == 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<string>,
who: strview,
into: &mut vector<u64>,
lenient: bool = false
): result<void, failure> {
for &name in deps {
continue if name == "std";
val found := this.library_named(name.span) else {
continue if lenient;
return failure { status = 2, message = $"`{name.span}`, which `{who}` reads, is no library of {this.projects[project].identity.span} or of what it requires." };
};
val held := &this.libraries[found];
if held.project != project && !this.projects[held.project].exported(name.span) {
return failure { status = 2, message = $"`{name.span}`, which `{who}` reads, isn't exported by {this.projects[held.project].identity.span}." };
}
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.span, name.span, 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<u64>): result<void, failure> {
val holder := &this.projects[project];
var own := vector::<string>::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.span, holder.identity.span, into, lenient);
if reached is error(&mut why) {
return move(why);
}
for &each in holder.targets {
reached = this.reach(project, each.deps.span, each.name.span, into, lenient);
if reached is error(&mut why) {
return move(why);
}
}
for &each in holder.tests {
reached = this.reach(project, each.deps.span, each.name.span, 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.span) 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).span);
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.span);
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::blank();
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.span, strview::blank(), 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.span, 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.span.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<models::setting>, b: span<models::setting>): 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<models::setting>): string {
var made := string::new(nothing {});
for &each in options {
if made.length != 0 {
made.push(' ');
}
made.append($"{each.name.span}={each.value.span}".span);
}
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<void, io_error> {
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::<path>::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);
}
+186
View File
@@ -0,0 +1,186 @@
#! @file project.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what a blossomfile says of a project: who it is, its options, what
#! it requires, its targets and tests, what it exports, how it installs, and how
#! it is packaged.
import std::io;
module blossom::models;
#! An option of a project, and the value it has, as the text written.
pub struct setting {
pub var name: string;
pub var value: string;
}
#! What a target is.
pub enum target_kind: u8 {
program, #! A program, built into an executable.
library, #! A folder of modules, which programs read through `--lib`.
}
#! Where a test runs.
pub enum runner: u8 {
machine, #! On the machine, by `sakura run`.
native, #! Built into an executable, which is then run.
}
#! A target or a test of a project.
pub struct target {
pub var name: string;
pub var kind: target_kind;
pub var level: u32 = 2; #! `-O`, from 0 to 2.
pub var petal: bool; #! Whether it's built with `-g`.
pub var system: string; #! What it's built for, as `windows-x86_64`, or empty for the system blossom runs on.
pub var deps: vector<string>; #! The libraries it reads, by name, `std` among them or not.
pub var srcs: vector<string>; #! Its files, folders, and globs, relative to the project.
pub var opts: vector<string>; #! What's given to `sakura` as written.
pub var root: string; #! A library's folder, relative to the project.
pub var runs: runner; #! Where a test runs.
pub var checks: bool; #! Whether a test's memory is checked as it runs.
pub var args: vector<string>; #! What a test is given.
pub var title: string; #! What a program is called where it's shown, or empty for its name.
pub var icons: vector<string>; #! The PNG, SVG, and icon files a program is shown by, relative to the project.
pub var windowed: bool; #! Whether a program runs in windows of its own, with no console or terminal.
pub var member: string; #! The folder of the member it's written in, relative to the project, as its `members` writes it, or empty for the project's own blossomfile.
pub var file: path; #! The blossomfile it's written in: the project's, or a member's.
pub var line: u32; #! Where it's written.
}
#! Whether a program is shown as a desktop's program: it gives a `title`, an
#! `icon`, or `windowed: true`, as a tool run in a terminal gives none of them.
#! @param this The target.
#! @returns Whether it is.
pub val target::shown: bool {
get => this.title.length != 0 || this.icons.length != 0 || this.windowed;
}
#! A project another requires.
pub struct requirement {
pub var remote: string; #! A remote's address, or a folder relative to the blossomfile.
pub var branch: string; #! The branch or tag cloned, `main` unless written.
pub var local: bool; #! Whether it's a folder rather than a remote.
pub var options: vector<setting>; #! The values it's given for its options.
pub var file: path; #! The blossomfile it's written in: the project's, or a member's.
pub var line: u32; #! Where it's written.
}
#! A member of a project: a folder within it holding a blossomfile of its own,
#! which says it's the project's member, and whose targets, tests, and
#! requirements are the project's, as though its own blossomfile wrote them.
pub struct member {
pub var folder: string; #! Its folder, relative to the project, with `/` between names and none at its end, as `engine` or `editor/modeling`.
pub var file: path; #! Its blossomfile.
}
#! A step of installing, beside what's installed by default.
pub struct step {
pub var tag: string; #! What it does, as `!include`.
pub var source: string; #! What it takes, relative to the project.
pub var dest: string; #! Where it goes under the prefix, or empty for the source's own place.
pub var line: u32; #! Where it's written.
}
#! How a project is described in its packages.
pub struct package_info {
pub var lic: string; #! Its license, as `MIT`.
pub var desc: string; #! What it is, in a line.
pub var auth: string; #! Who made it, as `Name <mail>`.
pub var url: string; #! Where it lives.
}
#! A project, as its blossomfile says it.
pub struct project {
pub var name: string;
pub var gpid: string;
pub var semv: string;
pub var folder: path; #! The folder holding its blossomfile, absolute.
pub var file: path; #! Its blossomfile.
pub var members: vector<member>; #! The folders whose blossomfiles are its members', in the order `members` lists them.
pub var options: vector<setting>; #! Its options' values, in the order declared.
pub var requires: vector<requirement>;
pub var targets: vector<target>;
pub var tests: vector<target>;
pub var exports: vector<string>; #! The libraries other projects may read.
pub var install: vector<step>;
pub var package: package_info;
pub var key: string; #! Its output folder's name in `.blossom`.
}
#! Who the project is, as `malunal/hello@1.0.0`.
#! @param this The project.
#! @returns Its group, name, and version.
pub val project::identity: string {
get => $"{this.gpid}/{this.name}@{this.semv}";
}
#! The folder its outputs for these option values go to.
#! @param this The project.
#! @returns `.blossom/<key>` within its folder.
pub val project::output: path {
get => this.folder.join(".blossom").join(this.key.span);
}
#! Finds a target or test by its name.
#! @param this The project.
#! @param name The name.
#! @returns Where it is among the targets, then the tests after them, or
#! `nothing` where neither has it.
pub def project::find(&this, name: strview): maybe<u64> {
for k in 0..this.targets.length {
return k if this.targets[k].name.span == name;
}
for k in 0..this.tests.length {
return this.targets.length + k if this.tests[k].name.span == name;
}
return nothing {};
}
#! A target, or a test after the targets, by where `find` says it is.
#! @param this The project.
#! @param index Where it is.
#! @returns It.
pub def project::at(&this, index: u64): &target {
if index < this.targets.length {
return &this.targets[index];
}
return &this.tests[index - this.targets.length];
}
#! The member a file of the project belongs to: the one whose folder holds it
#! most nearly, as `editor/modeling` rather than `editor` where both are.
#! @param this The project.
#! @param file The file, relative to the project's folder, with `/` or `\`
#! between its names.
#! @returns The member's folder, or empty where no member holds it.
pub def project::member_holding(&this, file: strview): strview {
var best := strview::blank();
for &each in this.members {
val folder := each.folder.span;
continue if folder.length >= file.length || folder.length <= best.length;
continue if file[folder.length] != '/' && file[folder.length] != '\\';
var same := true;
for k in 0..folder.length {
val a := file[k] == '\\' ? '/' as u8 : file[k];
same = same && a == folder[k];
}
if same {
best = folder;
}
}
return best;
}
#! Whether the project lets others read a library.
#! @param this The project.
#! @param name The library's name.
#! @returns Whether `exports` names it.
pub def project::exported(&this, name: strview): bool {
for &each in this.exports {
return true if each.span == name;
}
return false;
}
+889
View File
@@ -0,0 +1,889 @@
#! @file reading.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains how a blossomfile is read into a project: from YAML's document,
#! whose values keep their lines and tags, with every key checked against those
#! a mapping takes, a key written twice refused, and each `${NAME}` replaced by
#! the option's value as the text is read.
import std::io;
import std::yaml;
module blossom::models;
#! The systems a target may be built for, as `--target` names them.
pub val platforms: strview[2] = ["linux-x86_64", "windows-x86_64"];
#! Why a blossomfile couldn't be read: where, and what's wrong.
pub struct problem {
pub var file: string; #! The blossomfile, as its path is written.
pub var line: u32; #! The line, counted from 1, or 0 where it's no line's.
pub var message: string; #! What's wrong, in a sentence.
}
#! Says what's wrong, after where.
#! @param this The problem.
#! @returns The sentence, as `blossomfile:4: ...`.
pub def problem::describe(&this): string {
if this.line == 0 {
return $"{this.file.span}: {this.message.span}";
}
return $"{this.file.span}:{this.line}: {this.message.span}";
}
#! Reads a blossomfile.
#! @param text Its text.
#! @param file Its path, absolute.
#! @param overrides Values for its options, as `-o` gives them, which must
#! each name one it declares.
#! @param platform What every target is built for, as `--target` says, or
#! empty, which goes into its output folder's name.
#! @returns The project, or the first problem the file has.
pub def read_project(
text: strview,
file: &path,
overrides: span<setting>,
platform: strview
): result<project, problem> {
var at := reading { file = file.span, at = path::copy_of(file), options = vector::<setting>::new() };
var folder := file.parent() else {
return problem { file = string::from(file.span, nothing {}), message = string::from("A blossomfile is in a folder.", nothing {}) };
};
var made := project { file = path::copy_of(file), folder = move(folder) };
at.read(text, &mut made, overrides, platform);
if at.failed {
return move(at.problem);
}
return move(made);
}
# What reading a blossomfile goes through: its file, as text and as a path, the
# options so far, which `${NAME}` is replaced by, and the first problem found.
struct reading {
var file: strview;
var at: path;
var options: vector<setting>;
var failed: bool;
var problem: problem;
}
# Notes the first problem, at a line of the file being read.
def reading::fail(&mut this, line: u32, message: string): void {
this.fail_in(this.file, line, move(message));
}
# Notes the first problem, at a line of a file: the project's, or a member's.
def reading::fail_in(&mut this, file: strview, line: u32, message: string): void {
return if this.failed;
this.failed = true;
this.problem = problem { file = string::from(file, nothing {}), line = line, message = move(message) };
}
# Reads the whole file into a project.
def reading::read(&mut this, text: strview, made: &mut project, overrides: span<setting>, platform: strview): void {
val doc := yaml::parse(text) else (e) {
this.fail(e.line, string::from(yaml::describe(e.kind), nothing {}));
return;
};
val root := doc.root;
if root.is_null {
this.fail(0, string::from("The blossomfile is empty: it needs `name`, `gpid`, and `semv`.", nothing {}));
return;
}
if root.kind == yaml::kind::mapping && root.get("member") is some(of) {
this.fail(of.place.line, string::from("This blossomfile is a member's, of the project whose blossomfile lists its folder in `members`: blossom reads it with that project, run there or here.", nothing {}));
return;
}
return if !this.keys(&root, ["name", "gpid", "semv", "options", "members", "requires", "targets", "tests", "exports", "install", "package"], "the blossomfile");
# Who it is comes first, then its options, which every text after may use.
made.name = this.needed(&root, "name");
made.gpid = this.needed(&root, "gpid");
made.semv = this.needed(&root, "semv");
return if this.failed;
if !is_version(made.semv.span) {
this.fail(root.get("semv").some.place.line, $"`{made.semv.span}` is not a version, as `1.2.0` or `1.2.0-alpha`.");
return;
}
if root.get("options") is some(options) {
return if !this.keys(&options, span::<strview>::blank(), "options");
for each in options.members() {
if each.name == "bin" {
this.fail(each.key.place.line, string::from("`bin` is blossom's: it names the folder of the programs built.", nothing {}));
return;
}
var value := this.text(&each.value, "An option's value");
for &given in overrides {
if given.name.span == each.name {
value = this.expanded(given.value.span, 0);
}
}
this.options.append(setting { name = string::from(each.name, nothing {}), value = move(value) });
}
}
for &given in overrides {
var declared := false;
for &each in this.options {
declared = declared || each.name == given.name;
}
if !declared {
this.fail(0, $"`{given.name.span}`, given a value, names no option of {made.identity.span}.");
return;
}
}
for &each in this.options {
made.options.append(setting { name = string::copy_of(&each.name), value = string::copy_of(&each.value) });
}
made.key = output_key(made.identity.span, made.options.span, platform);
val bin := made.output.join("bin");
this.options.append(setting { name = string::from("bin", nothing {}), value = string::from(bin.span, nothing {}) });
return if this.failed;
if root.get("requires") is some(requires) {
for each in this.list(&requires, "`requires`") {
made.requires.append(this.requirement(&each));
return if this.failed;
}
}
if root.get("targets") is some(targets) {
for each in this.list(&targets, "`targets`") {
made.targets.append(this.target(&each, false));
return if this.failed;
}
}
if root.get("tests") is some(tests) {
for each in this.list(&tests, "`tests`") {
made.tests.append(this.target(&each, true));
return if this.failed;
}
}
if root.get("members") is some(members) {
this.members(&members, made);
return if this.failed;
}
if root.get("exports") is some(exports) {
made.exports = this.texts(&exports, "`exports`");
}
if root.get("install") is some(install) {
for each in this.list(&install, "`install`") {
made.install.append(this.step(&each));
return if this.failed;
}
}
if root.get("package") is some(package) {
return if !this.keys(&package, ["lic", "desc", "auth", "url"], "`package`");
made.package = package_info {
lic = this.optional(&package, "lic"),
desc = this.optional(&package, "desc"),
auth = this.optional(&package, "auth"),
url = this.optional(&package, "url")
};
}
return if this.failed;
this.validate(made, &root);
}
# Reads the project's members: each folder `members` lists, within the project,
# holding a blossomfile that says it's the project's member, whose targets,
# tests, and requirements are the project's, their paths taken from the
# member's folder.
def reading::members(&mut this, list: &yaml::value, made: &mut project): void {
for each in this.list(list, "`members`") {
val written := this.text(&each, "A member");
return if this.failed;
val folder := member_folder(written.span);
if folder.length == 0 || !is_within(folder.span) {
this.fail(each.place.line, $"`{written.span}` is outside the project: a member is a folder within it, as `engine`.");
return;
}
for &prior in made.members {
if prior.folder == folder {
this.fail(each.place.line, $"`{folder.span}` is listed twice in `members`.");
return;
}
}
val named := path::parse(folder.span) else (_) {
this.fail(each.place.line, $"`{written.span}` is no folder.");
return;
};
val file := made.folder.join(&named).join("blossomfile");
val text := io::read_file(&file) else (why) {
this.fail(each.place.line, $"The member `{folder.span}` holds no blossomfile to read: {why}.");
return;
};
made.members.append(member { folder = string::copy_of(&folder), file = path::copy_of(&file) });
var inner := reading { file = file.span, at = path::copy_of(&file), options = vector::<setting>::new() };
for &option in this.options {
inner.options.append(setting { name = string::copy_of(&option.name), value = string::copy_of(&option.value) });
}
inner.member(text.span, made, folder.span);
if inner.failed {
this.failed = true;
this.problem = move(inner.problem);
return;
}
}
}
# Reads a member's blossomfile into its project: `member`, naming the project,
# then its requirements, its targets, and its tests, which take the project's
# options, each path they write taken from the member's folder.
def reading::member(&mut this, text: strview, made: &mut project, folder: strview): void {
val doc := yaml::parse(text) else (e) {
this.fail(e.line, string::from(yaml::describe(e.kind), nothing {}));
return;
};
val root := doc.root;
if root.is_null {
this.fail(0, $"A member's blossomfile is empty: it needs `member: {made.name.span}`, naming the project it's of.");
return;
}
return if !this.keys(&root, ["member", "requires", "targets", "tests"], "a member's blossomfile");
val of := this.needed(&root, "member");
return if this.failed;
if of != made.name {
this.fail(root.get("member").some.place.line, $"This blossomfile says it's a member of `{of.span}`, but `{made.name.span}` lists it in its `members`.");
return;
}
if root.get("requires") is some(requires) {
for each in this.list(&requires, "`requires`") {
var required := this.requirement(&each);
return if this.failed;
if required.local {
required.remote = placed(folder, required.remote.span);
}
made.requires.append(move(required));
}
}
for key in ["targets", "tests"] {
if root.get(key) is some(listed) {
for each in this.list(&listed, $"`{key}`".span) {
var read := this.target(&each, key == "tests");
return if this.failed;
this.place_target(&mut read, folder);
return if this.failed;
if key == "tests" {
made.tests.append(move(read));
} else {
made.targets.append(move(read));
}
}
}
}
}
# Takes a member's target's paths from the member's folder: a library's root,
# which stays within the member, its files, and its icons.
def reading::place_target(&mut this, read: &mut target, folder: strview): void {
read.member = string::from(folder, nothing {});
if read.kind == target_kind::library {
if !is_within(read.root.span) {
this.fail(read.line, $"`{read.root.span}` is outside the member: a library's root is a folder within its member's.");
return;
}
read.root = placed(folder, read.root.span);
}
for &mut each in read.srcs {
each = placed(folder, each.span);
}
for &mut each in read.icons {
each = placed(folder, each.span);
}
}
# A member's folder as `members` writes it, with `/` between its names, and
# neither `./` before it nor `/` after it.
def member_folder(text: strview): string {
var made := string::new(nothing {});
for k in 0..text.length {
made.push(text[k] == '\\' ? '/' as u8 : text[k]);
}
while made.span.starts_with("./") {
made = string::from(made.span.substr(2, made.length - 2), nothing {});
}
while made.length != 0 && made[made.length - 1] == '/' {
made = string::from(made.span.substr(0, made.length - 1), nothing {});
}
return made;
}
# A path a member writes, relative to its folder, as the project reads it,
# relative to its own: the member's folder before it, unless it's absolute.
def placed(folder: strview, text: strview): string {
if text.length != 0 && (text[0] == '/' || text[0] == '\\' || (text.length > 1 && text[1] == ':')) {
return string::from(text, nothing {});
}
var rest := text;
while rest.starts_with("./") || rest.starts_with(".\\") {
rest = rest.substr(2, rest.length - 2);
}
if rest.length == 0 || rest == "." {
return string::from(folder, nothing {});
}
return $"{folder}/{rest}";
}
#! The project a blossomfile says it's a member of, by its `member`, or none
#! where it says none, or isn't YAML to say.
#! @param text The blossomfile's text.
#! @returns The project's name.
pub def member_of(text: strview): maybe<string> {
val doc := yaml::parse(text) else (_) { return nothing {}; };
val root := doc.root;
return nothing {} if root.kind != yaml::kind::mapping;
val of := root.get("member") else { return nothing {}; };
val name := of.as_scalar() else (_) { return nothing {}; };
return string::from(name, nothing {});
}
#! Whether a blossomfile lists a folder among its `members`.
#! @param text The blossomfile's text.
#! @param folder The folder, relative to the blossomfile's, with `/` between
#! its names.
#! @returns Whether it does.
pub def lists_member(text: strview, folder: strview): bool {
val doc := yaml::parse(text) else (_) { return false; };
val root := doc.root;
return false if root.kind != yaml::kind::mapping;
val members := root.get("members") else { return false; };
return false if members.kind != yaml::kind::sequence;
for each in members.elements() {
val written := each.as_scalar() else (_) { continue; };
return true if member_folder(written).span == folder;
}
return false;
}
# Reads a requirement: its text alone, as `REMOTE@REF` or a folder, or the block
# of `remote`, `branch`, and `options`.
def reading::requirement(&mut this, value: &yaml::value): requirement {
val line := value.place.line;
if value.kind != yaml::kind::mapping {
val text := this.text(value, "A requirement");
var made := requirement { line = line, file = path::copy_of(&this.at) };
if is_folder_text(text.span) {
made.remote = string::copy_of(&text);
made.local = true;
return made;
}
val split := ref_at(text.span);
made.remote = string::from(text.span.substr(0, split), nothing {});
made.branch = split < text.length
? string::from(text.span.substr(split + 1, text.length - split - 1), nothing {})
: string::from("main", nothing {});
if made.remote.length == 0 || made.branch.length == 0 {
this.fail(line, $"`{text.span}` is no requirement: write `REMOTE@REF` or a folder, as `../shapes`.");
}
return made;
}
var made := requirement { line = line, file = path::copy_of(&this.at) };
return made if !this.keys(value, ["remote", "branch", "options"], "a requirement");
made.remote = this.needed(value, "remote");
made.local = is_folder_text(made.remote.span);
made.branch = string::from("main", nothing {});
if value.get("branch") is some(branch) {
made.branch = this.text(&branch, "`branch`");
if made.local {
this.fail(branch.place.line, string::from("A folder takes no `branch`.", nothing {}));
}
}
if value.get("options") is some(options) {
return made if !this.keys(&options, span::<strview>::blank(), "a requirement's options");
for each in options.members() {
made.options.append(setting { name = string::from(each.name, nothing {}), value = this.text(&each.value, "An option's value") });
}
}
return made;
}
# Reads a target, or a test, which takes the keys of tests too.
def reading::target(&mut this, value: &yaml::value, test: bool): target {
var made := target { line = value.place.line, file = path::copy_of(&this.at) };
if test {
return made if !this.keys(value, ["name", "type", "level", "petal", "target", "deps", "srcs", "opts", "runs", "checks", "args"], "a test");
} else {
return made if !this.keys(value, ["name", "type", "level", "petal", "target", "deps", "srcs", "opts", "root", "title", "icon", "windowed"], "a target");
}
made.name = this.needed(value, "name");
val kind := this.needed(value, "type");
return made if this.failed;
if kind == "program" {
made.kind = target_kind::program;
} else if kind == "library" && !test {
made.kind = target_kind::library;
} else {
val line := value.get("type").some.place.line;
this.fail(line, test ? $"A test's `type` is `program`, not `{kind.span}`." : $"`type` is `program` or `library`, not `{kind.span}`.");
return made;
}
if made.kind == target_kind::library {
for key in ["level", "petal", "target", "srcs", "opts", "title", "icon", "windowed"] {
if value.get(key) is some(given) {
this.fail(given.place.line, $"A library takes no `{key}`: it's read by the programs that import it.");
return made;
}
}
if !is_library_name(made.name.span) {
this.fail(made.line, $"`{made.name.span}` names no module: a library's name is its module's, with `.` for `::`, as `hello.geometry`.");
return made;
}
made.root = $"./{made.name.span}";
if value.get("root") is some(root) {
made.root = this.text(&root, "`root`");
}
} else {
if value.get("root") is some(root) {
this.fail(root.place.line, string::from("Only a library takes a `root`.", nothing {}));
return made;
}
if !is_file_name(made.name.span) {
this.fail(made.line, $"`{made.name.span}` can't name a program's file: write letters, digits, `.`, `_`, or `-`.");
return made;
}
}
if value.get("level") is some(level) {
val text := this.text(&level, "`level`");
if text != "0" && text != "1" && text != "2" {
this.fail(level.place.line, $"`level` is 0, 1, or 2, not `{text.span}`.");
return made;
}
made.level = (text[0] - '0') as u32;
}
if value.get("petal") is some(petal) {
made.petal = this.boolean(&petal, "`petal`");
}
if value.get("target") is some(system) {
made.system = this.text(&system, "`target`");
if !is_platform(made.system.span) {
this.fail(system.place.line, $"`{made.system.span}` is no target: write `linux-x86_64` or `windows-x86_64`.");
return made;
}
}
if value.get("deps") is some(deps) {
made.deps = this.texts(&deps, "`deps`");
}
if value.get("srcs") is some(srcs) {
made.srcs = this.texts(&srcs, "`srcs`");
}
if value.get("opts") is some(opts) {
made.opts = this.texts(&opts, "`opts`");
}
if value.get("args") is some(args) {
made.args = this.texts(&args, "`args`");
}
# How a program is shown: its title, its icon's files, and whether it's
# windowed, each of which may be an option's value, as an editor building a
# game gives them with `-o`: an empty title or icon is none.
if value.get("title") is some(title) {
made.title = this.text(&title, "`title`");
}
if value.get("icon") is some(icon) {
made.icons = this.icon_files(&icon);
return made if this.failed;
}
if value.get("windowed") is some(windowed) {
made.windowed = this.boolean(&windowed, "`windowed`");
}
made.checks = true;
if value.get("runs") is some(runs) {
val text := this.text(&runs, "`runs`");
if text == "native" {
made.runs = runner::native;
made.checks = false;
} else if text != "machine" {
this.fail(runs.place.line, $"`runs` is `machine` or `native`, not `{text.span}`.");
return made;
}
}
if value.get("checks") is some(checks) {
made.checks = this.boolean(&checks, "`checks`");
}
# A program needs files, which a test finds in `tests/` unless it says.
if made.kind == target_kind::program && made.srcs.length == 0 {
if !test {
this.fail(made.line, $"`{made.name.span}` needs `srcs`: its files, folders, or globs.");
return made;
}
made.srcs.append(string::from("tests/**/*.sakura", nothing {}));
}
return made;
}
# Reads a step of installing: a tag saying what it does, and its text.
def reading::step(&mut this, value: &yaml::value): step {
val line := value.place.line;
var made := step { line = line };
val tag := value.tag;
if tag is none {
this.fail(line, string::from("A step of `install` says what it does with a tag, as `!include ./share`.", nothing {}));
return made;
}
if tag.some != "!include" {
this.fail(line, $"`{tag.some}` is no step blossom knows: it knows `!include`.");
return made;
}
made.tag = string::from(tag.some, nothing {});
val text := this.text(value, "A step");
val split := text.span.find(":");
if split is some(at) {
made.source = string::from(text.span.substr(0, at), nothing {});
made.dest = string::from(text.span.substr(at + 1, text.length - at - 1), nothing {});
} else {
made.source = string::copy_of(&text);
}
if made.source.length == 0 || !is_within(made.source.span) {
this.fail(line, $"`{made.source.span}` is outside the project: a source is a path within it, as `./share`.");
} else if text.span.find(":") is some && (made.dest.length == 0 || !is_within(made.dest.span)) {
this.fail(line, $"`{made.dest.span}` is outside the prefix: a destination is a path within it, as `share/doc`.");
}
return made;
}
# Checks what reading each part couldn't: names given once, exports that are
# libraries, and libraries' roots within the project.
def reading::validate(&mut this, made: &mut project, root: &yaml::value): void {
val count := made.targets.length + made.tests.length;
for k in 0..count {
val each := &made.at(k);
for j in 0..k {
if made.at(j).name == each.name {
val first := &made.at(j);
val earlier := first.file == each.file ? $"line {first.line}" : $"{first.file.span}:{first.line}";
this.fail_in(each.file.span, each.line, $"`{each.name.span}` names two targets: this, and that of {earlier.span}.");
return;
}
}
if each.kind == target_kind::library && !is_within(each.root.span) {
this.fail_in(each.file.span, each.line, $"`{each.root.span}` is outside the project: a library's root is a folder within it.");
return;
}
}
for &name in made.exports {
val found := made.find(name.span);
if found is none || found.some >= made.targets.length || made.targets[found.some].kind != target_kind::library {
this.fail(root.get("exports").some.place.line, $"`{name.span}` is exported, but it's no library of {made.identity.span}.");
return;
}
}
}
# Checks a mapping's keys: each one of those allowed, unless none are named,
# where any is, and none written twice, which YAML would keep only one of.
def reading::keys(&mut this, map: &yaml::value, allowed: span<strview>, what: strview): bool {
if map.kind != yaml::kind::mapping {
this.fail(map.place.line, $"{what} is a mapping of keys and values.");
return false;
}
var seen := vector::<strview>::new();
for each in map.members() {
val line := each.key.place.line;
var known := allowed.length == 0;
for &name in allowed {
known = known || name == each.name;
}
if !known {
this.fail(line, $"`{each.name}` is no key of {what}.");
return false;
}
for &prior in seen {
if prior == each.name {
this.fail(line, $"`{each.name}` is written twice in {what}.");
return false;
}
}
seen.append(each.name);
}
return true;
}
# The elements of a sequence, or none where the value is another kind, which
# is noted.
def reading::list(&mut this, value: &yaml::value, what: strview): yaml::value::element_cursor {
if value.kind != yaml::kind::sequence && !value.is_null {
this.fail(value.place.line, $"{what} is a list, of lines starting with `-`.");
}
return value.elements();
}
# A scalar's text, with options replaced.
def reading::text(&mut this, value: &yaml::value, what: strview): string {
val read := value.as_scalar() else (_) {
this.fail(value.place.line, $"{what} is a scalar, not a list or a mapping.");
return string::new(nothing {});
};
return this.expanded(read, value.place.line);
}
# The texts of a list of scalars.
def reading::texts(&mut this, value: &yaml::value, what: strview): vector<string> {
var made := vector::<string>::new();
for each in this.list(value, what) {
made.append(this.text(&each, $"Each of {what}".span));
}
return made;
}
# The files an `icon` names: a file, or a list of them, each text naming any
# number with `,` between them, as an option's value names several, and none
# where it's empty. Each is a PNG, an SVG, or an icon file, by its ending.
def reading::icon_files(&mut this, value: &yaml::value): vector<string> {
var texts := vector::<string>::new();
if value.kind == yaml::kind::sequence {
texts = this.texts(value, "`icon`");
} else if !value.is_null {
texts.append(this.text(value, "`icon`"));
}
var made := vector::<string>::new();
for &text in texts {
for part in text.span.split(',') {
val file := part.trim();
continue if file.length == 0;
if !is_icon_file(file) {
this.fail(value.place.line, $"`{file}` is no icon blossom knows: write a `.png`, an `.svg`, or an `.ico`.");
return made;
}
made.append(string::from(file, nothing {}));
}
}
return made;
}
# A key's text, which must be written.
def reading::needed(&mut this, map: &yaml::value, key: strview): string {
if map.get(key) is some(value) {
var made := this.text(&value, $"`{key}`".span);
if made.length == 0 {
this.fail(value.place.line, $"`{key}` is empty.");
}
return made;
}
this.fail(map.place.line, $"`{key}` is needed.");
return string::new(nothing {});
}
# A key's text, or empty where it isn't written.
def reading::optional(&mut this, map: &yaml::value, key: strview): string {
if map.get(key) is some(value) {
return this.text(&value, $"`{key}`".span);
}
return string::new(nothing {});
}
# A scalar's truth, written `true` or `false`.
def reading::boolean(&mut this, value: &yaml::value, what: strview): bool {
val text := this.text(value, what);
if text != "true" && text != "false" {
this.fail(value.place.line, $"{what} is `true` or `false`, not `{text.span}`.");
}
return text == "true";
}
# Text with each `${NAME}` replaced by the option's value, noting a name that's
# no option's.
def reading::expanded(&mut this, text: strview, line: u32): string {
var made := string::new(nothing {});
var at := 0u;
while at < text.length {
if text[at] == '$' && at + 1 < text.length && text[at + 1] == '{' {
val rest := text.substr(at + 2, text.length - at - 2);
if rest.find("}") is some(length) {
val name := rest.substr(0, length);
var found := false;
for &each in this.options {
if !found && each.name.span == name {
made.append(each.value.span);
found = true;
}
}
if !found {
var message := string::from("`$", nothing {});
message.push('{');
message.append(name);
message.append("}` names no option declared before it.");
this.fail(line, move(message));
return made;
}
at += length + 3;
continue;
}
}
made.push(text[at]);
at++;
}
return made;
}
#! The name of a project's output folder: the 64-bit hash of its identity, its
#! options' values, and what its targets are built for, in hex.
#! @param identity As `malunal/hello@1.0.0`.
#! @param options Its options' values.
#! @param platform What `--target` says, or empty.
#! @returns Sixteen hex digits.
pub def output_key(identity: strview, options: span<setting>, platform: strview): string {
var text := string::from(identity, nothing {});
# In order by name, so writing the options in another order changes nothing.
var order := vector::<u64>::new();
for k in 0..options.length {
var at := order.length;
while at > 0 && options[order[at - 1]].name.span.compare(options[k].name.span) > 0 {
at--;
}
order.insert_at(at, k);
}
for k in order {
text.append($"\n{options[k].name.span}={options[k].value.span}".span);
}
text.append($"\ntarget={platform}".span);
return hex(hash(&text));
}
#! A number as sixteen hex digits.
#! @param value The number.
#! @returns Its digits, the highest first.
pub def hex(value: u64): string {
val digits: strview = "0123456789abcdef";
var made := string::new(nothing {});
var shift := 64u;
while shift > 0 {
shift -= 4;
made.push(digits[(value >> shift) & 15]);
}
return made;
}
#! Whether text is a version: three numbers, as `1.2.0`, then a `-` and what
#! comes before release, as `-alpha`, and a `+` and what it was built from, as
#! semantic versioning has them.
#! @param text The text.
#! @returns Whether it is one.
pub def is_version(text: strview): bool {
var at := 0u;
for part in 0..3 {
if part > 0 {
return false if at >= text.length || text[at] != '.';
at++;
}
val start := at;
while at < text.length && text[at].is_digit {
at++;
}
return false if at == start;
}
if at < text.length && (text[at] == '-' || text[at] == '+') {
at++;
return false if at == text.length;
while at < text.length {
val byte := text[at];
return false if !(byte.is_alnum || byte == '.' || byte == '-' || byte == '+');
at++;
}
}
return at == text.length;
}
#! Whether a requirement's text is a folder rather than a remote: a path
#! starting with `.` or a root.
#! @param text The text.
#! @returns Whether it is.
pub def is_folder_text(text: strview): bool {
return text.length != 0 && (text[0] == '.' || text[0] == '/' || text[0] == '\\' || (text.length > 1 && text[1] == ':' && text[0].is_alpha && text.find("://") is none));
}
# Where the `@` before a remote's ref is: the first after the remote's last `/`
# or `:`, or the text's length where there is none.
def ref_at(text: strview): u64 {
var from := 0u;
for k in 0..text.length {
if text[k] == '/' || text[k] == ':' {
from = k + 1;
}
}
for k in from..text.length {
return k if text[k] == '@';
}
return text.length;
}
# Whether a name is a module's, with `.` for `::`, as `hello.geometry`, and not
# one of the toolchain's own.
def is_library_name(name: strview): bool {
return false if name == "std" || name == "core" || name == "system" || name == "runtime";
var start := 0u;
for k in 0..=name.length {
if k == name.length || name[k] == '.' {
return false if k == start || name[start].is_digit;
start = k + 1;
continue;
}
return false if !name[k].is_ident;
}
return true;
}
# Whether a name can be a program's file.
def is_file_name(name: strview): bool {
return false if name.length == 0 || name == "." || name == "..";
for k in 0..name.length {
val byte := name[k];
return false if !(byte.is_alnum || byte == '.' || byte == '_' || byte == '-');
}
return true;
}
#! Whether `--target`, or a target's `target`, names a system blossom builds for.
#! @param text The name.
#! @returns Whether it does.
pub def is_platform(text: strview): bool {
for &each in platforms {
return true if each == text;
}
return false;
}
#! Whether a file is one an `icon` may name, by its ending, in any case: a PNG,
#! an SVG, or an icon file.
#! @param file The file.
#! @returns Whether it is.
pub def is_icon_file(file: strview): bool {
return ends_with_any_case(file, ".png") || ends_with_any_case(file, ".svg") || ends_with_any_case(file, ".ico");
}
#! Whether text ends with an ending, written in lower case, in any case.
#! @param text The text.
#! @param ending The ending.
#! @returns Whether it does.
pub def ends_with_any_case(text: strview, ending: strview): bool {
return false if text.length < ending.length;
val from := text.length - ending.length;
for k in 0..ending.length {
var byte := text[from + k];
if byte >= 'A' as u8 && byte <= 'Z' as u8 {
byte = byte + 32;
}
return false if byte != ending[k];
}
return true;
}
# Whether a path stays within the folder it's taken from: relative, with no `..`.
def is_within(text: strview): bool {
return false if text.length == 0 || text[0] == '/' || text[0] == '\\' || (text.length > 1 && text[1] == ':');
for part in text.split('/') {
return false if part == "..";
for inner in part.split('\\') {
return false if inner == "..";
}
}
return true;
}
+351
View File
@@ -0,0 +1,351 @@
#! @file archives.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what packages are written as: a tar archive, a zip file holding
#! its files stored rather than compressed, and an `ar` archive, which a
#! Debian package is. Each is written whole into memory, every entry owned by
#! root and dated alike, so the same stage writes the same bytes. Compressing
#! them is the system's `gzip`, `xz`, and `zstd`.
import std::io;
import system;
module blossom::pipeline;
#! A file or folder of a package.
pub struct entry {
pub var name: string; #! Its path within the package, with `/`, without one at the end.
pub var source: path; #! The file it's read from, or empty for a folder.
pub var folder: bool;
pub var mode: u32; #! Who may read, write, and run it.
}
#! Lists what a stage holds, as entries under a root: the root's own folders
#! first, then each folder before what it holds, in order by name.
#! @param stage The stage.
#! @param root Where its files go in the package, as `usr` or
#! `hello-1.0.0-linux-x86_64`, or empty for its top.
#! @returns The entries.
pub def staged(stage: &path, root: strview): vector<entry> {
var made := vector::<entry>::new();
var above := string::new(nothing {});
for part in root.split('/') {
continue if part.length == 0;
if above.length != 0 {
above.push('/');
}
above.append(part);
made.append(entry { name = string::copy_of(&above), folder = true, mode = 0o755 });
}
walked(stage, above.span, &mut made);
return made;
}
# Adds what a folder holds, in order by name, each folder before what it holds.
def walked(folder: &path, under: strview, into: &mut vector<entry>): void {
var names := vector::<string>::new();
var listing := io::directory::open(folder) else (_) { return; };
while listing.next() is some(each) {
names.append(string::from(each.name, nothing {}));
}
names.sort_by(def(a: &string, b: &string): bool { return a.span.compare(b.span) < 0; });
for &name in names {
val at := folder.join(name.span);
val text := under.length != 0 ? $"{under}/{name.span}" : string::copy_of(name);
val found := io::info(&at) else (_) { continue; };
if found.kind == file_kind::directory {
into.append(entry { name = string::copy_of(&text), folder = true, mode = 0o755 });
walked(&at, text.span, into);
} else {
into.append(entry {
name = string::copy_of(&text),
source = path::copy_of(&at),
mode = (found.permissions & 0o111) != 0 ? 0o755 : 0o644
});
}
}
}
#! A tar archive, as POSIX's ustar writes one, with GNU's long names for a path
#! too long to split between a header's name and prefix.
pub struct tar {
pub var bytes: string;
pub var mtime: i64; #! When every entry was written, in seconds since 1970.
}
#! Adds a folder.
#! @param this The archive.
#! @param name Its path, which `/` is added to.
pub def tar::folder(&mut this, name: strview): void {
val named := $"{name}/";
this.header(named.span, 0o755, 0, '5');
}
#! Adds a file.
#! @param this The archive.
#! @param name Its path.
#! @param data What it holds.
#! @param mode Who may read, write, and run it.
pub def tar::file(&mut this, name: strview, data: span<u8>, mode: u32): void {
this.header(name, mode, data.length, '0');
this.bytes.append(data);
this.pad();
}
#! Ends the archive with its two empty blocks.
#! @param this The archive.
#! @returns Its bytes.
pub def tar::finish(&mut this): strview {
for _ in 0..1024 {
this.bytes.push(0);
}
return this.bytes.span;
}
# Writes an entry's header, after a long name's own entry where it needs one.
def tar::header(&mut this, name: strview, mode: u32, size: u64, kind: u8): void {
var split := name.length;
if name.length > 100 {
# The last `/` leaving a name of 100 bytes or fewer, with 155 or fewer
# before it.
split = 0;
for k in 0..name.length {
if name[k] == '/' && name.length - k - 1 <= 100 && k <= 155 && k > 0 {
split = k;
break;
}
}
if split == 0 {
val longer := $"{name}\0";
this.header("././@LongLink", 0o644, longer.length, 'L');
this.bytes.append(longer.span);
this.pad();
split = name.length;
}
}
var block: u8[512];
for k in 0..512 {
block[k] = 0;
}
val base := split == name.length ? name : name.substr(split + 1, name.length - split - 1);
val prefix := split == name.length ? strview::blank() : name.substr(0, split);
put(&mut block, 0, base.substr(0, 100));
put_octal(&mut block, 100, 8, mode as u64);
put_octal(&mut block, 108, 8, 0);
put_octal(&mut block, 116, 8, 0);
put_octal(&mut block, 124, 12, size);
put_octal(&mut block, 136, 12, this.mtime as u64);
for k in 148..156 {
block[k] = ' ';
}
block[156] = kind;
put(&mut block, 257, "ustar");
put(&mut block, 263, "00");
put(&mut block, 265, "root");
put(&mut block, 297, "root");
put(&mut block, 345, prefix);
var sum := 0u;
for k in 0..512 {
sum += block[k] as u64;
}
put_octal(&mut block, 148, 7, sum);
block[155] = ' ';
this.bytes.append(strview::over((&block) as *u8, 512));
}
# Pads the archive to a whole block.
def tar::pad(&mut this): void {
while this.bytes.length % 512 != 0 {
this.bytes.push(0);
}
}
# Writes text into a header from a byte.
def put(block: &mut u8[512], at: u64, text: strview): void {
for k in 0..text.length {
block[at + k] = text[k];
}
}
# Writes a number in octal into a header, in a field of a width: zeros before
# it, and a zero byte after.
def put_octal(block: &mut u8[512], at: u64, width: u64, value: u64): void {
var left := value;
var k := width - 1;
block[at + k] = 0;
while k > 0 {
k--;
block[at + k] = ('0' + (left & 7) as u8);
left = left >> 3;
}
}
#! A zip file whose files are stored as they are, rather than compressed, with
#! who may run each in the Unix bits of its attributes.
pub struct zip {
pub var bytes: string;
pub var central: string; #! The central directory, written after the files.
pub var count: u64;
pub var mtime: i64; #! When every entry was written, in seconds since 1970.
}
#! Adds a folder.
#! @param this The zip file.
#! @param name Its path, which `/` is added to.
pub def zip::folder(&mut this, name: strview): void {
val named := $"{name}/";
this.add(named.span, strview::blank(), 0o040000 | 0o755, 0x10);
}
#! Adds a file.
#! @param this The zip file.
#! @param name Its path.
#! @param data What it holds.
#! @param mode Who may read, write, and run it.
pub def zip::file(&mut this, name: strview, data: span<u8>, mode: u32): void {
this.add(name, data, 0o100000 | mode, 0);
}
# Adds an entry: its header, its bytes, and its record in the central directory.
def zip::add(&mut this, name: strview, data: span<u8>, unix: u32, dos: u32): void {
val offset := this.bytes.length;
val crc := crc32(data);
val stamp := dos_stamp(this.mtime);
put_u32(&mut this.bytes, 0x04034b50);
put_u16(&mut this.bytes, 20);
put_u16(&mut this.bytes, 0x0800); # Names are UTF-8.
put_u16(&mut this.bytes, 0);
put_u32(&mut this.bytes, stamp);
put_u32(&mut this.bytes, crc);
put_u32(&mut this.bytes, data.length as u32);
put_u32(&mut this.bytes, data.length as u32);
put_u16(&mut this.bytes, name.length as u16);
put_u16(&mut this.bytes, 0);
this.bytes.append(name);
this.bytes.append(data);
put_u32(&mut this.central, 0x02014b50);
put_u16(&mut this.central, (3 << 8) | 20); # Made on Unix.
put_u16(&mut this.central, 20);
put_u16(&mut this.central, 0x0800);
put_u16(&mut this.central, 0);
put_u32(&mut this.central, stamp);
put_u32(&mut this.central, crc);
put_u32(&mut this.central, data.length as u32);
put_u32(&mut this.central, data.length as u32);
put_u16(&mut this.central, name.length as u16);
put_u16(&mut this.central, 0);
put_u16(&mut this.central, 0);
put_u16(&mut this.central, 0);
put_u16(&mut this.central, 0);
put_u32(&mut this.central, (unix << 16) | dos);
put_u32(&mut this.central, offset as u32);
this.central.append(name);
this.count++;
}
#! Ends the zip file with its central directory.
#! @param this The zip file.
#! @returns Its bytes.
pub def zip::finish(&mut this): strview {
val start := this.bytes.length;
this.bytes.append(this.central.span);
put_u32(&mut this.bytes, 0x06054b50);
put_u16(&mut this.bytes, 0);
put_u16(&mut this.bytes, 0);
put_u16(&mut this.bytes, this.count as u16);
put_u16(&mut this.bytes, this.count as u16);
put_u32(&mut this.bytes, this.central.length as u32);
put_u32(&mut this.bytes, start as u32);
put_u16(&mut this.bytes, 0);
return this.bytes.span;
}
# A time as MS-DOS keeps it, as zip files do: the date in the high half, the
# time in the low, in two-second steps, from 1980 on.
def dos_stamp(seconds: i64): u32 {
val at := seconds < 315532800 ? 315532800 : seconds;
val days := at / 86400;
val left := at % 86400;
val date := civil_of(days);
val day := ((date.year - 1980) as u32 << 9) | (date.month as u32 << 5) | date.day as u32;
val time := ((left / 3600) as u32 << 11) | (((left % 3600) / 60) as u32 << 5) | ((left % 60) / 2) as u32;
return (day << 16) | time;
}
# A day of the Gregorian calendar.
struct civil {
var year: i64;
var month: i64;
var day: i64;
}
# The date a number of days after 1970-01-01 is, as Howard Hinnant's
# `civil_from_days` works it out.
def civil_of(days: i64): civil {
val z := days + 719468;
val era := (z >= 0 ? z : z - 146096) / 146097;
val doe := z - era * 146097;
val yoe := (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
val doy := doe - (365 * yoe + yoe / 4 - yoe / 100);
val mp := (5 * doy + 2) / 153;
val day := doy - (153 * mp + 2) / 5 + 1;
val month := mp < 10 ? mp + 3 : mp - 9;
return civil { year = yoe + era * 400 + (month <= 2 ? 1 : 0), month = month, day = day };
}
#! An `ar` archive, as a Debian package is: its signature, then each member
#! with a header of 60 bytes.
pub struct ar {
pub var bytes: string;
pub var mtime: i64;
}
#! Starts an archive.
#! @param mtime When every member was written, in seconds since 1970.
#! @returns The archive, holding its signature.
pub def ar::new(mtime: i64): ar {
return ar { bytes = string::from("!<arch>\n", nothing {}), mtime = mtime };
}
#! Adds a member.
#! @param this The archive.
#! @param name Its name, of 16 bytes or fewer.
#! @param data What it holds.
pub def ar::member(&mut this, name: strview, data: span<u8>): void {
this.bytes.append(padded(name, 16).span);
this.bytes.append(padded($"{this.mtime}".span, 12).span);
this.bytes.append(padded("0", 6).span);
this.bytes.append(padded("0", 6).span);
this.bytes.append(padded("100644", 8).span);
this.bytes.append(padded($"{data.length}".span, 10).span);
this.bytes.append("`\n");
this.bytes.append(data);
if data.length % 2 != 0 {
this.bytes.push('\n');
}
}
# Text with spaces after it, to a width.
def padded(text: strview, width: u64): string {
var made := string::from(text, nothing {});
while made.length < width {
made.push(' ');
}
return made;
}
# Adds a number of two bytes, the low first.
def put_u16(into: &mut string, value: u32): void {
into.push((value & 0xff) as u8);
into.push(((value >> 8) & 0xff) as u8);
}
# Adds a number of four bytes, the low first.
def put_u32(into: &mut string, value: u32): void {
put_u16(into, value & 0xffff);
put_u16(into, value >> 16);
}
+266
View File
@@ -0,0 +1,266 @@
#! @file digests.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the digests packages carry: MD5, which Debian's `md5sums` lists,
#! SHA-256, which Arch's `.MTREE` lists beside MD5, and CRC-32, which a zip
#! file keeps of each file it holds. Both digests add words modulo 2^32, so
#! they add through `math::wrapping_add`, which a program run or built with
#! `--checks` doesn't stop at.
import std::math;
module blossom::pipeline;
#! The MD5 digest of bytes, as RFC 1321 gives it.
#! @param data The bytes.
#! @returns The digest, as 32 hex digits.
pub def md5(data: span<u8>): string {
var state: u32[4] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476];
var block: u8[64];
val total := data.length;
var at := 0u;
while at + 64 <= total {
md5_block(&mut state, data.data + at);
at += 64;
}
# The last bytes, then `0x80`, then zeros, then the length in bits, low
# byte first, filling one block or two.
val left := total - at;
for k in 0..64 {
block[k] = 0;
}
for k in 0..left {
block[k] = data[at + k];
}
block[left] = 0x80;
if left >= 56 {
md5_block(&mut state, (&block) as *u8);
for k in 0..64 {
block[k] = 0;
}
}
val bits := total * 8;
for k in 0..8 {
block[56 + k] = ((bits >> (8 * k as u64)) & 0xff) as u8;
}
md5_block(&mut state, (&block) as *u8);
var made := string::new(nothing {});
for word in state {
for k in 0..4 {
append_hex(&mut made, ((word >> (8 * k as u32)) & 0xff) as u8);
}
}
return made;
}
# The amounts each round of MD5 turns its words left by.
val md5_turns: u32[16] = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
# Mixes a block of 64 bytes into MD5's state.
def md5_block(state: &mut u32[4], at: *u8): void {
var words: u32[16];
for k in 0..16 {
val from := at + 4 * k;
words[k] = from[0] as u32 | (from[1] as u32 << 8) | (from[2] as u32 << 16) | (from[3] as u32 << 24);
}
var a := state[0];
var b := state[1];
var c := state[2];
var d := state[3];
for i in 0u..64u {
var mixed: u32 = 0;
var index: u64 = 0;
if i < 16 {
mixed = (b & c) | (~b & d);
index = i;
} else if i < 32 {
mixed = (d & b) | (~d & c);
index = (5 * i + 1) % 16;
} else if i < 48 {
mixed = b ^ c ^ d;
index = (3 * i + 5) % 16;
} else {
mixed = c ^ (b | ~d);
index = (7 * i) % 16;
}
val sum := sum_of([a, mixed, md5_constant(i), words[index]]);
a = d;
d = c;
c = b;
b = sum_of([b, turned_left(sum, md5_turns[(i / 16) * 4 + i % 4])]);
}
state[0] = sum_of([state[0], a]);
state[1] = sum_of([state[1], b]);
state[2] = sum_of([state[2], c]);
state[3] = sum_of([state[3], d]);
}
# MD5's constant of each step: the whole part of 2^32 times the sine of the
# step's number, counted from 1.
def md5_constant(i: u64): u32 {
return md5_constants[i];
}
val md5_constants: u32[64] = [
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
];
#! The SHA-256 digest of bytes, as FIPS 180-4 gives it.
#! @param data The bytes.
#! @returns The digest, as 64 hex digits.
pub def sha256(data: span<u8>): string {
var state: u32[8] = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
var block: u8[64];
val total := data.length;
var at := 0u;
while at + 64 <= total {
sha256_block(&mut state, data.data + at);
at += 64;
}
# As MD5 pads, but with the length's high byte first.
val left := total - at;
for k in 0..64 {
block[k] = 0;
}
for k in 0..left {
block[k] = data[at + k];
}
block[left] = 0x80;
if left >= 56 {
sha256_block(&mut state, (&block) as *u8);
for k in 0..64 {
block[k] = 0;
}
}
val bits := total * 8;
for k in 0..8 {
block[63 - k] = ((bits >> (8 * k as u64)) & 0xff) as u8;
}
sha256_block(&mut state, (&block) as *u8);
var made := string::new(nothing {});
for word in state {
for k in 0..4 {
append_hex(&mut made, ((word >> (24 - 8 * k as u32)) & 0xff) as u8);
}
}
return made;
}
# SHA-256's constants: the first 32 bits of the fractional parts of the cube
# roots of the first 64 primes.
val sha256_constants: u32[64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];
# Mixes a block of 64 bytes into SHA-256's state.
def sha256_block(state: &mut u32[8], at: *u8): void {
var words: u32[64];
for k in 0..16 {
val from := at + 4 * k;
words[k] = (from[0] as u32 << 24) | (from[1] as u32 << 16) | (from[2] as u32 << 8) | from[3] as u32;
}
for k in 16..64 {
val low := words[k - 15];
val high := words[k - 2];
val small0 := turned_right(low, 7) ^ turned_right(low, 18) ^ (low >> 3);
val small1 := turned_right(high, 17) ^ turned_right(high, 19) ^ (high >> 10);
words[k] = sum_of([words[k - 16], small0, words[k - 7], small1]);
}
var a := state[0];
var b := state[1];
var c := state[2];
var d := state[3];
var e := state[4];
var f := state[5];
var g := state[6];
var h := state[7];
for k in 0..64 {
val big1 := turned_right(e, 6) ^ turned_right(e, 11) ^ turned_right(e, 25);
val chosen := (e & f) ^ (~e & g);
val first := sum_of([h, big1, chosen, sha256_constants[k], words[k]]);
val big0 := turned_right(a, 2) ^ turned_right(a, 13) ^ turned_right(a, 22);
val major := (a & b) ^ (a & c) ^ (b & c);
val second := sum_of([big0, major]);
h = g;
g = f;
f = e;
e = sum_of([d, first]);
d = c;
c = b;
b = a;
a = sum_of([first, second]);
}
state[0] = sum_of([state[0], a]);
state[1] = sum_of([state[1], b]);
state[2] = sum_of([state[2], c]);
state[3] = sum_of([state[3], d]);
state[4] = sum_of([state[4], e]);
state[5] = sum_of([state[5], f]);
state[6] = sum_of([state[6], g]);
state[7] = sum_of([state[7], h]);
}
#! The CRC-32 of bytes, as zip files and gzip keep it: the polynomial
#! `0xEDB88320`, reflected, starting from and ending with every bit flipped.
#! @param data The bytes.
#! @returns The checksum.
pub def crc32(data: span<u8>): u32 {
var crc: u32 = 0xFFFFFFFF;
for k in 0..data.length {
crc = crc ^ data[k] as u32;
for _ in 0..8 {
val low := crc & 1;
crc = crc >> 1;
if low != 0 {
crc = crc ^ 0xEDB88320;
}
}
}
return ~crc;
}
# Words added modulo 2^32, as both digests add them.
def sum_of(words: span<u32>): u32 {
var sum: u32 = 0;
for word in words {
sum = math::wrapping_add(sum, word);
}
return sum;
}
# A word turned left, its high bits coming round to the low.
def turned_left(word: u32, by: u32): u32 {
return (word << by) | (word >> (32 - by));
}
# A word turned right, its low bits coming round to the high.
def turned_right(word: u32, by: u32): u32 {
return (word >> by) | (word << (32 - by));
}
# Adds a byte as two hex digits.
def append_hex(into: &mut string, byte: u8): void {
val digits: strview = "0123456789abcdef";
into.push(digits[(byte >> 4) as u64]);
into.push(digits[(byte & 15) as u64]);
}
+285
View File
@@ -0,0 +1,285 @@
#! @file install.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `install`: the project built, then its programs put in the prefix's
#! `bin`, its exported libraries in `share/sakura`, as source another project's
#! `--lib` reads, and each `install` step done in turn.
import std::io;
import std::process;
import system;
import blossom::models;
import blossom::management;
module blossom::pipeline;
#! Builds the project, then installs it.
#! @param this The session.
#! @param prefix Where it's installed, or empty for `~/.local`.
#! @param destdir A folder to put what's installed under, as DESTDIR/PREFIX,
#! or empty.
#! @returns The status the command ends with.
pub def session::install_command(&mut this, prefix: strview, destdir: strview): i32 {
var into := path::new();
if prefix.length != 0 {
val named := path::parse(prefix) else (_) {
fatal(2, $"`--prefix {prefix}` is no path.");
return 2;
};
into = io::absolute(&named) else (why) {
fatal(2, $"`--prefix {prefix}` can't be found: {why}.");
return 2;
};
} else {
val home := process::variable("HOME") else {
when os == windows {
if process::variable("USERPROFILE") is some(profile) {
return this.install_into(prefix_under(profile), destdir);
}
}
fatal(2, "`HOME` isn't set, so the prefix must be given, with `--prefix`.");
return 2;
};
into = prefix_under(home);
}
return this.install_into(move(into), destdir);
}
# Installs into a prefix, under a destination folder where one's given.
def session::install_into(&mut this, prefix: path, destdir: strview): i32 {
var into := path::copy_of(&prefix);
if destdir.length != 0 {
val named := path::parse(destdir) else (_) {
fatal(2, $"`--destdir {destdir}` is no path.");
return 2;
};
val stage := io::absolute(&named) else (why) {
fatal(2, $"`--destdir {destdir}` can't be found: {why}.");
return 2;
};
into = under_root(&stage, &prefix);
}
this.build(false, "");
if this.failed {
return 1;
}
val count := this.install(&into, prefix.span);
val files: strview = count == 1 ? "file" : "files";
io::println($"Installed {this.space.projects[0].identity.span} ({count} {files}) to {into.span}".span);
return 0;
}
#! Installs the project, already built, under a folder: its programs into
#! `bin`, each shown as a desktop's program for Linux with its desktop entry and
#! its icons, its exported libraries into `share/sakura`, then each step.
#! @param this The session.
#! @param into The folder, which stands for the prefix.
#! @param prefix The prefix itself, where a desktop entry finds its program.
#! @returns How many files were installed.
pub def session::install(&mut this, into: &path, prefix: strview): u64 {
val holder := &this.space.projects[0];
var count := 0u;
for &each in holder.targets {
if each.kind == models::target_kind::program {
val system := this.platform_of(&each);
val name := output_name(each.name.span, system);
val built := holder.folder.join($"{output_text(holder).span}/bin/{name.span}".span);
count += copied(&built, &into.join("bin").join(name.span));
val petal := holder.folder.join($"{output_text(holder).span}/bin/{name.span}.petal".span);
if io::exists(&petal) {
count += copied(&petal, &into.join("bin").join($"{name.span}.petal".span));
}
if each.shown && !for_windows(system) {
count += install_desktop_entry(holder, &each, into, prefix);
}
} else if holder.exported(each.name.span) {
val root := path::parse(each.root.span) else (_) { continue; };
count += copied(&holder.folder.join(&root), &into.join("share").join("sakura").join(each.name.span));
}
}
for &step in holder.install {
val source := path::parse(step.source.span) else (_) {
fatal(2, $"{holder.file.span}:{step.line}: `{step.source.span}` is no path.");
return count;
};
val from := holder.folder.join(&source);
if !io::exists(&from) {
fatal(2, $"{holder.file.span}:{step.line}: `{step.source.span}` isn't there to install.");
}
val to := step.dest.length != 0 ? path::parse(step.dest.span) : path::parse(step.source.span);
if to is value(&place) {
count += copied(&from, &into.join(place));
}
}
return count;
}
# Copies a file, or a folder and everything in it, making the folders above
# it, keeping who may run each, and giving how many files were copied. A copy
# that fails stops the command.
def copied(from: &path, to: &path): u64 {
val found := io::info(from) else (why) {
fatal(1, $"`{from.span}` can't be read: {why}.");
return 0;
};
if found.kind == file_kind::directory {
_ = io::create_directories(to);
var names := vector::<string>::new();
var listing := io::directory::open(from) else (why) {
fatal(1, $"`{from.span}` can't be read: {why}.");
return 0;
};
while listing.next() is some(entry) {
names.append(string::from(entry.name, nothing {}));
}
names.sort_by(def(a: &string, b: &string): bool { return a.span.compare(b.span) < 0; });
var count := 0u;
for &name in names {
count += copied(&from.join(name.span), &to.join(name.span));
}
return count;
}
if to.parent() is some(&above) {
_ = io::create_directories(above);
}
val bytes := io::read_file(from) else (why) {
fatal(1, $"`{from.span}` can't be read: {why}.");
return 0;
};
if io::write_file(to, bytes.span) is error(why) {
fatal(1, $"`{to.span}` can't be written: {why}.");
}
_ = io::set_permissions(to, (found.permissions & 0o111) != 0 ? 0o755 : 0o644);
return 1;
}
# Installs what Linux's desktops show a program by, as the freedesktop.org
# specifications have it, its file's name its own: each PNG of its `icon` into
# the icon theme every desktop reads, `share/icons/hicolor/WxH/apps`, by the
# size its header says, an SVG into its `scalable/apps`, and its desktop entry,
# `share/applications/NAME.desktop`, naming it by its title, its program where
# the prefix holds it, and its icon. An icon file holds Windows' icons alone,
# so it's left out here. Gives how many files were installed.
def install_desktop_entry(holder: &models::project, each: &models::target, into: &path, prefix: strview): u64 {
val name := each.name.span;
val icons := into.join("share/icons/hicolor");
var count := 0u;
var iconic := false;
for &file in each.icons {
val named := path::parse(file.span) else (_) {
fatal(2, $"{each.file.span}:{each.line}: `{file.span}` is no path.");
return count;
};
val from := holder.folder.join(&named);
if models::ends_with_any_case(file.span, ".svg") {
count += copied(&from, &icons.join($"scalable/apps/{name}.svg".span));
iconic = true;
} else if models::ends_with_any_case(file.span, ".png") {
val bytes := io::read_file(&from) else (why) {
fatal(1, $"`{from.span}` can't be read: {why}.");
return count;
};
val size := png_size(bytes.span);
if size[0] == 0 || size[1] == 0 {
fatal(2, $"{each.file.span}:{each.line}: `{file.span}` is no PNG.");
return count;
}
count += copied(&from, &icons.join($"{size[0]}x{size[1]}/apps/{name}.png".span));
iconic = true;
}
}
var entry := string::from("[Desktop Entry]\nType=Application\n", nothing {});
entry.append($"Name={one_line(each.title.length != 0 ? each.title.span : name).span}\n".span);
entry.append($"Exec={exec_text(prefix, name).span}\n".span);
if iconic {
entry.append($"Icon={name}\n".span);
}
entry.append(each.windowed ? "Terminal=false\n" : "Terminal=true\n");
entry.append($"StartupWMClass={name}\n".span);
val desktop := into.join($"share/applications/{name}.desktop".span);
if !written(&desktop, entry.span) {
fatal(1, $"`{desktop.span}` can't be written.");
}
_ = io::set_permissions(&desktop, 0o644);
return count + 1;
}
#! The size of a PNG, as its header says it.
#! @param bytes The file.
#! @returns Its width and height, or zeros where it's no PNG or is cut short.
pub def png_size(bytes: strview): u64[2] {
var made: u64[2];
return made if bytes.length < 24 || !bytes.starts_with("\x89PNG\r\n\x1A\n") || bytes.substr(12, 4) != "IHDR";
for k in 0..2u {
val at := 16 + 4 * k;
made[k] = (bytes[at] as u64 << 24) | (bytes[at + 1] as u64 << 16) | (bytes[at + 2] as u64 << 8) | bytes[at + 3] as u64;
}
return made;
}
#! What a desktop entry's `Exec` runs: the program in the prefix's `bin`, its
#! path's `\` written `/`, quoted where it holds what a desktop would split it
#! at, or read as its own, as the specification quotes it.
#! @param prefix The prefix.
#! @param name The program.
#! @returns The text.
pub def exec_text(prefix: strview, name: strview): string {
var end := prefix.length;
while end > 1 && (prefix[end - 1] == '/' || prefix[end - 1] == '\\') {
end--;
}
var whole := string::new(nothing {});
for k in 0..end {
whole.push(prefix[k] == '\\' ? '/' as u8 : prefix[k]);
}
whole.append($"/bin/{name}".span);
var plain := true;
for k in 0..whole.length {
val byte := whole[k];
plain = plain && !(byte == ' ' || byte == '\t' || byte == '"' || byte == '\'' || byte == '\\' || byte == '`' || byte == '$' || byte == '%');
}
return whole if plain;
var made := string::from("\"", nothing {});
for k in 0..whole.length {
val byte := whole[k];
if byte == '"' || byte == '`' || byte == '$' || byte == '\\' {
made.push('\\' as u8);
}
if byte == '%' {
made.push('%' as u8);
}
made.push(byte);
}
made.push('"' as u8);
return made;
}
# Text on one line, as a desktop entry's value is: each line break a space.
def one_line(text: strview): string {
var made := string::new(nothing {});
for k in 0..text.length {
made.push(text[k] == '\n' || text[k] == '\r' ? ' ' as u8 : text[k]);
}
return made;
}
# `.local` in a home folder, the prefix unless one's given.
def prefix_under(home: strview): path {
val at := path::parse(home) else (_) { return path::new(); };
return at.join(".local");
}
# A path put under a folder, as `/stage` and `/usr/local` make
# `/stage/usr/local`.
def under_root(stage: &path, at: &path): path {
var made := path::copy_of(stage);
for part in at.segments() {
made = made.join(part);
}
return made;
}
+478
View File
@@ -0,0 +1,478 @@
#! @file package.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `package`: the project installed into its stage, then written as
#! each package asked for into its output folder's `dist`. tar and zip files
#! hold the stage under a folder of the project's name, version, and target;
#! Debian and Arch packages hold it under the prefix they install to, `/usr`
#! unless given; and an rpm package is built by `rpmbuild` from a spec written
#! for it. Every entry is dated `SOURCE_DATE_EPOCH`, where it's set, so a
#! package is written alike each time.
import std::io;
import std::process;
import std::time;
import system;
import blossom::models;
import blossom::management;
module blossom::pipeline;
#! The packages blossom writes.
pub val formats: strview[5] = ["tar", "zip", "deb", "arch", "rpm"];
#! Builds the project, installs it into its stage, then writes its packages.
#! @param this The session.
#! @param asked The formats asked for, each a format or several with `,`
#! between them, or none for `tar`, or `zip` for Windows.
#! @param prefix Where a Debian, Arch, or rpm package installs, or empty for
#! `/usr`.
#! @returns The status the command ends with.
pub def session::package_command(&mut this, asked: span<strview>, prefix: strview): i32 {
var chosen := vector::<strview>::new();
for &each in asked {
for format in each.split(',') {
continue if format.length == 0;
var known := false;
for &name in formats {
known = known || name == format;
}
if !known {
fatal(2, $"`{format}` is no format: write `tar`, `zip`, `deb`, `arch`, or `rpm`.".span);
}
chosen.append(format);
}
}
val platform := this.package_platform();
if chosen.length == 0 {
chosen.append(platform == "windows-x86_64" ? "zip" : "tar");
}
var installed_at: strview = "/usr";
if prefix.length != 0 {
installed_at = prefix;
}
# What a system's package can't hold is said before anything's built.
for &format in chosen {
if format == "deb" || format == "arch" || format == "rpm" {
_ = distro_arch(platform, format, "");
_ = distro_name(&this.space.projects[0]);
_ = distro_version(&this.space.projects[0]);
}
}
this.build(false, "");
return 1 if this.failed;
val holder := &this.space.projects[0];
val output := holder.output;
val stage := output.join("stage");
val dist := output.join("dist");
if management::remove_tree(&stage) is error(why) {
fatal(1, $"`{stage.span}` can't be emptied: {why}.".span);
}
_ = io::create_directories(&stage);
# A program's desktop entry names it where a system's package installs it.
if this.install(&stage, installed_at) == 0 {
fatal(1, $"{holder.identity.span} installs nothing, so there's nothing to package.".span);
}
_ = io::create_directories(&dist);
val mtime := build_time();
for &format in chosen {
var made := path::new();
if format == "tar" || format == "zip" {
made = this.archive(format, &stage, &dist, platform, mtime);
} else if format == "deb" {
made = this.debian(&stage, &dist, trimmed(installed_at), platform, mtime);
} else if format == "arch" {
made = this.arch_package(&stage, &dist, trimmed(installed_at), platform, mtime);
} else {
made = this.rpm(&stage, &dist, trimmed(installed_at), platform);
}
io::println($"Packaged {made.span}".span);
}
return 0;
}
# What the packages are for: what `--target` says, else what the first program
# that says is built for, else the system blossom runs on.
def session::package_platform(&this): strview {
if this.space.platform.length != 0 {
return this.space.platform.span;
}
for &each in this.space.projects[0].targets {
if each.kind == models::target_kind::program && each.system.length != 0 {
return each.system.span;
}
}
when os == windows {
return "windows-x86_64";
}
return "linux-x86_64";
}
# Writes a tar archive, compressed by `gzip`, or a zip file, of the stage under
# a folder of the project's name, version, and target.
def session::archive(&mut this, format: strview, stage: &path, dist: &path, platform: strview, mtime: i64): path {
val holder := &this.space.projects[0];
val stem := $"{holder.name.span}-{holder.semv.span}-{platform}";
val items := staged(stage, stem.span);
if format == "zip" {
var made := zip { bytes = string::new(nothing {}), central = string::new(nothing {}), mtime = mtime };
for &item in items {
if item.folder {
made.folder(item.name.span);
} else {
val data := read_all(&item.source);
made.file(item.name.span, data.span, item.mode);
}
}
val at := dist.join($"{stem.span}.zip".span);
write_whole(&at, made.finish());
return at;
}
var made := tar { bytes = string::new(nothing {}), mtime = mtime };
add_items(&mut made, items.span, strview::blank());
val at := dist.join($"{stem.span}.tar".span);
write_whole(&at, made.finish());
return this.compressed(&at, "gzip", ".gz");
}
# Writes a Debian package: its control file and the digest of each file in a
# tar compressed by `gzip`, and the stage under the prefix in one compressed by
# `xz`, as members of an `ar` archive.
def session::debian(&mut this, stage: &path, dist: &path, prefix: strview, platform: strview, mtime: i64): path {
val holder := &this.space.projects[0];
val name := distro_name(holder);
val version := distro_version(holder);
val arch := distro_arch(platform, "deb", "amd64");
val items := staged(stage, prefix);
var sums := string::new(nothing {});
var size := 0u;
for &item in items {
continue if item.folder;
val data := read_all(&item.source);
size += data.length;
sums.append($"{md5(data.span).span} {item.name.span}\n".span);
}
var control := string::new(nothing {});
control.append($"Package: {name.span}\n".span);
control.append($"Version: {version.span}-1\n".span);
control.append($"Architecture: {arch}\n".span);
control.append($"Maintainer: {or_else(holder.package.auth.span, "Unknown <unknown@localhost>")}\n".span);
control.append($"Installed-Size: {(size + 1023) / 1024}\n".span);
control.append("Section: misc\nPriority: optional\n");
if holder.package.url.length != 0 {
control.append($"Homepage: {holder.package.url.span}\n".span);
}
control.append($"Description: {or_else(holder.package.desc.span, holder.name.span)}\n".span);
val work := dist.join("deb");
_ = management::remove_tree(&work);
_ = io::create_directories(&work);
var controls := tar { bytes = string::new(nothing {}), mtime = mtime };
controls.folder(".");
controls.file("./control", control.span, 0o644);
controls.file("./md5sums", sums.span, 0o644);
val control_at := work.join("control.tar");
write_whole(&control_at, controls.finish());
val control_gz := this.compressed(&control_at, "gzip", ".gz");
var data := tar { bytes = string::new(nothing {}), mtime = mtime };
data.folder(".");
add_items(&mut data, items.span, "./");
val data_at := work.join("data.tar");
write_whole(&data_at, data.finish());
val data_xz := this.compressed(&data_at, "xz", ".xz");
var made := ar::new(mtime);
made.member("debian-binary", "2.0\n");
made.member("control.tar.gz", read_all(&control_gz).span);
made.member("data.tar.xz", read_all(&data_xz).span);
val at := dist.join($"{name.span}_{version.span}-1_{arch}.deb".span);
write_whole(&at, made.bytes.span);
_ = management::remove_tree(&work);
return at;
}
# Writes an Arch package: its `.PKGINFO`, its `.MTREE` of each entry's
# digests, compressed by `gzip`, and the stage under the prefix, in a tar
# compressed by `zstd`.
def session::arch_package(&mut this, stage: &path, dist: &path, prefix: strview, platform: strview, mtime: i64): path {
val holder := &this.space.projects[0];
val name := distro_name(holder);
val version := distro_version(holder);
val arch := distro_arch(platform, "arch", "x86_64");
val items := staged(stage, prefix);
var size := 0u;
for &item in items {
continue if item.folder;
val found := io::info(&item.source) else (_) { continue; };
size += found.size;
}
var info := string::from("# Generated by blossom\n", nothing {});
info.append($"pkgname = {name.span}\npkgbase = {name.span}\nxdata = pkgtype=pkg\n".span);
info.append($"pkgver = {version.span}-1\n".span);
info.append($"pkgdesc = {or_else(holder.package.desc.span, holder.name.span)}\n".span);
if holder.package.url.length != 0 {
info.append($"url = {holder.package.url.span}\n".span);
}
info.append($"builddate = {mtime}\n".span);
info.append($"packager = {or_else(holder.package.auth.span, "Unknown Packager")}\n".span);
info.append($"size = {size}\narch = {arch}\n".span);
if holder.package.lic.length != 0 {
info.append($"license = {holder.package.lic.span}\n".span);
}
var tree := string::from("#mtree\n/set type=file uid=0 gid=0 mode=644\n", nothing {});
tree.append($"./.PKGINFO time={mtime}.0 size={info.length} md5digest={md5(info.span).span} sha256digest={sha256(info.span).span}\n".span);
for &item in items {
val named := mtree_escaped(item.name.span);
if item.folder {
tree.append($"./{named.span} time={mtime}.0 mode=755 type=dir\n".span);
continue;
}
val data := read_all(&item.source);
var mode := string::new(nothing {});
if item.mode != 0o644 {
mode.append(" mode=");
mode.append(octal_text(item.mode).span);
}
tree.append($"./{named.span} time={mtime}.0{mode.span} size={data.length} md5digest={md5(data.span).span} sha256digest={sha256(data.span).span}\n".span);
}
val work := dist.join("arch");
_ = management::remove_tree(&work);
_ = io::create_directories(&work);
val tree_at := work.join("mtree");
write_whole(&tree_at, tree.span);
val tree_gz := this.compressed(&tree_at, "gzip", ".gz");
var made := tar { bytes = string::new(nothing {}), mtime = mtime };
made.file(".PKGINFO", info.span, 0o644);
made.file(".MTREE", read_all(&tree_gz).span, 0o644);
add_items(&mut made, items.span, strview::blank());
val at := dist.join($"{name.span}-{version.span}-1-{arch}.pkg.tar".span);
write_whole(&at, made.finish());
_ = management::remove_tree(&work);
return this.compressed(&at, "zstd", ".zst");
}
# Builds an rpm package with `rpmbuild`, from a spec written for it that copies
# the stage under the prefix.
def session::rpm(&mut this, stage: &path, dist: &path, prefix: strview, platform: strview): path {
val holder := &this.space.projects[0];
val name := distro_name(holder);
val version := distro_version(holder);
val arch := distro_arch(platform, "rpm", "x86_64");
val summary := or_else(holder.package.desc.span, holder.name.span);
var spec := string::from("%define debug_package %{nil}\n", nothing {});
spec.append($"Name: {name.span}\nVersion: {version.span}\nRelease: 1\nSummary: {summary}\n".span);
spec.append($"License: {or_else(holder.package.lic.span, "Unspecified")}\n".span);
if holder.package.url.length != 0 {
spec.append($"URL: {holder.package.url.span}\n".span);
}
spec.append($"BuildArch: {arch}\n\n%description\n{summary}\n\n%install\n".span);
spec.append("mkdir -p \"%{buildroot}/");
spec.append(prefix);
spec.append("\"\ncp -a \"");
spec.append(stage.span);
spec.append("/.\" \"%{buildroot}/");
spec.append(prefix);
spec.append("/\"\n\n%files\n%defattr(-,root,root,-)\n");
val items := staged(stage, prefix);
for &item in items {
continue if item.folder;
spec.append($"\"/{item.name.span}\"\n".span);
}
val top := dist.join("rpmbuild");
val file := top.join("SPECS").join($"{name.span}.spec".span);
if !written(&file, spec.span) {
fatal(1, $"`{file.span}` can't be written.".span);
}
var words := vector::<string>::new();
words.append(string::from("rpmbuild", nothing {}));
words.append(string::from("-bb", nothing {}));
words.append(string::from("--define", nothing {}));
words.append($"_topdir {top.span}");
words.append(string::from(file.span, nothing {}));
var building := this.command(words.span, dist);
val status := building.run() else (_) {
fatal(1, $"rpm packages need `rpmbuild`, which isn't found; the spec is written to `{file.span}`.".span);
return path::new();
};
if !status.succeeded {
fatal(1, "`rpmbuild` failed.");
}
# `rpmbuild` puts the package in a folder of its architecture.
val built := top.join("RPMS").join(arch).join($"{name.span}-{version.span}-1.{arch}.rpm".span);
val at := dist.join($"{name.span}-{version.span}-1.{arch}.rpm".span);
if io::rename(&built, &at) is error(why) {
fatal(1, $"`{built.span}` can't be moved to `{at.span}`: {why}.".span);
}
return at;
}
# Adds entries to a tar archive, each name after a prefix, as `./`.
def add_items(made: &mut tar, items: span<entry>, before: strview): void {
for &item in items {
val name := $"{before}{item.name.span}";
if item.folder {
made.folder(name.span);
} else {
val data := read_all(&item.source);
made.file(name.span, data.span, item.mode);
}
}
}
# Compresses a file with a program of the system, `gzip`, `xz`, or `zstd`,
# which replaces it with one named with a suffix, as `.gz`, giving its path.
def session::compressed(&mut this, at: &path, program: strview, suffix: strview): path {
var words := vector::<string>::new();
words.append(string::from(program, nothing {}));
if program == "gzip" {
words.append(string::from("-n", nothing {}));
words.append(string::from("-9", nothing {}));
} else if program == "zstd" {
words.append(string::from("-q", nothing {}));
words.append(string::from("--rm", nothing {}));
words.append(string::from("-19", nothing {}));
}
words.append(string::from("-f", nothing {}));
words.append(string::from(at.span, nothing {}));
val folder := at.parent() else { return path::new(); };
var compressing := this.command(words.span, &folder);
val status := compressing.run() else (why) {
fatal(1, $"`{program}` can't be run, to compress `{at.span}`: {why}.".span);
return path::new();
};
if !status.succeeded {
fatal(1, $"`{program}` failed to compress `{at.span}`.".span);
}
return path::parse($"{at.span}{suffix}".span) else (_) { return path::new(); };
}
# When a package's entries were written: `SOURCE_DATE_EPOCH`, where it's set,
# else now.
def build_time(): i64 {
if process::variable("SOURCE_DATE_EPOCH") is some(given) {
if integer::parse::<i64>(given) is value(seconds) {
return seconds;
}
}
return time::timestamp::now().unix;
}
# The project's name as a system's package names it: in lower case, with `-`
# for `_`, two or more letters, digits, `.`, `+`, or `-`, starting with a
# letter or digit.
def distro_name(holder: &models::project): string {
var made := holder.name.lower();
for k in 0..made.length {
if made[k] == '_' {
made[k] = '-';
}
}
var fits := made.length >= 2 && made[0].is_alnum;
for k in 0..made.length {
val byte := made[k];
fits = fits && (byte.is_alnum || byte == '.' || byte == '+' || byte == '-');
}
if !fits {
fatal(2, $"`{holder.name.span}` can't name a system's package: it needs two or more letters, digits, `.`, `+`, or `-`.".span);
}
return made;
}
# The project's version as a system's package takes it: starting with a digit,
# with only letters, digits, `.`, `+`, or `~`.
def distro_version(holder: &models::project): string {
val text := holder.semv.span;
var fits := text.length != 0 && text[0].is_digit;
for k in 0..text.length {
val byte := text[k];
fits = fits && (byte.is_alnum || byte == '.' || byte == '+' || byte == '~');
}
if !fits {
fatal(2, $"{holder.identity.span}'s version, `{text}`, can't be a system package's: it starts with a digit, and holds only letters, digits, `.`, `+`, or `~`.".span);
}
return string::from(text, nothing {});
}
# The architecture a system's packages name x86-64 by, where they're for Linux.
def distro_arch(platform: strview, format: strview, name: strview): strview {
if platform != "linux-x86_64" {
fatal(2, $"{format} packages are for Linux, not `{platform}`.".span);
}
return name;
}
# A path in `.MTREE`, each byte but letters, digits, and `._/+-` written as `\`
# and three octal digits.
def mtree_escaped(text: strview): string {
var made := string::new(nothing {});
for k in 0..text.length {
val byte := text[k];
if byte.is_alnum || byte == '.' || byte == '_' || byte == '/' || byte == '+' || byte == '-' {
made.push(byte);
} else {
made.push('\\');
made.push('0' + (byte >> 6));
made.push('0' + ((byte >> 3) & 7));
made.push('0' + (byte & 7));
}
}
return made;
}
# A mode in octal, as `755`.
def octal_text(mode: u32): string {
var made := string::new(nothing {});
made.push('0' + ((mode >> 6) & 7) as u8);
made.push('0' + ((mode >> 3) & 7) as u8);
made.push('0' + (mode & 7) as u8);
return made;
}
# Text, or another where it's empty.
def or_else(text: strview, fallback: strview): strview {
return text.length != 0 ? text : fallback;
}
# The whole of a file, stopping the command where it can't be read.
def read_all(at: &path): string {
return io::read_file(at) else (why) {
fatal(1, $"`{at.span}` can't be read: {why}.".span);
return string::new(nothing {});
};
}
# Writes a file whole, stopping the command where it can't be written.
def write_whole(at: &path, bytes: strview): void {
if !written(at, bytes) {
fatal(1, $"`{at.span}` can't be written.".span);
}
}
# A prefix as a package holds it: without the `/` it starts or ends with.
def trimmed(text: strview): strview {
var start := 0u;
var end := text.length;
while start < end && text[start] == '/' {
start++;
}
while end > start && text[end - 1] == '/' {
end--;
}
return text.substr(start, end - start);
}
+230
View File
@@ -0,0 +1,230 @@
#! @file session.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the session a command runs in: the workspace, the `sakura` it runs
#! and what it's given, the steps counted and said as they're done, and what
#! decides a step is done already: the command that made its output, kept
#! beside it, and the files `sakura` said it read, through `--deps`, none newer
#! than the output.
import std::io;
import std::process;
import system;
import blossom::models;
import blossom::management;
module blossom::pipeline;
#! What a command runs with, and how its steps went.
pub struct session {
pub var space: management::workspace;
pub var sakura: string; #! The `sakura` run, absolute.
pub var std: string; #! The standard library it's given, or empty for the one it finds.
pub var threads: string; #! What `-j` says, or empty.
pub var step: u64; #! The step being done, counted from 1.
pub var steps: u64; #! How many there are.
pub var failed: bool; #! Whether a step failed.
}
#! Says a step is done, as `[2/3] Built hello`.
#! @param this The session.
#! @param what The step, as `Built`.
#! @param name The target's name.
#! @param more What follows, in parentheses, or empty.
pub def session::said(&mut this, what: strview, name: strview, more: strview = ""): void {
this.step++;
if more.length != 0 {
io::println($"[{this.step}/{this.steps}] {what} {name} ({more})".span);
} else {
io::println($"[{this.step}/{this.steps}] {what} {name}".span);
}
}
#! Says a step failed, as `Failed hello`, and notes it, which the command's
#! status says.
#! @param this The session.
#! @param name The target's name.
pub def session::fail(&mut this, name: strview): void {
this.step++;
this.failed = true;
io::println($"Failed {name}".span);
}
#! Says a step is skipped, as `Skipped hello`, since one it needs failed.
#! @param this The session.
#! @param name The target's name.
pub def session::skip(&mut this, name: strview): void {
this.step++;
io::println($"Skipped {name}".span);
}
#! The words starting a `sakura` command: the program, the command, and the
#! standard library where the config names one, as `--lib std=DIR`.
#! @param this The session.
#! @param command `check`, `run`, or `build`.
#! @returns The words.
pub def session::words(&this, command: strview): vector<string> {
var made := vector::<string>::new();
made.append(string::copy_of(&this.sakura));
made.append(string::from(command, nothing {}));
if this.std.length != 0 {
made.append(string::from("--lib", nothing {}));
made.append($"std={this.std}");
}
return made;
}
#! Adds `-j N` where the command was given it.
#! @param this The session.
#! @param words The words to add to.
pub def session::add_threads(&this, words: &mut vector<string>): void {
if this.threads.length != 0 {
words.append(string::from("-j", nothing {}));
words.append(string::copy_of(&this.threads));
}
}
#! Runs a command in a project's folder, its output and error going where
#! blossom's go, printing it first where `-v` asks.
#! @param this The session.
#! @param words The program, then its arguments.
#! @param cwd The folder it runs in.
#! @returns How it stopped, or why it couldn't start.
pub def session::run(&mut this, words: span<string>, cwd: &path): result<process::status, io_error> {
var made := this.command(words, cwd);
return made.run();
}
#! A command, ready to run in a project's folder, with `SAKURA` set to the
#! `sakura` blossom runs, so what it runs can run `sakura` as blossom does,
#! printed first where `-v` asks.
#! @param this The session.
#! @param words The program, then its arguments.
#! @param cwd The folder it runs in.
#! @returns The command.
pub def session::command(&mut this, words: span<string>, cwd: &path): process::command {
if this.space.verbose {
io::println(spoken(words).span);
}
var made := process::command::new(words[0].span);
for k in 1..words.length {
made.argument(words[k].span);
}
made.directory(cwd);
made.set_variable("SAKURA", this.sakura.span);
return made;
}
#! A command as a shell would take it, each word quoted where it holds what a
#! shell reads apart.
#! @param words The words.
#! @returns The line.
pub def spoken(words: span<string>): string {
var made := string::new(nothing {});
for &each in words {
if made.length != 0 {
made.push(' ');
}
var plain := each.length != 0;
for k in 0..each.length {
val byte := each[k];
plain = plain && (byte.is_alnum || byte == '/' || byte == '.' || byte == '-' || byte == '_' || byte == '=' || byte == ':' || byte == '+' || byte == ',' || byte == '@');
}
if plain {
made.append(each.span);
continue;
}
made.push('\'');
for k in 0..each.length {
if each[k] == '\'' {
made.append("'\\''");
} else {
made.push(each[k]);
}
}
made.push('\'');
}
return made;
}
#! What's kept beside an output to say how it was made: the `sakura` that made
#! it, when that executable was written, and the command's words, a line each.
#! @param this The session.
#! @param words The command.
#! @returns The text.
pub def session::made_by(&this, words: span<string>): string {
var made := string::copy_of(&this.sakura);
var written: i64 = 0;
if path::parse(this.sakura.span) is value(&at) {
if io::info(&at) is value(&found) {
written = found.modified;
}
}
made.append($"\n{written}".span);
for &each in words {
made.push('\n');
made.append(each.span);
}
made.push('\n');
return made;
}
#! Whether an output is up to date: it's there, the command kept beside it is
#! the one that would make it now, and no file `sakura` read making it, nor the
#! blossomfile, nor a member's, is newer than it.
#! @param output The output, as an executable or a stamp.
#! @param kept The command kept beside it.
#! @param now The command that would make it now, as `made_by` gives it.
#! @param deps The files `sakura` read, as `--deps` wrote them, relative to
#! the project's folder where they're not absolute.
#! @param holder The project.
#! @returns Whether it is.
pub def is_fresh(output: &path, kept: &path, now: strview, deps: &path, holder: &models::project): bool {
val made := io::info(output) else (_) { return false; };
val before := io::read_file(kept) else (_) { return false; };
return false if before.span != now;
val read := io::read_file(deps) else (_) { return false; };
return false if newer(&holder.file, made.modified);
for &each in holder.members {
return false if newer(&each.file, made.modified);
}
for line in read.span.lines() {
continue if line.length == 0;
val named := path::parse(line) else (_) { return false; };
val file := holder.folder.join(&named);
return false if newer(&file, made.modified);
}
return true;
}
# Whether a file was written after a time, or isn't there to say.
def newer(at: &path, than: i64): bool {
val found := io::info(at) else (_) { return true; };
return found.modified > than;
}
#! Writes a file, making the folders above it first.
#! @param at The file.
#! @param text What it holds.
#! @returns Whether it was written.
pub def written(at: &path, text: strview): bool {
if at.parent() is some(&above) {
_ = io::create_directories(above);
}
return io::write_file(at, text) is value;
}
#! A status as the code a program exits with: its own where it exited, and
#! 128 and the signal's number where a signal stopped it, as shells give it.
#! @param status How it stopped.
#! @returns The code.
pub def exit_code(status: &process::status): i32 {
if status is exited(code) {
return code;
}
if status is signaled(signal) {
return 128 + signal;
}
return 1;
}
+526
View File
@@ -0,0 +1,526 @@
#! @file steps.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the steps of `check`, `build`, `test`, and `run`: a library checked,
#! a program built, a test run, and a program run on the machine, each one
#! `sakura` command run in the project's folder, with `--lib` for every library
#! its `deps` reach.
import std::io;
import std::process;
import system;
import blossom::models;
import blossom::management;
module blossom::pipeline;
# Bytes read at a time from a test's output, which is passed on as it comes.
const passing_bytes: u64 = 4096;
#! Checks the project's libraries, then builds its programs, each where it
#! isn't up to date, and, for `test`, runs its suites after, the project's
#! `tests`.
#! @param this The session.
#! @param tests Whether the suites are run, as `test` asks.
#! @param suite Text a suite's name holds to be run, as `--suite` gives it, or
#! empty for every suite.
#! @param test Text a test's name holds to be run, as `--test` gives it,
#! which each suite is given as `--only TEXT`, or empty for every
#! test.
pub def session::build(&mut this, tests: bool, suite: strview = "", test: strview = ""): void {
val root := &this.space.projects[0];
val whose := this.whose();
var chosen := vector::<u64>::new();
if tests {
for k in 0..root.tests.length {
continue if !this.space.takes(&root.tests[k]);
if suite.length == 0 || root.tests[k].name.span.find(suite) is some {
chosen.append(k);
}
}
if chosen.length == 0 {
fatal(2, suite.length == 0 ? $"{whose.span} has no tests." : $"No suite of {whose.span} is named with `{suite}`.");
}
}
var taken: u64 = 0;
for &each in root.targets {
taken += this.space.takes(&each) ? 1 : 0;
}
this.steps = taken + chosen.length;
var broken := vector::<u64>::new(); # The libraries that failed to check.
for t in 0..root.targets.length {
continue if this.space.projects[0].targets[t].kind != models::target_kind::library;
continue if !this.space.takes(&this.space.projects[0].targets[t]);
if !this.check_library(t, true) {
val name := &this.space.projects[0].targets[t].name;
broken.append(this.space.library_named(name.span).some);
}
}
for t in 0..root.targets.length {
continue if this.space.projects[0].targets[t].kind != models::target_kind::program;
continue if !this.space.takes(&this.space.projects[0].targets[t]);
_ = this.build_program(t, false, &broken);
}
var none: u64 = 0; # The suites that said they ran no test.
for &k in chosen {
if this.run_test(k, &broken, test) is some(&count) && count == 0 {
none++;
}
}
# A test named in no suite run is a mistake in the command, as a suite named
# by none is.
if test.length != 0 && !this.failed && none == chosen.length {
fatal(2, $"No test of {whose.span} is named with `{test}`.");
}
}
# Who a command works on, as its mistakes name it: the project, as
# `malunal/hello@1.0.0`, or its member, as `engine of malunal/hello@1.0.0`.
def session::whose(&this): string {
val identity := this.space.projects[0].identity;
return string::copy_of(&identity) if this.space.member.length == 0;
return $"{this.space.member.span} of {identity.span}";
}
#! Checks every target of the project, its libraries and programs, writing
#! nothing; of its member alone, where it was run in a member's folder.
#! @param this The session.
pub def session::check(&mut this): void {
val count := this.space.projects[0].targets.length;
var taken: u64 = 0;
for t in 0..count {
taken += this.space.takes(&this.space.projects[0].targets[t]) ? 1 : 0;
}
this.steps = taken;
for t in 0..count {
continue if !this.space.takes(&this.space.projects[0].targets[t]);
if this.space.projects[0].targets[t].kind == models::target_kind::library {
_ = this.check_library(t, false);
} else {
_ = this.check_program(t);
}
}
}
#! Runs a program target on the machine, as `sakura run` does.
#! @param this The session.
#! @param name The target, or empty for the project's only program.
#! @param args What the program is given.
#! @returns The status it stopped with.
pub def session::run_program(&mut this, name: strview, args: span<strview>): i32 {
val root := &this.space.projects[0];
val whose := this.whose();
var chosen := root.targets.length;
for t in 0..root.targets.length {
continue if root.targets[t].kind != models::target_kind::program;
continue if !this.space.takes(&root.targets[t]);
if name.length == 0 {
if chosen != root.targets.length {
fatal(2, $"{whose.span} has more than one program: name the one to run.");
}
chosen = t;
} else if root.targets[t].name.span == name {
chosen = t;
}
}
if chosen == root.targets.length {
fatal(2, name.length == 0 ? $"{whose.span} has no program to run." : $"`{name}` is no program of {whose.span}.");
}
val each := &this.space.projects[0].targets[chosen];
var words := this.words("run");
this.add_libraries(each, &mut words);
this.add_threads(&mut words);
this.add_sources(each, &mut words);
if args.length != 0 {
words.append(string::from("--", nothing {}));
for &arg in args {
words.append(string::from(arg, nothing {}));
}
}
val status := this.run(words.span, &this.space.projects[0].folder) else (why) {
fatal(1, $"`{this.sakura.span}` can't be run: {why}.");
return 1;
};
return exit_code(&status);
}
# Checks a library: its files, with `--lib` for those it reads. Where `fresh` is
# asked, a stamp kept with the command and the files read says it's checked, so
# it's checked again only where those change.
def session::check_library(&mut this, t: u64, fresh: bool): bool {
val holder := &this.space.projects[0];
val each := &holder.targets[t];
var files := management::library_files(holder, each);
if files is error(&why) {
fatal(why.status, why.message.span);
}
var words := this.words("check");
this.add_libraries(each, &mut words);
this.add_threads(&mut words);
val base := $"{output_text(holder).span}/check/{each.name.span}";
if fresh {
words.append(string::from("--deps", nothing {}));
words.append($"{base.span}.deps");
}
if files is value(&listed) {
for &file in listed {
words.append(string::copy_of(file));
}
}
return this.made(t, words.span, fresh ? base.span : strview::blank(), "Checked", "");
}
# Checks a program, as `check` does, writing nothing.
def session::check_program(&mut this, t: u64): bool {
val each := &this.space.projects[0].targets[t];
var words := this.words("check");
this.add_libraries(each, &mut words);
val system := this.platform_of(each);
if system.length != 0 {
words.append(string::from("--target", nothing {}));
words.append(string::from(system, nothing {}));
}
this.add_threads(&mut words);
this.add_sources(each, &mut words);
return this.made(t, words.span, strview::blank(), "Checked", "");
}
# Builds a program, or a test that runs natively, into the output folder's
# `bin`, unless it's up to date, or a library of the project it reads failed.
def session::build_program(&mut this, t: u64, test: bool, broken: &vector<u64>): bool {
val holder := &this.space.projects[0];
val index := test ? holder.targets.length + t : t;
val each := &holder.at(index);
if this.reaches_broken(each, broken) {
this.skip(each.name.span);
return false;
}
val system := this.platform_of(each);
val output := $"{output_text(holder).span}/bin/{output_name(each.name.span, system).span}";
var words := this.words("build");
this.add_libraries(each, &mut words);
words.append($"-O{each.level}");
if each.petal {
words.append(string::from("-g", nothing {}));
}
if system.length != 0 {
words.append(string::from("--target", nothing {}));
words.append(string::from(system, nothing {}));
}
if test && each.checks {
words.append(string::from("--checks", nothing {}));
}
this.add_threads(&mut words);
if each.shown && for_windows(system) {
add_shown(each, holder.semv.span, &mut words);
}
for &opt in each.opts {
words.append(string::copy_of(opt));
}
words.append(string::from("--deps", nothing {}));
words.append($"{output.span}.deps");
words.append(string::from("-o", nothing {}));
words.append(string::copy_of(&output));
this.add_sources(each, &mut words);
return this.made(index, words.span, output.span, test ? "" : "Built", output.span);
}
# Runs a command that checks or builds a target, unless its output, where it
# has one, is up to date, and says how it went. A test built is said by its
# run, so its build is said only where it fails.
def session::made(&mut this, index: u64, words: span<string>, output: strview, verb: strview, more: strview): bool {
val holder := &this.space.projects[0];
val name := &holder.at(index).name;
val now := this.made_by(words);
if output.length != 0 {
val out := holder.folder.join(output);
val kept := holder.folder.join($"{output}.command".span);
val deps := holder.folder.join($"{output}.deps".span);
if is_fresh(&out, &kept, now.span, &deps, holder) {
if verb.length != 0 {
this.said("Up to date", name.span);
}
return true;
}
_ = io::remove(&kept);
if out.parent() is some(&above) {
_ = io::create_directories(above);
}
}
val status := this.run(words, &holder.folder) else (why) {
fatal(1, $"`{this.sakura.span}` can't be run: {why}.");
return false;
};
if !status.succeeded {
this.fail(name.span);
return false;
}
if output.length != 0 {
val kept := holder.folder.join($"{output}.command".span);
if verb == "Checked" {
_ = written(&holder.folder.join(output), "");
}
_ = written(&kept, now.span);
}
if verb.length != 0 {
this.said(verb, name.span, more);
}
return true;
}
# Runs a suite, a test of the project's: on the machine, as `sakura run`, with
# `--checks` unless it says otherwise, or built, then run, given its `args`, then
# `--only TEXT` where `--test` names its tests, which, coming last, `std::testing`
# takes over any `--only` of its `args`. What it writes is passed on as it comes,
# and the count its last line gives, as `14 passed`, is said with it. It gives
# how many tests ran, of the counts its last line gives, where the suite ran and
# gave them.
def session::run_test(&mut this, k: u64, broken: &vector<u64>, test: strview): maybe<u64> {
val holder := &this.space.projects[0];
val each := &holder.tests[k];
var words := vector::<string>::new();
if each.runs == models::runner::native {
return nothing {} if !this.build_program(k, true, broken);
val output := $"{output_text(holder).span}/bin/{output_name(each.name.span, this.platform_of(each)).span}";
words.append(string::from(holder.folder.join(output.span).span, nothing {}));
for &arg in each.args {
words.append(string::copy_of(arg));
}
add_test(test, &mut words);
} else {
if this.reaches_broken(each, broken) {
this.skip(each.name.span);
return nothing {};
}
words = this.words("run");
this.add_libraries(each, &mut words);
if each.checks {
words.append(string::from("--checks", nothing {}));
}
this.add_threads(&mut words);
this.add_sources(each, &mut words);
if each.args.length != 0 || test.length != 0 {
words.append(string::from("--", nothing {}));
for &arg in each.args {
words.append(string::copy_of(arg));
}
add_test(test, &mut words);
}
}
var running := this.command(words.span, &holder.folder);
running.output(process::stdio::piped);
var child := running.spawn() else (why) {
fatal(1, $"`{words[0].span}` can't be run: {why}.");
return nothing {};
};
# The output is passed on as it comes, keeping its last line.
var last := string::new(nothing {});
var chunk: u8[passing_bytes];
val into := slice::<u8>::over((&mut chunk) as *mut u8, passing_bytes);
while true {
val count := child.output().read(into) else (_) { break; };
break if count == 0;
val text := strview::over((&chunk) as *u8, count);
_ = system::fd::stdout.put(text);
last.append(text);
if last.length > 1024 {
val keep := last.span.substr(last.length - 512, 512);
last = string::from(keep, nothing {});
}
}
val status := child.wait() else (why) {
fatal(1, $"`{words[0].span}` couldn't be waited for: {why}.");
return nothing {};
};
if !status.succeeded {
this.fail(each.name.span);
return nothing {};
}
val ran := ran_of(last.span);
if test.length != 0 && ran is some(&count) && count == 0 {
this.said("Tested", each.name.span, $"none named with `{test}`".span);
} else {
this.said("Tested", each.name.span, tally_of(last.span));
}
return ran;
}
# Adds `--only TEXT`, where `--test` gives the text.
def add_test(test: strview, words: &mut vector<string>): void {
return if test.length == 0;
words.append(string::from("--only", nothing {}));
words.append(string::from(test, nothing {}));
}
# A test's last line, without the line's end.
def last_line(text: strview): strview {
var end := text.length;
while end > 0 && (text[end - 1] == '\n' || text[end - 1] == '\r') {
end--;
}
var start := end;
while start > 0 && text[start - 1] != '\n' {
start--;
}
return text.substr(start, end - start);
}
# The count a test's last line gives, as `14 passed` of `14 passed, 0 failed,
# 0 skipped`, or empty where it gives none.
def tally_of(text: strview): strview {
val line := last_line(text);
val comma := line.find(",") else { return strview::blank(); };
val first := line.substr(0, comma);
return first.ends_with(" passed") ? first : strview::blank();
}
# How many tests a suite ran, of the counts its last line gives, as `std::testing`
# writes them, `14 passed, 1 failed, 2 skipped`, or none where it gives none.
def ran_of(text: strview): maybe<u64> {
var total: u64 = 0;
var counts: u64 = 0;
var at: u64 = 0;
val line := last_line(text);
for word in ["passed", "failed", "skipped"] {
var number: u64 = 0;
var digits: u64 = 0;
while at < line.length && line[at] >= '0' && line[at] <= '9' {
number = number * 10 + (line[at] - '0') as u64;
digits++;
at++;
}
return nothing {} if digits == 0;
val rest := line.substr(at, line.length - at);
return nothing {} if !rest.starts_with($" {word}".span);
at += word.length + 1;
if counts < 2 {
return nothing {} if !line.substr(at, line.length - at).starts_with(", ");
at += 2;
}
total += number;
counts++;
}
return nothing {} if at != line.length;
return total;
}
# Adds `--lib` for every library a target's `deps` reach.
def session::add_libraries(&mut this, each: &models::target, words: &mut vector<string>): void {
var reached := vector::<u64>::new();
var found := this.space.reach(0, each.deps.span, each.name.span, &mut reached);
if found is error(&why) {
fatal(why.status, why.message.span);
}
for &library in reached {
words.append(string::from("--lib", nothing {}));
words.append(this.space.lib_option(library, 0));
}
}
# Adds a target's files, as its `srcs` give them.
def session::add_sources(&mut this, each: &models::target, words: &mut vector<string>): void {
var files := management::sources_of(&this.space.projects[0], each);
if files is error(&why) {
fatal(why.status, why.message.span);
}
if files is value(&mut listed) {
for &mut file in listed {
words.append(move(file));
}
}
}
# Whether a target reads a library of the project that failed to check.
def session::reaches_broken(&mut this, each: &models::target, broken: &vector<u64>): bool {
return false if broken.length == 0;
var reached := vector::<u64>::new();
_ = this.space.reach(0, each.deps.span, each.name.span, &mut reached);
for &library in reached {
for &failed in broken {
return true if library == failed;
}
}
return false;
}
# What a target is built for: what `--target` says, else its own `target`,
# else nothing, for the system blossom runs on.
def session::platform_of(&this, each: &models::target): strview {
if this.space.platform.length != 0 {
return this.space.platform.span;
}
return each.system.span;
}
#! Whether a program is built for Windows: it says so, or it says nothing and
#! blossom runs there.
#! @param platform What it's built for, or empty.
#! @returns Whether it is.
pub def for_windows(platform: strview): bool {
return true if platform == "windows-x86_64";
when os == windows {
return platform.length == 0;
}
return false;
}
# Gives `sakura build` what a program for Windows is shown by, where it gives
# any of it: its version, as the project's, its title, each of its icons' PNG
# and icon files, which an SVG isn't, and whether it's windowed. A program
# giving none is built as ever. A program for Linux is shown by what `install`
# puts beside it.
def add_shown(each: &models::target, semv: strview, words: &mut vector<string>): void {
words.append(string::from("--semv", nothing {}));
words.append(string::from(semv, nothing {}));
if each.title.length != 0 {
words.append(string::from("--title", nothing {}));
words.append(string::copy_of(&each.title));
}
for &file in each.icons {
continue if models::ends_with_any_case(file.span, ".svg");
words.append(string::from("--icon", nothing {}));
words.append(string::copy_of(&file));
}
if each.windowed {
words.append(string::from("--windowed", nothing {}));
}
}
#! The file a program is built into: its name, with `.exe` where it's for
#! Windows, or blossom runs there and it's built for the system blossom runs on.
#! @param name The program's name.
#! @param platform What it's built for, or empty.
#! @returns The file's name.
pub def output_name(name: strview, platform: strview): string {
if platform == "windows-x86_64" {
return $"{name}.exe";
}
if platform.length == 0 {
return management::program_file(name);
}
return string::from(name, nothing {});
}
#! A project's output folder, relative to its own: `.blossom/` and its key.
#! @param holder The project.
#! @returns The folder, written with `/`.
pub def output_text(holder: &models::project): string {
return $".blossom/{holder.key.span}";
}
#! Says why the command can't go on, and stops it with a status.
#! @param status 1 where something failed, and 2 where a blossomfile or the
#! command is wrong.
#! @param message What's wrong.
pub def fatal(status: i32, message: strview): void {
_ = system::fd::stderr.put($"blossom: {message}\n".span);
system::exit(status);
}
+181
View File
@@ -0,0 +1,181 @@
# Tests of `build`, `check`, `run`, and `clean`: a program, a program with a
# library of its own, the `sakurac` run where the config names none, building
# only what changed, a check that fails, and building for Windows.
import std::io;
import std::process;
import std::testing;
@test def a_program_is_built_then_run(t: &mut tester, box: sandbox): void {
box.write("one/blossomfile", """
name: one
gpid: tests
semv: 0.1.0
targets:
- name: one
type: program
srcs: [main.sakura]
""");
box.write("one/main.sakura", """
import std::io;
def main(args: span<strview>): void {
io::println($"given {args.length}".span);
}
""");
val built := box.blossom("one", ["build"]);
t.expects(built.status == 0, built.error.span);
t.expects(built.says("[1/1] Built one (.blossom/") && built.says("Built tests/one@0.1.0"));
# The executable is where blossom said.
val output := built_path(built.output.span, "one");
val ran := box.run($"{box.at.span}/one/{output}".span, "one", ["a", "b"]);
t.expects(ran.says("given 2"));
val again := box.blossom("one", ["run", "--", "x", "y", "z"]);
t.expects(again.status == 0 && again.says("given 3"));
}
@test def a_program_reads_a_library_of_its_project(t: &mut tester, box: sandbox): void {
box.hello("hello");
val built := box.blossom("hello", ["build"]);
t.expects(built.status == 0, built.error.span);
t.expects(built.says("[1/2] Checked hello.geometry") && built.says("[2/2] Built hello"));
val ran := box.blossom("hello", ["run", "--", "1"]);
t.expects(ran.says("area 12 cube 8 given 1"));
# `check` checks each target and writes nothing.
box.hello("other");
val checked := box.blossom("other", ["check"]);
t.expects(checked.status == 0 && checked.says("[1/2] Checked hello") && checked.says("[2/2] Checked hello.geometry"));
t.expects(!box.has("other/.blossom"));
}
# Where the config names no `sakura`, blossom runs the first `sakurac` on
# `PATH`, here a link to the tests' own, as none is beside it. Windows links
# only for those allowed to, and a copy finds no `core` beside it, so there
# `PATH` names the folder of the tests' own, where it's a `sakurac`.
@test def a_config_naming_no_sakura_runs_sakurac(t: &mut tester, box: sandbox): void {
val sakura := process::variable("SAKURA") else { return; };
box.write("config/blossom/config", std_line().span);
box.hello("hello");
val missing := box.blossom("hello", ["build"], box.search_path().span);
t.expects(missing.status == 2 && missing.warns("No `sakurac` is found"), missing.error.span);
var found := string::new(nothing {});
when os == windows {
val named := path::parse(sakura) else (_) { return; };
return if !named.span.ends_with("sakurac.exe");
val folder := named.parent() else { return; };
found = $"{folder.span};{system_programs()}";
}
else {
box.write("bin/.keep", "");
val linked := box.run("ln", "bin", ["-s", sakura, "sakurac"]);
t.expects(linked.status == 0, linked.error.span);
found = box.search_path("bin");
}
val built := box.blossom("hello", ["build"], found.span);
t.expects(built.status == 0 && built.says("[2/2] Built hello"), built.error.span);
}
@test def only_what_changed_is_built_again(t: &mut tester, box: sandbox): void {
box.hello("hello");
t.expects(box.blossom("hello", ["build"]).status == 0);
# Nothing changed: `sakura` isn't run.
val again := box.blossom("hello", ["build", "-v"]);
t.expects(again.says("[1/2] Up to date hello.geometry") && again.says("[2/2] Up to date hello"));
t.expects(!again.says("sakura"));
# A file of the library: it's checked again, and the program built again.
box.write("hello/hello.geometry/solids/solids.sakura", """
module hello::geometry::solids;
pub def cube(side: i64): i64 { return side * side * side + 0; }
""");
val touched := box.blossom("hello", ["build"]);
t.expects(touched.says("[1/2] Checked hello.geometry") && touched.says("[2/2] Built hello"));
# The program's own file: only it's built again.
box.write("hello/main.sakura", box.read("hello/main.sakura").span);
val program := box.blossom("hello", ["build"]);
t.expects(program.says("[1/2] Up to date hello.geometry") && program.says("[2/2] Built hello"));
# Another option value builds in a folder of its own, and the first stays up
# to date.
val other := box.blossom("hello", ["build", "-o", "level=0"]);
t.expects(other.says("[2/2] Built hello") && built_path(other.output.span, "hello") != built_path(program.output.span, "hello"));
t.expects(box.blossom("hello", ["build"]).says("[2/2] Up to date hello"));
# Changing the blossomfile builds again.
val text := box.read("hello/blossomfile");
box.write("hello/blossomfile", $"{text.span}\n".span);
t.expects(box.blossom("hello", ["build"]).says("[2/2] Built hello"));
# `clean` removes this option set's outputs, and `--all` every set's.
val cleaned := box.blossom("hello", ["clean"]);
t.expects(cleaned.status == 0 && cleaned.says("Cleaned tests/hello@1.0.0"));
t.expects(box.has("hello/.blossom") && box.blossom("hello", ["clean"]).says("Nothing to clean"));
t.expects(box.blossom("hello", ["clean", "--all"]).status == 0 && !box.has("hello/.blossom"));
}
@test def a_program_that_fails_to_check_fails_the_build(t: &mut tester, box: sandbox): void {
box.hello("hello");
box.write("hello/main.sakura", """
def main(): void {
val wrong: i64 = "text";
}
""");
val built := box.blossom("hello", ["build"]);
t.expects(built.status == 1 && built.says("Failed hello") && !built.says("Built tests/hello"));
t.expects(built.error.span.find("main.sakura:2") is some, built.error.span);
# A library that fails to check skips the programs reading it.
box.hello("broken");
box.write("broken/hello.geometry/shapes.sakura", """
module hello::geometry;
pub def area(w: i64, h: i64): i64 { return "no"; }
""");
val skipped := box.blossom("broken", ["build"]);
t.expects(skipped.status == 1 && skipped.says("Failed hello.geometry") && skipped.says("Skipped hello"));
# `check` checks every target, so the program fails there too.
val checked := box.blossom("broken", ["check"]);
t.expects(checked.status == 1 && checked.says("Failed hello\n") && checked.says("Failed hello.geometry\n"), checked.output.span);
}
# What a program for Windows is shown by is given to `sakura`, which holds it in
# the executable: its version, title, icon, and window, an SVG being Linux's.
@test def a_program_for_windows_is_built_with_its_icon_title_and_window(t: &mut tester, box: sandbox): void {
box.shown("shown");
val built := box.blossom("shown", ["build", "--target", "windows-x86_64", "-v"]);
t.expects(built.status == 0, built.error.span);
t.expects(built.says("--semv 2.1.0 --title 'Shown Off' --icon icons/shown.png --windowed"), built.output.span);
t.expects(!built.says("shown.svg"));
val output := built_path(built.output.span, "shown");
val exe := box.read($"shown/{output}".span);
val header := word_of(exe.span, 0x3C, 4);
t.expects(word_of(exe.span, header + 24 + 68, 2) == 2);
t.expects(word_of(exe.span, header + 24 + 112 + 16, 4) != 0);
# Given a console by its option, it's built again, in one.
val console := box.blossom("shown", ["build", "--target", "windows-x86_64", "-v", "-o", "windowed=false"]);
t.expects(console.status == 0 && !console.says("--windowed"), console.error.span);
val again := box.read($"shown/{built_path(console.output.span, "shown")}".span);
t.expects(word_of(again.span, word_of(again.span, 0x3C, 4) + 24 + 68, 2) == 3);
# Built for Linux, it's given none of it.
val linux := box.blossom("shown", ["build", "--target", "linux-x86_64", "-v"]);
t.expects(linux.status == 0 && !linux.says("--title") && !linux.says("--icon"), linux.error.span);
}
@test def a_target_builds_an_executable_for_windows(t: &mut tester, box: sandbox): void {
box.hello("hello");
val built := box.blossom("hello", ["build", "--target", "windows-x86_64"]);
t.expects(built.status == 0, built.error.span);
val output := built_path(built.output.span, "hello");
t.expects(output.ends_with("/bin/hello.exe"), output);
t.expects(box.read($"hello/{output}".span).span.starts_with("MZ"));
}
+150
View File
@@ -0,0 +1,150 @@
# Tests of `test`, `install`, and `package`: tests passing, failing, run
# natively, and suites and tests chosen by name; installing into a prefix and
# under a folder; and packages of tar and zip.
import std::io;
import std::testing;
@test def tests_run_and_say_how_many_passed(t: &mut tester, box: sandbox): void {
box.hello("hello");
val tested := box.blossom("hello", ["test"]);
t.expects(tested.status == 0 && tested.says("[3/3] Tested hello.tests (2 passed)") && tested.says("[ OK ] cubes_cube"), tested.error.span);
t.expects(tested.says("Tested tests/hello@1.0.0"));
}
@test def a_test_that_fails_fails_the_command(t: &mut tester, box: sandbox): void {
box.hello("hello");
box.write("hello/tests/wrong.sakura", """
import std::testing;
@test def nothing_is_something(t: &mut tester): void { t.expects(1 == 2); }
""");
val tested := box.blossom("hello", ["test"]);
t.expects(tested.status == 1 && tested.says("Failed hello.tests") && !tested.says("Tested tests/hello"));
}
@test def tests_run_natively_by_name_with_what_theyre_given(t: &mut tester, box: sandbox): void {
box.hello("hello", """
- name: given.tests
type: program
runs: native
srcs: [given/main.sakura]
args: ["${bin}", second]
""");
box.write("hello/given/main.sakura", """
import std::io;
import system;
def main(args: span<strview>): void {
io::println($"given {args[0]} {args[1]}".span);
exit(args[0].ends_with("bin") && args[1] == "second" ? 0 : 1);
}
""");
val tested := box.blossom("hello", ["test", "--suite", "given"]);
t.expects(tested.status == 0 && tested.says("[3/3] Tested given.tests") && !tested.says("hello.tests"), tested.output.span);
t.expects(tested.says($"given {box.path_of("hello/.blossom")}".span));
t.expects(box.blossom("hello", ["test", "--suite", "none"]).status == 2);
}
@test def tests_are_chosen_by_name_within_the_suites_run(t: &mut tester, box: sandbox): void {
box.hello("hello");
# Each suite is given `--only cubes`, so it runs that test alone.
val tested := box.blossom("hello", ["test", "--test", "cubes"]);
t.expects(tested.status == 0 && tested.says("[ OK ] cubes_cube") && !tested.says("areas_multiply"), tested.output.span);
t.expects(tested.says("[3/3] Tested hello.tests (1 passed)"), tested.output.span);
# Within the suites chosen.
val both := box.blossom("hello", ["test", "--suite", "hello", "--test", "areas"]);
t.expects(both.status == 0 && both.says("[ OK ] areas_multiply") && !both.says("cubes_cube"), both.output.span);
# A test named in no suite run is a mistake in the command, as a suite is.
val none := box.blossom("hello", ["test", "--test", "spheres"]);
t.expects(none.status == 2 && none.says("[3/3] Tested hello.tests (none named with `spheres`)"), none.output.span);
t.expects(none.error.span.find("No test of tests/hello@1.0.0 is named with `spheres`.") is some, none.error.span);
}
@test def install_puts_programs_libraries_and_steps_in_the_prefix(t: &mut tester, box: sandbox): void {
box.hello("hello", """
exports:
- hello.geometry
install:
- !include ./share
- !include ./docs:share/doc/hello
- !include ./notes.txt
- !include ./notes.txt:etc/hello.txt
""");
box.write("hello/share/data.txt", "data\n");
box.write("hello/docs/README.md", "# Hello\n");
box.write("hello/notes.txt", "notes\n");
val installed := box.blossom("hello", ["install", "--prefix", $"{box.at.span}/prefix".span]);
t.expects(installed.status == 0 && installed.says("Installed tests/hello@1.0.0 (7 files)"), installed.error.span);
val hello := program("hello");
t.expects(box.has($"prefix/bin/{hello}".span), hello.span);
for name in ["prefix/share/data.txt", "prefix/share/doc/hello/README.md", "prefix/notes.txt", "prefix/etc/hello.txt",
"prefix/share/sakura/hello.geometry/shapes.sakura", "prefix/share/sakura/hello.geometry/solids/solids.sakura"] {
t.expects(box.has(name), name);
}
val ran := box.run(box.path_of($"prefix/bin/{hello}".span).span, ".", span::<strview>::blank());
t.expects(ran.says("area 12"));
# Under a folder, as a package is staged.
val staged := box.blossom("hello", ["install", "--prefix", "/usr/local", "--destdir", box.path_of("stage").span]);
t.expects(staged.status == 0 && box.has($"stage/usr/local/bin/{hello}".span), staged.error.span);
}
# A program for Linux shown as a desktop's program is installed with its icons
# in the icon theme and its desktop entry; one for Windows holds them itself.
@test def install_puts_a_desktop_entry_and_icons_beside_a_program_for_linux(t: &mut tester, box: sandbox): void {
box.shown("shown");
val installed := box.blossom("shown", ["install", "--target", "linux-x86_64", "--prefix", $"{box.at.span}/prefix".span]);
t.expects(installed.status == 0 && installed.says("Installed tests/shown@2.1.0 (4 files)"), installed.error.span);
t.expects(box.has("prefix/bin/shown"));
t.expects(box.has("prefix/share/icons/hicolor/32x32/apps/shown.png"));
t.expects(box.has("prefix/share/icons/hicolor/scalable/apps/shown.svg"));
val entry := box.read("prefix/share/applications/shown.desktop");
t.expects(entry.span.starts_with("[Desktop Entry]\nType=Application\nName=Shown Off\nExec="), entry.span);
t.expects(entry.span.find("/prefix/bin/shown\nIcon=shown\nTerminal=false\nStartupWMClass=shown\n") is some, entry.span);
t.expects(entry.span.find("\\") is none);
# In a console, it runs in a terminal.
val console := box.blossom("shown", ["install", "--target", "linux-x86_64", "-o", "windowed=false", "--prefix", $"{box.at.span}/console".span]);
t.expects(console.status == 0 && box.read("console/share/applications/shown.desktop").span.find("Terminal=true\n") is some, console.error.span);
# A package names it where the package installs it.
val packaged := box.blossom("shown", ["package", "-f", "tar", "--target", "linux-x86_64"]);
t.expects(packaged.status == 0, packaged.error.span);
val dist := box.dist("shown");
val stage := $"{dist.span.substr(0, dist.length - 4)}stage/share/applications/shown.desktop";
val parsed := path::parse(stage.span) else (_) { return; };
val staged := io::read_file(&parsed) else (_) {
t.expects(false, stage.span);
return;
};
t.expects(staged.span.find("Exec=/usr/bin/shown\n") is some, staged.span);
# For Windows, nothing's put beside it.
val windows := box.blossom("shown", ["install", "--target", "windows-x86_64", "--prefix", $"{box.at.span}/windows".span]);
t.expects(windows.status == 0 && box.has("windows/bin/shown.exe") && !box.has("windows/share"), windows.error.span);
}
# A package for Linux, made on any system, compressed by the `gzip` on `PATH`.
@test def packages_hold_what_installing_puts_in_the_prefix(t: &mut tester, box: sandbox): void {
box.hello("hello", "install:\n- !include ./notes.txt\n");
box.write("hello/notes.txt", "notes\n");
val packaged := box.blossom("hello", ["package", "-f", "tar,zip", "--target", "linux-x86_64"]);
t.expects(packaged.status == 0 && packaged.says("hello-1.0.0-linux-x86_64.tar.gz") && packaged.says("hello-1.0.0-linux-x86_64.zip"), packaged.error.span);
val dist := box.dist("hello");
val tar := box.path_of($"{dist}/hello-1.0.0-linux-x86_64.tar.gz".span);
val listed := box.run("tar", "hello", ["-tzf", tar.span]);
t.expects(lines_of(listed.output.span) == "hello-1.0.0-linux-x86_64/\nhello-1.0.0-linux-x86_64/bin/\nhello-1.0.0-linux-x86_64/bin/hello\nhello-1.0.0-linux-x86_64/notes.txt\n", listed.output.span);
val zip := box.read($"{dist}/hello-1.0.0-linux-x86_64.zip".span);
t.expects(zip.span.starts_with("PK"));
# The same stage makes the same bytes.
val first := box.read(tar.span);
_ = box.blossom("hello", ["package", "-f", "tar,zip", "--target", "linux-x86_64"]);
t.expects(first.length != 0 && box.read(tar.span) == first && box.read($"{dist}/hello-1.0.0-linux-x86_64.zip".span) == zip);
# A system's package is refused for Windows before anything's built.
val windows := box.blossom("hello", ["package", "-f", "deb", "--target", "windows-x86_64"]);
t.expects(windows.status == 2 && windows.warns("deb packages are for Linux") && !windows.says("Built"));
}
+125
View File
@@ -0,0 +1,125 @@
# Tests of `libraries`, the `--lib` of each library a project holds or reads,
# its folder absolute, in the order found, which names what the store is missing
# rather than cloning it and refuses what a build refuses; and of `pull`, which
# clones what a project requires, or what's named, or with `--update` clones it
# again.
import std::io;
import std::testing;
@test def libraries_lists_what_a_project_holds_and_reads(t: &mut tester, box: sandbox): void {
# Its own library, then what that reads, from a requirement given options;
# and no `sakura` is needed, since none is run.
box.shapes("shapes");
box.write("app/blossomfile", """
name: app
gpid: tests
semv: 1.0.0
requires:
- remote: ../shapes
options:
flavor: fancy
targets:
- name: app
type: program
deps: [std, app.parts]
srcs: [main.sakura]
- name: app.parts
type: library
deps: [shapes.basic]
tests:
- name: app.tests
type: program
deps: [app.parts, shapes.basic]
""");
box.write("config/blossom/config", "");
val listed := box.blossom("app", ["libraries"], box.search_path().span);
val want := $"--lib app::parts={box.path_of("app/app.parts")}\n--lib shapes::basic={box.path_of("shapes/fancy")}\n";
t.expects(listed.status == 0 && listed.output == want, $"{listed.output.span}{listed.error.span}".span);
# Given another folder, it lists that project's.
val other := box.blossom(".", ["libraries", "shapes"], box.search_path().span);
t.expects(other.status == 0 && other.output == $"--lib shapes::basic={box.path_of("shapes/plain")}\n", other.output.span);
}
@test def libraries_refuses_what_a_build_refuses(t: &mut tester, box: sandbox): void {
box.shapes("hidden", false);
box.app("private", "- ../hidden");
val private := box.blossom("private", ["libraries"]);
t.expects(private.status == 2 && private.output.length == 0, private.output.span);
t.expects(private.warns("`shapes.basic`, which `app` reads, isn't exported by tests/shapes@1.0.0."), private.error.span);
}
# Writes a project holding a library, `colors.basic`, and makes a bare git
# repository of it, `colors.git`, as `remote` does.
def sandbox::colors(&this): bool {
this.write("colors/blossomfile", "name: colors\ngpid: tests\nsemv: 1.0.0\ntargets:\n- name: colors.basic\n type: library\nexports:\n- colors.basic\n");
this.write("colors/colors.basic/basic.sakura", "module colors::basic;\n\npub def hue(): strview { return \"red\"; }\n");
return this.remote("colors", "colors.git");
}
@test def libraries_names_what_the_store_is_missing_and_clones_nothing(t: &mut tester, box: sandbox): void {
box.shapes("source");
t.expects(box.remote("source", "shapes.git"));
val shapes := $"{box.url("shapes.git")}@v1.0.0";
box.app("app", $"- {shapes}".span);
val listed := box.blossom("app", ["libraries"]);
t.expects(listed.status == 0 && listed.output == $"--missing {shapes}\n", listed.output.span);
t.expects(listed.warns("1 requirement isn't in the store") && !listed.says("Cloning"), listed.error.span);
t.expects(box.stored("shapes@v1.0.0").length == 0);
}
@test def pull_clones_what_a_project_requires_or_what_is_named(t: &mut tester, box: sandbox): void {
box.shapes("source");
t.expects(box.remote("source", "shapes.git") && box.colors());
val shapes := $"{box.url("shapes.git")}@v1.0.0";
val colors := $"{box.url("colors.git")}@v1.0.0";
box.write("app/blossomfile", $"name: app\ngpid: tests\nsemv: 1.0.0\nrequires:\n- {shapes.span}\n- {colors.span}\ntargets:\n- name: app.parts\n type: library\n deps: [shapes.basic, colors.basic]\n".span);
# One named by the last part of its path.
val one := box.blossom("app", ["pull", "shapes"]);
val stored := box.stored("shapes@v1.0.0");
t.expects(one.status == 0 && stored.length != 0 && one.says($"[1/1] Cloned {shapes.span} ({stored})".span), $"{one.output.span}{one.error.span}".span);
t.expects(box.stored("colors@v1.0.0").length == 0);
val plain := box.path_of($"{stored}/plain".span);
val listed := box.blossom("app", ["libraries"]);
t.expects(listed.output == $"--lib app::parts={box.path_of("app/app.parts")}\n--lib shapes::basic={plain}\n--missing {colors.span}\n", listed.output.span);
# Everything, what's there already said to be.
val all := box.blossom("app", ["pull"]);
t.expects(all.status == 0 && all.says($"[1/2] Present {shapes.span}".span) && all.says($"[2/2] Cloned {colors.span}".span), all.output.span);
t.expects(all.says("Pulled what tests/app@1.0.0 requires"));
t.expects(box.blossom("app", ["libraries"]).output.span.find("--missing") is none);
# A name of nothing it requires.
val none := box.blossom("app", ["pull", "sizes"]);
t.expects(none.status == 2 && none.warns($"`sizes` is no requirement of tests/app@1.0.0: it requires `{shapes.span}`, `{colors.span}`.".span), none.error.span);
}
@test def pull_update_clones_a_branch_that_moved_again(t: &mut tester, box: sandbox): void {
box.shapes("source");
t.expects(box.remote("source", "shapes.git"));
box.app("app", $"- {box.url("shapes.git")}".span);
t.expects(box.blossom("app", ["pull"]).says("Cloned"));
val stored := box.stored("shapes@main");
t.expects(stored.length != 0);
# The branch moves; a pull leaves the store's clone as it is.
box.write("source/plain/basic.sakura", "module shapes::basic;\n\npub def side(): strview { return \"moved\"; }\n");
val bare := box.path_of("shapes.git");
t.expects(box.git("source", ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-am", "two"])
&& box.git("source", ["push", "-q", bare.span, "main"]));
t.expects(box.blossom("app", ["pull"]).says("Present"));
t.expects(box.read($"{stored.span}/plain/basic.sakura".span).span.find("plain") is some);
# With `--update`, it's cloned again, and nothing is left beside it.
val updated := box.blossom("app", ["pull", "--update"]);
t.expects(updated.status == 0 && updated.says("again") && updated.says("[1/1] Updated"), $"{updated.output.span}{updated.error.span}".span);
t.expects(box.read($"{stored.span}/plain/basic.sakura".span).span.find("moved") is some);
t.expects(!box.has($"{stored.span}.old".span) && !box.has($"{stored.span}.partial".span));
val ran := box.blossom("app", ["run"]);
t.expects(ran.status == 0 && ran.says("side moved"), ran.error.span);
}
+45
View File
@@ -0,0 +1,45 @@
# Runs blossom's tests of its commands. Each makes projects in a folder of its
# own, runs the blossom it's given first on them, and compares what it says and
# what it makes with what's expected. blossom's config in that folder names the
# `sakura` that `SAKURA` names, where it's set, as `blossom test` sets it, and
# as its `std` the standard library blossom's own project reads, as `blossom
# libraries` lists it run where the tests are, so they don't depend on a std
# found beside that `sakura`:
#
# blossom test --suite blossom.commands
#
# with `--test TEXT` to run those whose names hold the text; or, from the root
# of the repository, with a blossom built:
#
# SAKURA=SAKURA sakura run tests/commands/*.sakura -- BLOSSOM
#
# Add `--only TEXT` after BLOSSOM to run those whose name holds the text, and
# `--here` to run them in one program, as a debugger wants. Each test's folder
# is in the system's temporary folder, and blossom's config and store are the
# folder's, on Linux and on Windows alike. They run `git` and `tar`, and blossom
# runs `gzip` to package, each found on `PATH`.
import std::io;
import std::process;
import system;
import std::testing;
def main(args: span<strview>): void {
if args.length == 0 || args[0].starts_with("-") {
io::println("blossom's tests are given the blossom they run first, as `-- .blossom/KEY/bin/blossom`.");
exit(2);
}
if process::variable("SAKURA") is none {
io::println("blossom's tests run the `sakura` that `SAKURA` names, as `blossom test` sets it.");
exit(2);
}
blossom_at = args[0];
var listing := process::command::new(blossom_at);
listing.arguments(["libraries"]);
val listed := listing.capture() else (why) {
io::println($"blossom's tests can't run `{blossom_at} libraries`: {why}".span);
exit(2);
return;
};
std_at = std_folder(listed.output.span);
exit(tester::run(args));
}
+203
View File
@@ -0,0 +1,203 @@
# Tests of members: folders of a project holding blossomfiles of their own,
# which say whose members they are, read as one project with it, from its
# folder or a member's; a library's files, but its member's tests'; members
# that say nothing, or another project, or that no project lists; what a member
# requires, from its own folder; and a project requiring one of members.
import std::io;
import std::testing;
# Writes a project, `shop`, of two members: `shapes`, a library, `shop.shapes`,
# whose folder is the member's own, and its tests beside it in `tests`; and
# `app`, a program reading it.
def sandbox::shop(&this, folder: strview): void {
this.write($"{folder}/blossomfile".span, """
name: shop
gpid: tests
semv: 1.0.0
members:
- shapes
- ./app/
exports:
- shop.shapes
""");
this.write($"{folder}/shapes/blossomfile".span, """
member: shop
targets:
- name: shop.shapes
type: library
root: .
tests:
- name: shop.shapes.tests
type: program
deps: [shop.shapes]
""");
this.write($"{folder}/shapes/area.sakura".span, """
module shop::shapes;
pub def area(w: i64, h: i64): i64 { return w * h; }
""");
this.write($"{folder}/shapes/tests/main.sakura".span, """
import system;
import std::testing;
import shop::shapes;
def main(args: span<strview>): void { exit(tester::run(args)); }
@test def areas_multiply(t: &mut tester): void { t.expects(shapes::area(2, 5) == 10); }
""");
this.write($"{folder}/app/blossomfile".span, """
member: shop
targets:
- name: shop
type: program
deps: [std, shop.shapes]
srcs: [main.sakura]
""");
this.write($"{folder}/app/main.sakura".span, """
import std::io;
import shop::shapes;
def main(args: span<strview>): void {
io::println($"area {shapes::area(3, 4)}".span);
}
""");
}
@test def members_are_built_and_tested_as_one_project(t: &mut tester, box: sandbox): void {
box.shop("shop");
val tested := box.blossom("shop", ["test"]);
t.expects(tested.status == 0 && tested.says("[1/3] Checked shop.shapes") && tested.says("Built shop"), tested.output.span);
t.expects(tested.says("[3/3] Tested shop.shapes.tests (1 passed)") && tested.says("Tested tests/shop@1.0.0"), tested.output.span);
# The library's files are its member's, but those its tests list.
val checked := box.blossom("shop", ["check", "-v"]);
t.expects(checked.status == 0 && checked.says("area.sakura"), checked.output.span);
t.expects(!checked.says("tests/main.sakura") && !checked.says("tests\\main.sakura"), checked.output.span);
# Its program, of the member's file, runs as the project's.
val ran := box.blossom("shop", ["run"]);
t.expects(ran.status == 0 && ran.says("area 12"), ran.output.span);
}
@test def a_members_folder_keeps_to_the_member(t: &mut tester, box: sandbox): void {
box.shop("shop");
val tested := box.blossom("shop/shapes", ["test"]);
t.expects(tested.status == 0 && tested.says("[2/2] Tested shop.shapes.tests (1 passed)") && !tested.says("Built shop"), tested.output.span);
# Its outputs are the project's.
t.expects(box.has("shop/.blossom") && !box.has("shop/shapes/.blossom"));
# Its mistakes name it.
val none := box.blossom("shop/app", ["test"]);
t.expects(none.status == 2 && none.error.span.find("app of tests/shop@1.0.0 has no tests.") is some, none.error.span);
val ran := box.blossom("shop/app", ["run"]);
t.expects(ran.status == 0 && ran.says("area 12"), ran.output.span);
}
@test def members_say_whose_they_are(t: &mut tester, box: sandbox): void {
box.shop("shop");
box.write("shop/app/blossomfile", """
targets: []
""");
val unsaid := box.blossom("shop", ["build"]);
t.expects(unsaid.status == 2 && unsaid.error.span.find("`member` is needed.") is some, unsaid.error.span);
box.write("shop/app/blossomfile", """
member: market
""");
val other := box.blossom("shop", ["build"]);
t.expects(other.status == 2 && other.error.span.find("member of `market`, but `shop` lists it") is some, other.error.span);
# A member's blossomfile is never a project's of its own.
box.write("shop/app/blossomfile", """
member: shop
name: app
""");
val named := box.blossom("shop", ["build"]);
t.expects(named.status == 2 && named.error.span.find("`name` is no key of a member's blossomfile.") is some, named.error.span);
# One no project lists is read by no command.
box.shop("shop");
box.write("shop/loose/blossomfile", """
member: shop
""");
val loose := box.blossom("shop/loose", ["build"]);
t.expects(loose.status == 2 && loose.error.span.find("no blossomfile above it lists its folder in `members`") is some, loose.error.span);
# Members name their targets apart from each other.
box.write("shop/app/blossomfile", """
member: shop
targets:
- name: shop.shapes
type: library
""");
val twice := box.blossom("shop", ["build"]);
t.expects(twice.status == 2 && twice.error.span.find("`shop.shapes` names two targets") is some, twice.error.span);
}
@test def a_member_requires_from_its_own_folder(t: &mut tester, box: sandbox): void {
box.shop("shop");
box.write("extra/blossomfile", """
name: extra
gpid: tests
semv: 1.0.0
targets:
- name: extra.numbers
type: library
exports:
- extra.numbers
""");
box.write("extra/extra.numbers/twice.sakura", """
module extra::numbers;
pub def twice(n: i64): i64 { return n * 2; }
""");
box.write("shop/shapes/blossomfile", """
member: shop
requires:
- ../../extra
targets:
- name: shop.shapes
type: library
root: .
deps: [extra.numbers]
""");
box.write("shop/shapes/area.sakura", """
import extra::numbers;
module shop::shapes;
pub def area(w: i64, h: i64): i64 { return numbers::twice(w * h) / 2; }
""");
val built := box.blossom("shop", ["build"]);
t.expects(built.status == 0 && built.says("Built shop"), built.error.span);
}
@test def a_project_requiring_one_of_members_reads_their_libraries(t: &mut tester, box: sandbox): void {
box.shop("shop");
box.write("user/blossomfile", """
name: user
gpid: tests
semv: 1.0.0
requires:
- ../shop
targets:
- name: user
type: program
deps: [std, shop.shapes]
srcs: [main.sakura]
""");
box.write("user/main.sakura", """
import std::io;
import shop::shapes;
def main(args: span<strview>): void {
io::println($"used {shapes::area(2, 3)}".span);
}
""");
val built := box.blossom("user", ["run"]);
t.expects(built.status == 0 && built.says("used 6"), built.error.span);
}
+93
View File
@@ -0,0 +1,93 @@
# Tests of what blossom refuses, each with status 2 and a line saying what's
# wrong and where: a key written twice, keys and options it doesn't know, a
# step of `install` without a tag it knows, and a folder with no blossomfile.
import std::testing;
# Writes a project whose blossomfile is the text given, with a program to build.
def sandbox::project(&this, folder: strview, blossomfile: strview): void {
this.write($"{folder}/blossomfile".span, blossomfile);
this.write($"{folder}/main.sakura".span, "def main(): void {}\n");
}
@test def a_key_written_twice_is_refused_by_its_line(t: &mut tester, box: sandbox): void {
box.project("twice", """
name: twice
gpid: tests
semv: 1.0.0
requires:
- remote: https://example.com/one
branch: v1.0.0
remote: https://example.com/two
branch: v1.0.0
""");
val built := box.blossom("twice", ["build"]);
t.expects(built.status == 2 && built.warns("blossomfile:8: `remote` is written twice in a requirement."), built.error.span);
}
@test def keys_options_and_targets_blossom_doesnt_know_are_refused(t: &mut tester, box: sandbox): void {
box.project("keys", """
name: keys
gpid: tests
semv: 1.0.0
targets:
- name: keys
type: program
srcs: [main.sakura]
optlevel: 2
""");
t.expects(box.blossom("keys", ["build"]).warns("blossomfile:9: `optlevel` is no key of a target."));
box.project("options", """
name: options
gpid: tests
semv: 1.0.0
options:
level: 2
targets:
- name: options
type: program
level: ${nope}
srcs: [main.sakura]
""");
val unknown := box.blossom("options", ["build"]);
t.expects(unknown.status == 2 && unknown.warns("blossomfile:11: `${nope}` names no option declared before it."), unknown.error.span);
val bad := box.blossom("keys", ["build", "-o", "nope=1"]);
t.expects(bad.status == 2 && bad.warns("`nope`, given a value, names no option of tests/keys@1.0.0."));
t.expects(box.blossom("keys", ["build", "--target", "mars"]).status == 2);
t.expects(box.blossom("keys", ["frobnicate"]).status == 2);
t.expects(box.blossom("keys", ["build", "--no-such-option"]).status == 2);
box.project("version", "name: version\ngpid: tests\nsemv: one\n");
t.expects(box.blossom("version", ["build"]).warns("`one` is not a version"));
box.project("level", "name: level\ngpid: tests\nsemv: 1.0.0\ntargets:\n- name: level\n type: program\n level: 3\n srcs: [main.sakura]\n");
t.expects(box.blossom("level", ["build"]).warns("blossomfile:7: `level` is 0, 1, or 2, not `3`."));
box.project("missing", "name: missing\ngpid: tests\nsemv: 1.0.0\ntargets:\n- name: missing\n type: program\n srcs: [nothing.sakura, '*.c']\n");
val missing := box.blossom("missing", ["build"]);
t.expects(missing.status == 2 && missing.warns("`nothing.sakura`, in `missing`'s `srcs`, names no file."), missing.error.span);
}
@test def a_step_of_install_says_what_it_does_by_a_tag_blossom_knows(t: &mut tester, box: sandbox): void {
box.project("untagged", "name: untagged\ngpid: tests\nsemv: 1.0.0\ninstall:\n- ./share\n");
val untagged := box.blossom("untagged", ["install", "--prefix", "prefix"]);
t.expects(untagged.status == 2 && untagged.warns("blossomfile:5: A step of `install` says what it does with a tag"), untagged.error.span);
box.project("unknown", "name: unknown\ngpid: tests\nsemv: 1.0.0\ninstall:\n- !program ./share\n");
val unknown := box.blossom("unknown", ["install", "--prefix", "prefix"]);
t.expects(unknown.status == 2 && unknown.warns("`!program` is no step blossom knows"), unknown.error.span);
box.project("outside", "name: outside\ngpid: tests\nsemv: 1.0.0\ninstall:\n- !include ../elsewhere\n- !include ./a:/etc\n");
t.expects(box.blossom("outside", ["install", "--prefix", "prefix"]).warns("`../elsewhere` is outside the project"));
}
@test def a_folder_without_a_blossomfile_is_refused(t: &mut tester, box: sandbox): void {
box.write("empty/main.sakura", "def main(): void {}\n");
val built := box.blossom("empty", ["build"]);
t.expects(built.status == 2 && built.warns("holds no blossomfile"), built.error.span);
}
+181
View File
@@ -0,0 +1,181 @@
# Tests of requirements: a folder beside the project, a remote cloned once into
# the store, from a bare git repository in the test's folder, written short with
# a ref and without, and as a block giving options, and what's refused: one
# project with two sets of options, a library not exported, a name two
# projects give, and a clone that fails.
import std::io;
import std::testing;
# Writes a project holding a library, `shapes.basic`, whose `side` gives the
# text the option `flavor` names a folder of, `plain` unless given.
def sandbox::shapes(&this, folder: strview, exported: bool = true): void {
var exports := string::new(nothing {});
if exported {
exports.append("exports:\n- shapes.basic\n");
}
this.write($"{folder}/blossomfile".span, $"""
name: shapes
gpid: tests
semv: 1.0.0
options:
flavor: plain
targets:
- name: shapes.basic
type: library
root: ./$\{flavor\}
{exports.span}
""".span);
this.write($"{folder}/plain/basic.sakura".span, "module shapes::basic;\n\npub def side(): strview { return \"plain\"; }\n");
this.write($"{folder}/fancy/basic.sakura".span, "module shapes::basic;\n\npub def side(): strview { return \"fancy\"; }\n");
}
# Writes a program, `app`, reading `shapes.basic`, which its blossomfile's
# `requires` names.
def sandbox::app(&this, folder: strview, requires: strview): void {
this.write($"{folder}/blossomfile".span, $"""
name: app
gpid: tests
semv: 1.0.0
requires:
{requires}
targets:
- name: app
type: program
deps: [shapes.basic]
srcs: [main.sakura]
""".span);
this.write($"{folder}/main.sakura".span, """
import std::io;
import shapes::basic;
def main(): void {
io::println($"side {basic::side()}".span);
}
""");
}
# Makes a bare git repository of a project, as a remote is, with a commit on
# `main` and a tag, `v1.0.0`.
def sandbox::remote(&this, from: strview, bare: strview): bool {
val into := this.path_of(bare);
return this.git(from, ["init", "-q", "-b", "main", "."])
&& this.git(from, ["add", "-A"])
&& this.git(from, ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "one"])
&& this.git(from, ["tag", "v1.0.0"])
&& this.git(from, ["clone", "-q", "--bare", ".", into.span]);
}
@test def a_folder_beside_the_project_is_required_by_its_path(t: &mut tester, box: sandbox): void {
box.shapes("shapes");
box.app("app", "- ../shapes");
val ran := box.blossom("app", ["run"]);
t.expects(ran.status == 0 && ran.says("side plain"), ran.error.span);
}
@test def a_block_gives_a_requirement_values_for_its_options(t: &mut tester, box: sandbox): void {
box.shapes("shapes");
box.app("app", "- remote: ../shapes\n options:\n flavor: fancy");
val ran := box.blossom("app", ["run"]);
t.expects(ran.status == 0 && ran.says("side fancy"), ran.error.span);
}
@test def a_remote_is_cloned_once_into_the_store(t: &mut tester, box: sandbox): void {
box.shapes("source");
t.expects(box.remote("source", "shapes.git"));
val shapes := box.url("shapes.git");
box.app("app", $"- {shapes}@v1.0.0".span);
val first := box.blossom("app", ["build"]);
t.expects(first.status == 0 && first.says("Cloning file://") && first.says("[1/1] Built app"), first.error.span);
val stored := box.stored("shapes@v1.0.0");
t.expects(stored.length != 0 && box.has($"{stored}/blossomfile".span));
# Cloned, it's taken from the store.
val second := box.blossom("app", ["build"]);
t.expects(second.status == 0 && !second.says("Cloning"));
# Without a ref, `main` is cloned.
box.app("main", $"- {shapes}".span);
val main := box.blossom("main", ["run"]);
t.expects(main.status == 0 && main.says("side plain"), main.error.span);
t.expects(box.stored("shapes@main").length != 0);
}
@test def a_clone_that_fails_says_why(t: &mut tester, box: sandbox): void {
when os == windows {
box.write("bin/git.cmd", "@echo off\r\necho fatal: the remote hung up 1>&2\r\nexit /b 128\r\n");
}
else {
box.write("bin/git", "#!/bin/sh\necho 'fatal: the remote hung up' >&2\nexit 128\n");
val git := box.at.join("bin/git");
_ = io::set_permissions(&git, 0o755);
}
box.app("app", "- https://example.com/shapes@v1.0.0");
val built := box.blossom("app", ["build"], box.search_path("bin").span);
t.expects(built.status == 1 && built.warns("fatal: the remote hung up") && built.warns("Cloning https://example.com/shapes@v1.0.0 failed."), built.error.span);
t.expects(box.stored("shapes@v1.0.0").length == 0);
}
@test def requirements_that_dont_fit_are_refused(t: &mut tester, box: sandbox): void {
# One project, with two sets of option values.
box.shapes("shapes");
box.write("other/blossomfile", "name: other\ngpid: tests\nsemv: 1.0.0\nrequires:\n- ../shapes\ntargets:\n- name: other.lib\n type: library\n deps: [shapes.basic]\n");
box.app("app", "- ../other\n- remote: ../shapes\n options:\n flavor: fancy");
val twice := box.blossom("app", ["build"]);
t.expects(twice.status == 2 && twice.warns("tests/shapes@1.0.0 is required with two sets of option values"), twice.error.span);
# A library its project doesn't export.
box.shapes("hidden", false);
box.app("private", "- ../hidden");
val private := box.blossom("private", ["build"]);
t.expects(private.status == 2 && private.warns("`shapes.basic`, which `app` reads, isn't exported by tests/shapes@1.0.0."), private.error.span);
# One name, two projects.
box.write("copy/blossomfile", "name: copy\ngpid: tests\nsemv: 1.0.0\ntargets:\n- name: shapes.basic\n type: library\n root: ./plain\nexports:\n- shapes.basic\n");
box.write("copy/plain/basic.sakura", "module shapes::basic;\n\npub def side(): strview { return \"copy\"; }\n");
box.app("both", "- ../shapes\n- ../copy");
val clash := box.blossom("both", ["build"]);
t.expects(clash.status == 2 && clash.warns("`shapes.basic` is a library of both"), clash.error.span);
# A library no project has.
box.app("none", " []");
t.expects(box.blossom("none", ["build"]).warns("`shapes.basic`, which `app` reads, is no library"));
}
@test def a_requirement_reads_what_it_requires_only_where_its_libraries_need_it(t: &mut tester, box: sandbox): void {
# What `shapes` requires for itself alone, which can't be fetched, isn't.
box.shapes("shapes");
val text := box.read("shapes/blossomfile");
box.write("shapes/blossomfile", $"{text.span}\nrequires:\n- https://example.invalid/never@v1.0.0\n".span);
box.app("app", "- ../shapes");
val ran := box.blossom("app", ["run"]);
t.expects(ran.status == 0 && ran.says("side plain") && !ran.says("Cloning"), ran.error.span);
# A library reading one of what its project requires brings that along.
box.shapes("inner");
box.write("outer/blossomfile", """
name: outer
gpid: tests
semv: 1.0.0
requires:
- ../inner
targets:
- name: outer.lib
type: library
deps: [shapes.basic]
exports:
- outer.lib
""");
box.write("outer/outer.lib/lib.sakura", "import shapes::basic;\n\nmodule outer::lib;\n\npub def says(): strview { return basic::side(); }\n");
box.write("user/blossomfile", "name: user\ngpid: tests\nsemv: 1.0.0\nrequires:\n- ../outer\ntargets:\n- name: user\n type: program\n deps: [outer.lib]\n srcs: [main.sakura]\n");
box.write("user/main.sakura", "import std::io;\nimport outer::lib;\n\ndef main(): void { io::println($\"says {lib::says()}\".span); }\n");
val through := box.blossom("user", ["run"]);
t.expects(through.status == 0 && through.says("says plain"), through.error.span);
}
+471
View File
@@ -0,0 +1,471 @@
# What blossom's tests of its commands share: the blossom they run, a folder of
# each test's own, writing projects into it, and running blossom there.
import std::io;
import std::process;
import system;
import std::testing;
#! The blossom the tests run, which `main` is given first.
var blossom_at: strview = "";
#! The standard library the projects the tests make are given, as their
#! config's `std`: the one blossom's own project reads, so the tests don't
#! depend on a `sakura` that finds one of its own. Empty where blossom's store
#! holds none, for the one `sakura` finds.
var std_at: strview = "";
#! The folder of the standard library blossom's own project reads, from what
#! `blossom libraries` lists of it, as `--lib std::io=FOLDER/io`.
#! @param listed What `blossom libraries` printed.
#! @returns The folder, or empty text where it lists no module of std.
def std_folder(listed: strview): strview {
for line in listed.lines() {
continue if !line.starts_with("--lib std::");
val rest := line.substr(11, line.length - 11);
val equals := rest.find("=") else { continue; };
# A module within one, as `std::io::glob`, is a folder deeper.
continue if rest.substr(0, equals).find(":") is some;
val folder := rest.substr(equals + 1, rest.length - equals - 1);
var end := folder.length;
while end > 0 && folder[end - 1] != '/' && folder[end - 1] != '\\' {
end--;
}
return folder.substr(0, end - 1) if end > 1;
}
return strview::blank();
}
#! The line of a sandbox's config naming `std_at` as its `std`.
#! @returns The line, or empty text where there's none.
def std_line(): string {
if std_at.length == 0 {
return string::new(nothing {});
}
return $"std: {std_at}\n";
}
#! The folder the system keeps temporary files in: what `TMPDIR` names, or on
#! Windows `TEMP` or `TMP`, else `/tmp`.
#! @returns The folder.
def temporary_folder(): strview {
for name in ["TMPDIR", "TEMP", "TMP"] {
if process::variable(name) is some(named) {
return named if named.length != 0;
}
}
return "/tmp";
}
#! Removes a file, or a folder and everything in it, as blossom's `remove_tree`
#! does. Links are removed, not followed.
#! @param at What to remove.
def remove_tree(at: &path): void {
val found := io::info(at, false) else (_) { return; };
if found.kind == file_kind::directory {
var names := vector::<path>::new();
var listing := io::directory::open(at) else (_) { return; };
while listing.next() is some(entry) {
val name := path::parse(entry.name) else (_) { return; };
names.append(at.join(&name));
}
for &each in names {
remove_tree(each);
}
}
_ = io::remove(at);
}
#! A folder of a test's own, in the system's temporary folder, holding the
#! projects it makes, and blossom's config, in `config`, naming the `sakura` and
#! std the tests run, and store, in `cache`, removed with all it holds where the
#! test returns.
struct sandbox : fixture<sandbox>, owning {
var at: path;
}
def sandbox::setup(t: &mut tester): sandbox {
val temporary := temporary_folder();
for n in 0..10000 {
var at := path::parse($"{temporary}/blossom-tests-{n}".span) else (_) { break; };
if io::create_directory(&at) is error(_) {
continue;
}
var made := sandbox { at = move(at) };
var config := string::new(nothing {});
if process::variable("SAKURA") is some(sakura) {
config.append($"sakura: {sakura}\n".span);
}
config.append(std_line().span);
made.write("config/blossom/config", config.span);
return made;
}
system::abort();
return sandbox {};
}
def sandbox::close(&mut this): void {
remove_tree(&this.at);
}
#! Writes a file in the sandbox, making the folders above it.
#! @param this The sandbox.
#! @param name The file, relative to the sandbox.
#! @param text What it holds.
def sandbox::write(&this, name: strview, text: strview): void {
val at := this.at.join(name);
if at.parent() is some(&above) {
_ = io::create_directories(above);
}
_ = io::write_file(&at, text);
}
#! Reads a file of the sandbox.
#! @param this The sandbox.
#! @param name The file, relative to the sandbox.
#! @returns What it holds, or empty text where it can't be read.
def sandbox::read(&this, name: strview): string {
val at := this.at.join(name);
return io::read_file(&at) else (_) { return string::new(nothing {}); };
}
#! Whether a file or folder is in the sandbox.
#! @param this The sandbox.
#! @param name Its path, relative to the sandbox.
#! @returns Whether it is.
def sandbox::has(&this, name: strview): bool {
val at := this.at.join(name);
return io::exists(&at);
}
#! The text of a path in the sandbox, as the system writes it and blossom says
#! it: `/tmp/blossom-tests-0/app/app.parts`, and on Windows with `\`.
#! @param this The sandbox.
#! @param name The path, relative to the sandbox.
#! @returns Its text.
def sandbox::path_of(&this, name: strview): string {
val at := this.at.join(name);
return string::from(at.span, nothing {});
}
#! Text a program wrote, its lines ended by `\n` alone, as a program of Windows
#! ends them by `\r\n`.
#! @param text The text.
#! @returns The text without `\r`.
def lines_of(text: strview): string {
var made := string::new(nothing {});
for i in 0..text.length {
if text[i] != '\r' {
made.push(text[i]);
}
}
return made;
}
#! The folder a project's packages are made in, `.blossom/KEY/dist`, of the
#! first output folder holding one.
#! @param this The sandbox.
#! @param folder The project's folder, relative to the sandbox.
#! @returns The folder, as the system writes it, or empty text where there's
#! none.
def sandbox::dist(&this, folder: strview): string {
val outputs := this.at.join(folder).join(".blossom");
val found := folder_named(&outputs, "dist", 0) else { return string::new(nothing {}); };
return string::from(found.span, nothing {});
}
#! The `file://` URL of a folder of the sandbox, as git takes one:
#! `file:///tmp/blossom-tests-0/shapes.git`, and on Windows
#! `file:///C:/Users/me/AppData/Local/Temp/blossom-tests-0/shapes.git`.
#! @param this The sandbox.
#! @param name The folder, relative to the sandbox.
#! @returns The URL.
def sandbox::url(&this, name: strview): string {
val at := this.path_of(name);
var made := string::from("file://", nothing {});
if at.length != 0 && at[0] != '/' {
made.push('/');
}
for i in 0..at.length {
made.push(at[i] == '\\' ? '/' : at[i]);
}
return made;
}
#! The folder of blossom's store in the sandbox that a remote's branch is
#! cloned into, found by its name, as `shapes@v1.0.0`, wherever the remote's
#! path put it, which differs from system to system.
#! @param this The sandbox.
#! @param name The folder's name.
#! @returns Its path, as the system writes it, or empty text where there's none.
def sandbox::stored(&this, name: strview): string {
val store := this.at.join("cache/blossom");
val found := folder_named(&store, name, 0) else { return string::new(nothing {}); };
return string::from(found.span, nothing {});
}
# The first folder of a name within a folder, or within those it holds.
def folder_named(at: &path, name: strview, depth: u32): maybe<path> {
return nothing {} if depth > 16;
var folders := vector::<path>::new();
var listing := io::directory::open(at) else (_) { return nothing {}; };
while listing.next() is some(entry) {
continue if entry.kind != file_kind::directory;
val each := path::parse(entry.name) else (_) { continue; };
if entry.name == name {
return at.join(&each);
}
folders.append(at.join(&each));
}
for &each in folders {
val found := folder_named(each, name, depth + 1);
return found if found is some;
}
return nothing {};
}
#! A program's file, as the system names it: `hello`, and on Windows
#! `hello.exe`.
#! @param name The program.
#! @returns Its file's name.
def program(name: strview): string {
when os == windows {
return $"{name}.exe";
}
return string::from(name, nothing {});
}
when os == windows {
# How `PATH` splits its folders.
val path_split: strview = ";";
# The folder of the system's own programs, which holds no `sakurac`.
def system_programs(): string {
val root := process::variable("SystemRoot") else { return string::from("C:\\Windows\\System32", nothing {}); };
return $"{root}\\System32";
}
}
else {
val path_split: strview = ":";
def system_programs(): string {
return string::from("/usr/bin:/bin", nothing {});
}
}
#! A `PATH` of a folder of the sandbox, where one's named, then the system's own
#! programs, which hold no `sakurac`, split as the system splits it.
#! @param this The sandbox.
#! @param folder The folder, relative to the sandbox, or empty for none.
#! @returns The `PATH`.
def sandbox::search_path(&this, folder: strview = ""): string {
var made := string::new(nothing {});
if folder.length != 0 {
made.append(this.path_of(folder).span);
made.append(path_split);
}
made.append(system_programs().span);
return made;
}
#! Runs git in a folder of the sandbox.
#! @param this The sandbox.
#! @param folder The folder, relative to the sandbox.
#! @param words What git is given.
#! @returns Whether it succeeded.
def sandbox::git(&this, folder: strview, words: span<strview>): bool {
return this.run("git", folder, words).status == 0;
}
#! What a command said, and the status it ended with.
struct said {
var status: i32;
var output: string;
var error: string;
}
#! Whether what a command wrote to its output holds some text.
#! @param this What it said.
#! @param text The text.
#! @returns Whether it does.
def said::says(&this, text: strview): bool {
return this.output.span.find(text) is some;
}
#! Whether what a command wrote to its error holds some text.
#! @param this What it said.
#! @param text The text.
#! @returns Whether it does.
def said::warns(&this, text: strview): bool {
return this.error.span.find(text) is some;
}
#! Runs blossom in a folder of the sandbox, its config and store the sandbox's.
#! @param this The sandbox.
#! @param folder The folder, relative to the sandbox.
#! @param words What blossom is given.
#! @param path What `PATH` is, or empty for the tests' own.
#! @returns What it said.
def sandbox::blossom(&this, folder: strview, words: span<strview>, path: strview = ""): said {
return this.run(blossom_at, folder, words, path);
}
#! Runs a program in a folder of the sandbox, as `blossom` does, where blossom's
#! config and store are the sandbox's: `XDG_CONFIG_HOME` and `XDG_CACHE_HOME`
#! name them, and on Windows `APPDATA` and `LOCALAPPDATA`, which blossom reads
#! there, so no test reaches the user's own.
#! @param this The sandbox.
#! @param program The program.
#! @param folder The folder, relative to the sandbox.
#! @param words What it's given.
#! @param path What `PATH` is, or empty for the tests' own.
#! @returns What it said.
def sandbox::run(&this, program: strview, folder: strview, words: span<strview>, path: strview = ""): said {
var command := process::command::new(program);
command.arguments(words);
val at := this.at.join(folder);
command.directory(&at);
command.set_variable("XDG_CONFIG_HOME", $"{this.at.span}/config".span);
command.set_variable("XDG_CACHE_HOME", $"{this.at.span}/cache".span);
command.set_variable("APPDATA", $"{this.at.span}/config".span);
command.set_variable("LOCALAPPDATA", $"{this.at.span}/cache".span);
command.set_variable("SOURCE_DATE_EPOCH", "1700000000");
# On Windows, the copy of the tests running this one is told its test by
# `SAKURA_TEST_ONE`, which the tests blossom runs would read as theirs.
command.set_variable("SAKURA_TEST_ONE", "");
if path.length != 0 {
command.set_variable("PATH", path);
}
var got := command.capture() else (why) {
return said { status = -1, output = string::new(nothing {}), error = $"`{program}` can't be run: {why}" };
};
var code: i32 = -1;
if got.status is exited(exited) {
code = exited;
}
return said { status = code, output = move(got.output), error = move(got.error) };
}
#! The path a line of blossom's output gives in parentheses, as the program of
#! `[2/2] Built hello (.blossom/KEY/bin/hello)`, relative to the project.
#! @param text What blossom said.
#! @param name The target.
#! @returns The path, or empty text.
def built_path(text: strview, name: strview): strview {
val marker := $"Built {name} (";
val at := text.find(marker.span) else { return strview::blank(); };
val from := at + marker.length;
val rest := text.substr(from, text.length - from);
val end := rest.find(")") else { return strview::blank(); };
return rest.substr(0, end);
}
#! Writes a project, `shown`, in a folder of the sandbox: a program shown as a
#! desktop's program is, by its title, its icon, a PNG of 32 pixels each way
#! and an SVG, and its window, which its option `windowed` says, as an editor
#! building a game would give it.
#! @param this The sandbox.
#! @param folder The project's folder.
def sandbox::shown(&this, folder: strview): void {
this.write($"{folder}/blossomfile".span, """
name: shown
gpid: tests
semv: 2.1.0
options:
windowed: true
targets:
- name: shown
type: program
srcs: [main.sakura]
title: Shown Off
icon: [icons/shown.png, icons/shown.svg]
windowed: ${windowed}
""");
this.write($"{folder}/main.sakura".span, """
import std::io;
def main(): void {
io::println("shown");
}
""");
this.write($"{folder}/icons/shown.png".span, "\x89PNG\r\n\x1A\n\x00\x00\x00\x0DIHDR\x00\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00");
this.write($"{folder}/icons/shown.svg".span, "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\"/>\n");
}
#! A word of a file's bytes, the least significant byte first.
#! @param bytes The bytes.
#! @param at Where it is.
#! @param size How many bytes it is.
#! @returns The word, or 0 where it's past the end.
def word_of(bytes: strview, at: u64, size: u64): u64 {
return 0 if at + size > bytes.length;
var made: u64 = 0;
for k in 0..size {
made = made | (bytes[at + k] as u64 << (8 * k));
}
return made;
}
#! Writes a project, `hello`, in a folder of the sandbox: a program reading a
#! library of its own, `hello.geometry`, which holds a module within it, and
#! tests of the library, as the plan's "Using it" has it.
#! @param this The sandbox.
#! @param folder The project's folder.
#! @param more What's added to its blossomfile.
def sandbox::hello(&this, folder: strview, more: strview = ""): void {
this.write($"{folder}/blossomfile".span, $"""
name: hello
gpid: tests
semv: 1.0.0
options:
level: 2
targets:
- name: hello
type: program
level: $\{level\}
deps: [std, hello.geometry]
srcs: [main.sakura]
- name: hello.geometry
type: library
tests:
- name: hello.tests
type: program
deps: [hello.geometry]
{more}
""".span);
this.write($"{folder}/main.sakura".span, """
import std::io;
import hello::geometry;
import hello::geometry::solids;
def main(args: span<strview>): void {
io::println($"area {geometry::area(3, 4)} cube {solids::cube(2)} given {args.length}".span);
}
""");
this.write($"{folder}/hello.geometry/shapes.sakura".span, """
module hello::geometry;
pub def area(w: i64, h: i64): i64 { return w * h; }
""");
this.write($"{folder}/hello.geometry/solids/solids.sakura".span, """
module hello::geometry::solids;
pub def cube(side: i64): i64 { return side * side * side; }
""");
this.write($"{folder}/tests/main.sakura".span, """
import system;
import std::testing;
import hello::geometry;
import hello::geometry::solids;
def main(args: span<strview>): void { exit(tester::run(args)); }
@test def areas_multiply(t: &mut tester): void { t.expects(geometry::area(2, 5) == 10); }
@test def cubes_cube(t: &mut tester): void { t.expects(solids::cube(3) == 27); }
""");
}
+14
View File
@@ -0,0 +1,14 @@
# Runs blossom's tests of its parts, which read its own files:
#
# blossom test --suite blossom.units
#
# or, from the root of the repository, with the standard library beside it:
#
# sakurac run --lib std=../std
# models/*.sakura management/*.sakura pipeline/*.sakura tests/units/*.sakura
import system;
import std::testing;
def main(args: span<strview>): void {
exit(tester::run(args));
}
+239
View File
@@ -0,0 +1,239 @@
# Tests of blossom's parts: reading blossomfiles, the store's folders, output
# folders' names, versions, the digests packages carry, and commands as `-v`
# prints them.
import std::io;
import std::testing;
import blossom::models;
import blossom::management;
import blossom::pipeline;
# Reads a blossomfile's text, giving what's wrong, or empty text where nothing
# is.
def problem_in(text: strview): string {
val file := path::parse("/projects/tests/blossomfile") else (_) { return string::new(nothing {}); };
var overrides := vector::<models::setting>::new();
var read := models::read_project(text, &file, overrides.span, "");
if read is error(&problem) {
return problem.describe();
}
return string::new(nothing {});
}
# What `problem_in` gives for a problem: the blossomfile's path, as the system
# writes it, as `\projects\tests\blossomfile` on Windows, then the rest.
def problem_at(rest: strview): string {
val file := path::parse("/projects/tests/blossomfile") else (_) { return string::new(nothing {}); };
return $"{file.span}{rest}";
}
@test def digests_are_those_their_standards_give(t: &mut tester): void {
t.expects(pipeline::md5("") == "d41d8cd98f00b204e9800998ecf8427e");
t.expects(pipeline::md5("abc") == "900150983cd24fb0d6963f7d28e17f72");
t.expects(pipeline::md5("12345678901234567890123456789012345678901234567890123456789012345678901234567890") == "57edf4a22be3c955ac49da2e2107b67a");
t.expects(pipeline::sha256("") == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
t.expects(pipeline::sha256("abc") == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
t.expects(pipeline::sha256("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") == "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1");
t.expects(pipeline::crc32("123456789") == 0xCBF43926 && pipeline::crc32("") == 0);
}
@test def remotes_are_stored_by_their_host_path_and_ref(t: &mut tester): void {
t.expects(management::store_key("https://git.malunal.studio/malunal/json", "v1.0.0") == "git.malunal.studio/malunal/json@v1.0.0");
t.expects(management::store_key("https://me@host.com/a/b.git", "main") == "host.com/a/b@main");
t.expects(management::store_key("git@github.com:malunal/json.git", "main") == "github.com/malunal/json@main");
t.expects(management::store_key("file:///tmp/x/repo.git", "v2") == "file/tmp/x/repo@v2");
# Nothing leads out of the store.
t.expects(management::store_key("https://host/../../etc", "main") == "host/etc@main");
t.expects(management::store_key("https://host/a", "../../x") == "host/a@.._.._x");
}
@test def output_folders_are_named_by_identity_options_and_target(t: &mut tester): void {
var options := vector::<models::setting>::new();
options.append(models::setting { name = string::from("level", nothing {}), value = string::from("2", nothing {}) });
options.append(models::setting { name = string::from("debug", nothing {}), value = string::from("false", nothing {}) });
val first := models::output_key("malunal/hello@1.0.0", options.span, "");
t.expects(first.length == 16);
# In any order, the same options name the same folder.
var reordered := vector::<models::setting>::new();
reordered.append(models::setting { name = string::from("debug", nothing {}), value = string::from("false", nothing {}) });
reordered.append(models::setting { name = string::from("level", nothing {}), value = string::from("2", nothing {}) });
t.expects(models::output_key("malunal/hello@1.0.0", reordered.span, "") == first);
t.expects(models::output_key("malunal/hello@1.0.0", options.span, "windows-x86_64") != first);
t.expects(models::output_key("malunal/hello@1.0.1", options.span, "") != first);
t.expects(models::hex(0x0123456789abcdef) == "0123456789abcdef");
}
@test def versions_are_semantic(t: &mut tester): void {
for text in ["1.2.0", "0.0.1", "10.20.30", "1.2.0-alpha", "1.2.0-alpha.1", "1.2.0+build.5"] {
t.expects(models::is_version(text), text);
}
for text in ["1", "1.2", "1.2.x", "v1.2.0", "1.2.0-", "1..0", ""] {
t.expects(!models::is_version(text), text);
}
}
@test def blossomfiles_are_read_with_their_mistakes_found(t: &mut tester): void {
t.expects(problem_in("name: a\ngpid: b\nsemv: 1.0.0\n").length == 0);
t.expects(problem_in("") == problem_at(": The blossomfile is empty: it needs `name`, `gpid`, and `semv`."));
t.expects(problem_in("name: a\ngpid: b\n") == problem_at(":1: `semv` is needed."));
t.expects(problem_in("name: a\ngpid: b\nsemv: 1.0.0\nname: c\n") == problem_at(":4: `name` is written twice in the blossomfile."));
t.expects(problem_in("name: a\ngpid: b\nsemv: 1.0.0\noptions:\n bin: x\n").span.find("`bin` is blossom's") is some);
t.expects(problem_in("name: a\ngpid: b\nsemv: 1.0.0\nexports: [nope]\n").span.find("`nope` is exported, but it's no library") is some);
t.expects(problem_in("name: a\ngpid: b\nsemv: 1.0.0\ntargets:\n- name: x.y\n type: library\n- name: x.y\n type: library\n").span.find("`x.y` names two targets: this, and that of line 5.") is some);
t.expects(problem_in("name: a\ngpid: b\nsemv: 1.0.0\ntargets:\n- name: 9lives\n type: library\n").span.find("names no module") is some);
t.expects(problem_in("name: a\ngpid: b\nsemv: 1.0.0\ntargets:\n- name: p\n type: program\n").span.find("`p` needs `srcs`") is some);
t.expects(problem_in("name: a\ngpid: b\nsemv: 1.0.0\nrequires:\n- ../x@v1\n- remote: ../y\n branch: v1\n").span.find("A folder takes no `branch`.") is some);
t.expects(problem_in("name: a\ngpid: b\nsemv: 1.0.0\ntargets:\n- name: l\n type: library\n srcs: [a.sakura]\n").span.find("A library takes no `srcs`") is some);
}
@test def requirements_are_read_short_and_as_blocks(t: &mut tester): void {
val file := path::parse("/projects/tests/blossomfile") else (_) { return; };
var overrides := vector::<models::setting>::new();
var read := models::read_project("""
name: a
gpid: b
semv: 1.0.0
requires:
- https://host/json@v1.0.0
- git@host:malunal/yaml
- ../shapes
- remote: https://host/args
options:
strict: true
""", &file, overrides.span, "");
if read is not value(&made) {
t.expects(false);
return;
}
t.expects(made.requires.length == 4);
t.expects(made.requires[0].remote == "https://host/json" && made.requires[0].branch == "v1.0.0" && !made.requires[0].local);
t.expects(made.requires[1].remote == "git@host:malunal/yaml" && made.requires[1].branch == "main");
t.expects(made.requires[2].remote == "../shapes" && made.requires[2].local);
t.expects(made.requires[3].branch == "main" && made.requires[3].options.length == 1 && made.requires[3].options[0].value == "true");
}
# Reads a blossomfile with values given its options, as `-o` gives them.
def read_given(text: strview, given: span<strview>): result<models::project, models::problem> {
val file := path::parse("/projects/tests/blossomfile") else (_) {
return models::problem { message = string::from("no path", nothing {}) };
};
var overrides := vector::<models::setting>::new();
for &each in given {
val split := each.find("=") else { continue; };
overrides.append(models::setting {
name = string::from(each.substr(0, split), nothing {}),
value = string::from(each.substr(split + 1, each.length - split - 1), nothing {})
});
}
return models::read_project(text, &file, overrides.span, "");
}
# A program shown by options, as an editor building a game gives them.
val shown_by_options: strview = """
name: a
gpid: b
semv: 1.0.0
options:
title: ''
icon: ''
windowed: false
targets:
- name: game
type: program
srcs: [main.sakura]
title: ${title}
icon: ${icon}
windowed: ${windowed}
""";
@test def a_program_is_shown_by_its_title_icons_and_window(t: &mut tester): void {
var read := read_given("""
name: a
gpid: b
semv: 1.0.0
targets:
- name: app
type: program
srcs: [main.sakura]
title: The App
icon: [icons/app.png, icons/app.svg, app.ICO]
windowed: true
- name: tool
type: program
srcs: [tool.sakura]
icon: one.png, two.png
- name: plain
type: program
srcs: [plain.sakura]
""", span::<strview>::blank());
if read is not value(&made) {
t.expects(false);
return;
}
val app := &made.targets[0];
t.expects(app.title == "The App" && app.windowed && app.icons.length == 3 && app.icons[0] == "icons/app.png" && app.icons[2] == "app.ICO");
t.expects(app.shown);
t.expects(made.targets[1].icons.length == 2 && made.targets[1].icons[1] == "two.png" && !made.targets[1].windowed);
t.expects(!made.targets[2].shown && made.targets[2].title.length == 0);
t.expects(problem_in("name: a\ngpid: b\nsemv: 1.0.0\ntargets:\n- name: p\n type: program\n srcs: [p.sakura]\n icon: p.bmp\n").span.find("`p.bmp` is no icon blossom knows") is some);
t.expects(problem_in("name: a\ngpid: b\nsemv: 1.0.0\ntargets:\n- name: p\n type: program\n srcs: [p.sakura]\n windowed: yes\n").span.find("`windowed` is `true` or `false`, not `yes`") is some);
t.expects(problem_in("name: a\ngpid: b\nsemv: 1.0.0\ntargets:\n- name: l.m\n type: library\n icon: l.png\n").span.find("A library takes no `icon`") is some);
t.expects(problem_in("name: a\ngpid: b\nsemv: 1.0.0\ntests:\n- name: t\n type: program\n title: T\n").span.find("`title` is no key of a test") is some);
}
@test def options_give_a_program_its_title_icons_and_window(t: &mut tester): void {
# Given nothing, an empty title and icon are none.
var plain := read_given(shown_by_options, span::<strview>::blank());
if plain is not value(&made) {
t.expects(false);
return;
}
t.expects(made.targets[0].title.length == 0 && made.targets[0].icons.length == 0 && !made.targets[0].windowed && !made.targets[0].shown);
# Several files are given as one value, between commas.
val given: strview[3] = ["title=Garden", "icon=icon.png, icon-16.png,icon.svg", "windowed=true"];
var shown := read_given(shown_by_options, given[:]);
if shown is not value(&made) {
t.expects(false);
return;
}
val game := &made.targets[0];
t.expects(game.title == "Garden" && game.windowed && game.shown);
t.expects(game.icons.length == 3 && game.icons[0] == "icon.png" && game.icons[1] == "icon-16.png" && game.icons[2] == "icon.svg");
# What's given is checked as what's written is.
val windowed: strview[1] = ["windowed=maybe"];
if read_given(shown_by_options, windowed[:]) is error(&problem) {
t.expects(problem.describe().span.find("`windowed` is `true` or `false`, not `maybe`") is some);
} else {
t.expects(false);
}
val icon: strview[1] = ["icon=icon.gif"];
if read_given(shown_by_options, icon[:]) is error(&problem) {
t.expects(problem.describe().span.find("`icon.gif` is no icon blossom knows") is some);
} else {
t.expects(false);
}
}
@test def a_desktop_entry_runs_its_program_where_the_prefix_holds_it(t: &mut tester): void {
t.expects(pipeline::exec_text("/usr", "game") == "/usr/bin/game");
t.expects(pipeline::exec_text("/opt/games/", "game") == "/opt/games/bin/game");
t.expects(pipeline::exec_text("C:\\Users\\me\\.local", "game") == "C:/Users/me/.local/bin/game");
t.expects(pipeline::exec_text("/home/me/my games", "game") == "\"/home/me/my games/bin/game\"");
t.expects(pipeline::exec_text("/home/me/100%", "game") == "\"/home/me/100%%/bin/game\"");
t.expects(pipeline::for_windows("windows-x86_64") && !pipeline::for_windows("linux-x86_64"));
val size := pipeline::png_size("\x89PNG\r\n\x1A\n\x00\x00\x00\x0DIHDR\x00\x00\x01\x00\x00\x00\x00\x30rest");
t.expects(size[0] == 256 && size[1] == 48);
t.expects(pipeline::png_size("GIF89a, not a PNG at all")[0] == 0);
}
@test def commands_are_printed_as_a_shell_takes_them(t: &mut tester): void {
var words := vector::<string>::new();
for each in ["sakura", "build", "--lib", "a::b=./x", "my file.sakura", "it's"] {
words.append(string::from(each, nothing {}));
}
t.expects(pipeline::spoken(words.span) == "sakura build --lib a::b=./x 'my file.sakura' 'it'\\''s'");
}