Compare commits

..

No commits in common. "master" and "v0.4.0" have entirely different histories.

73 changed files with 962 additions and 2258 deletions

View File

@ -1,3 +0,0 @@
target
.git
Dockerfile

View File

@ -1,27 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
<!-- Please do not open bug reports if you're using Manjaro.
ALMA does not support Manjaro. If it works then have fun, but if it doesn't then I won't fix it -->
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Additional context**
Add any other context about the problem here.

View File

@ -1,22 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
<!-- Before requesting a feature, note that ALMA isn't intended to be a generic Arch Linux installer. It's an installer focused on creating mutable live environments. In addition, avoid asking for new features which can be easily implemented using the preset system -->
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@ -1,31 +0,0 @@
name: Rust
on:
push:
pull_request:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
components: rustfmt, clippy
- uses: actions-rs/cargo@v1
name: Check format
with:
command: fmt
args: --all -- --check
- uses: actions-rs/cargo@v1
name: Run clippy
with:
command: clippy
args: --all-targets --locked -- -D warnings
- uses: actions-rs/cargo@v1
name: Run tests
with:
command: test

672
Cargo.lock generated
View File

@ -1,621 +1,529 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "aho-corasick"
version = "0.7.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8716408b8bc624ed7f65d223ddb9ac2d044c0547b6fa4b0d554f3a9540496ada"
dependencies = [
"memchr",
]
[[package]]
name = "alma"
version = "0.10.0"
version = "0.4.0"
dependencies = [
"anyhow",
"byte-unit",
"console",
"dialoguer",
"env_logger 0.8.2",
"log",
"nix",
"pretty_env_logger",
"serde",
"structopt",
"tempfile",
"toml",
"which",
"failure 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"nix 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)",
"simplelog 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)",
"structopt 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)",
"tempfile 3.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
"which 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "ansi_term"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b"
dependencies = [
"winapi",
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "anyhow"
version = "1.0.31"
name = "atty"
version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85bb70cc08ec97ca5450e6eba421deeea5f172c0fc61f78b5357b2a8e8be195f"
dependencies = [
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "atty"
version = "0.2.14"
name = "backtrace"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
dependencies = [
"hermit-abi",
"libc",
"winapi",
"backtrace-sys 0.1.24 (registry+https://github.com/rust-lang/crates.io-index)",
"cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-demangle 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "backtrace-sys"
version = "0.1.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"cc 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "bitflags"
version = "1.2.1"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
[[package]]
name = "byte-unit"
version = "4.0.9"
name = "byteorder"
version = "1.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c8758c32833faaae35b24a73d332e62d0528e89076ae841c63940e37008b153"
dependencies = [
"utf8-width",
]
[[package]]
name = "cc"
version = "1.0.54"
version = "1.0.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7bbb73db36c1246e9034e307d0fba23f9a2e251faa47ade70c1bd252220c8311"
[[package]]
name = "cfg-if"
version = "0.1.10"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
[[package]]
name = "chrono"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"num-integer 0.1.39 (registry+https://github.com/rust-lang/crates.io-index)",
"num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
"time 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "clap"
version = "2.33.1"
version = "2.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdfa80d47f954d53a35a64987ca1422f495b8d6483c0fe9f7117b36c2a792129"
dependencies = [
"ansi_term",
"atty",
"bitflags",
"strsim",
"textwrap",
"unicode-width",
"vec_map",
"ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)",
"atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)",
"bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
"strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"textwrap 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
"unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
"vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "console"
version = "0.13.0"
name = "cloudabi"
version = "0.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a50aab2529019abfabfa93f1e6c41ef392f91fbf179b347a7e96abb524884a08"
dependencies = [
"encode_unicode",
"lazy_static",
"libc",
"regex",
"terminal_size",
"unicode-width",
"winapi",
"winapi-util",
"bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "dialoguer"
version = "0.7.1"
name = "failure"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70f807b2943dc90f9747497d9d65d7e92472149be0b88bf4ce1201b4ac979c26"
dependencies = [
"console",
"lazy_static",
"tempfile",
"zeroize",
"backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)",
"failure_derive 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "encode_unicode"
version = "0.3.6"
name = "failure_derive"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f"
[[package]]
name = "env_logger"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36"
dependencies = [
"atty",
"humantime 1.3.0",
"log",
"regex",
"termcolor",
"proc-macro2 0.4.24 (registry+https://github.com/rust-lang/crates.io-index)",
"quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)",
"syn 0.15.22 (registry+https://github.com/rust-lang/crates.io-index)",
"synstructure 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "env_logger"
version = "0.8.2"
name = "fuchsia-zircon"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26ecb66b4bdca6c1409b40fb255eefc2bd4f6d135dab3c3124f80ffa2a9661e"
dependencies = [
"atty",
"humantime 2.0.1",
"log",
"regex",
"termcolor",
"bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
"fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "getrandom"
version = "0.1.14"
name = "fuchsia-zircon-sys"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7abc8dd8451921606d809ba32e95b6111925cd2906060d2dcc29c070220503eb"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "heck"
version = "0.3.1"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20564e78d53d2bb135c343b3f47714a56af2061f1c928fdb541dc7b9fdd94205"
dependencies = [
"unicode-segmentation",
"unicode-segmentation 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "hermit-abi"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9586eedd4ce6b3c498bc3b4dd92fc9f11166aa908a914071953768066c67909"
dependencies = [
"libc",
]
[[package]]
name = "humantime"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f"
dependencies = [
"quick-error",
]
[[package]]
name = "humantime"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c1ad908cc71012b7bea4d0c53ba96a8cba9962f048fa68d143376143d863b7a"
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.80"
version = "0.2.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d58d1b70b004888f764dfbf6a26a3b0342a1632d33968e4a179d8011c760614"
[[package]]
name = "log"
version = "0.4.8"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7"
dependencies = [
"cfg-if",
"cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "memchr"
version = "2.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400"
[[package]]
name = "nix"
version = "0.19.0"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85db2feff6bf70ebc3a4793191517d5f0331100a2f10f9bf93b5e5214f32b7b7"
dependencies = [
"bitflags",
"cc",
"cfg-if",
"libc",
"bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
"cc 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)",
"cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "ppv-lite86"
version = "0.2.8"
name = "num-integer"
version = "0.1.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "237a5ed80e274dbc66f86bd59c1e25edc039660be53194b5fe0a482e0f2612ea"
[[package]]
name = "pretty_env_logger"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "926d36b9553851b8b0005f1275891b392ee4d2d833852c417ed025477350fb9d"
dependencies = [
"env_logger 0.7.1",
"log",
"num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "proc-macro-error"
version = "1.0.2"
name = "num-traits"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98e9e4b82e0ef281812565ea4751049f1bdcdfccda7d3f459f2e138a40c08678"
dependencies = [
"proc-macro-error-attr",
"proc-macro2",
"quote",
"syn",
"version_check",
]
[[package]]
name = "proc-macro-error-attr"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f5444ead4e9935abd7f27dc51f7e852a0569ac888096d5ec2499470794e2e53"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn-mid",
"version_check",
]
[[package]]
name = "proc-macro2"
version = "1.0.18"
version = "0.4.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "beae6331a816b1f65d04c45b078fd8e6c93e8071771f41b8163255bbd8d7c8fa"
dependencies = [
"unicode-xid",
"unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "quick-error"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
[[package]]
name = "quote"
version = "1.0.7"
version = "0.6.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37"
dependencies = [
"proc-macro2",
"proc-macro2 0.4.24 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "rand"
version = "0.7.3"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03"
dependencies = [
"getrandom",
"libc",
"rand_chacha",
"rand_core",
"rand_hc",
"cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)",
"fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"rand_chacha 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rand_hc 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rand_isaac 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"rand_pcg 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"rand_xorshift 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "rand_chacha"
version = "0.2.2"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402"
dependencies = [
"ppv-lite86",
"rand_core",
"rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "rand_core"
version = "0.5.1"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19"
dependencies = [
"getrandom",
]
[[package]]
name = "rand_hc"
version = "0.2.0"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c"
dependencies = [
"rand_core",
"rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "rand_isaac"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "rand_pcg"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "rand_xorshift"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "redox_syscall"
version = "0.1.56"
version = "0.1.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84"
[[package]]
name = "regex"
version = "1.3.9"
name = "redox_termios"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c3780fcf44b193bc4d09f36d2a3c87b251da4a046c87795a0d35f4f927ad8e6"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
"thread_local",
"redox_syscall 0.1.43 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "regex-syntax"
version = "0.6.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26412eb97c6b088a6997e05f69403a802a92d520de2f8e63c2b65f9e0f47c4e8"
[[package]]
name = "remove_dir_all"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "rustc-demangle"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "rustc_version"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "semver"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "semver-parser"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "simplelog"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7"
dependencies = [
"winapi",
]
[[package]]
name = "serde"
version = "1.0.113"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6135c78461981c79497158ef777264c51d9d0f4f3fc3a4d22b915900e42dac6a"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.113"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93c5eaa17d0954cb481cdcfffe9d84fcfa7a1a9f2349271e678677be4c26ae31"
dependencies = [
"proc-macro2",
"quote",
"syn",
"chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"term 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "strsim"
version = "0.8.0"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
[[package]]
name = "structopt"
version = "0.3.15"
version = "0.2.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de2f5e239ee807089b62adce73e48c625e0ed80df02c7ab3f068f5db5281065c"
dependencies = [
"clap",
"lazy_static",
"structopt-derive",
"clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)",
"structopt-derive 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "structopt-derive"
version = "0.4.8"
version = "0.2.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "510413f9de616762a4fbeab62509bf15c729603b72d7cd71280fbca431b1c118"
dependencies = [
"heck",
"proc-macro-error",
"proc-macro2",
"quote",
"syn",
"heck 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
"proc-macro2 0.4.24 (registry+https://github.com/rust-lang/crates.io-index)",
"quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)",
"syn 0.15.22 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "syn"
version = "1.0.31"
version = "0.15.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5304cfdf27365b7585c25d4af91b35016ed21ef88f17ced89c7093b43dba8b6"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
"proc-macro2 0.4.24 (registry+https://github.com/rust-lang/crates.io-index)",
"quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)",
"unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "syn-mid"
version = "0.5.0"
name = "synstructure"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7be3539f6c128a931cf19dcee741c1af532c7fd387baa739c03dd2e96479338a"
dependencies = [
"proc-macro2",
"quote",
"syn",
"proc-macro2 0.4.24 (registry+https://github.com/rust-lang/crates.io-index)",
"quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)",
"syn 0.15.22 (registry+https://github.com/rust-lang/crates.io-index)",
"unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "tempfile"
version = "3.1.0"
version = "3.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a6e24d9338a0a5be79593e2fa15a648add6138caa803e2d5bc782c371732ca9"
dependencies = [
"cfg-if",
"libc",
"rand",
"redox_syscall",
"remove_dir_all",
"winapi",
"cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"rand 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)",
"redox_syscall 0.1.43 (registry+https://github.com/rust-lang/crates.io-index)",
"remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "termcolor"
version = "1.1.0"
name = "term"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb6bfa289a4d7c5766392812c0a1f4c1ba45afa1ad47803c11e1f407d846d75f"
dependencies = [
"winapi-util",
"byteorder 1.2.7 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "terminal_size"
version = "0.1.15"
name = "termion"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4bd2d183bd3fac5f5fe38ddbeb4dc9aec4a39a9d7d59e7491d900302da01cbe1"
dependencies = [
"libc",
"winapi",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"redox_syscall 0.1.43 (registry+https://github.com/rust-lang/crates.io-index)",
"redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "textwrap"
version = "0.11.0"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"
dependencies = [
"unicode-width",
"unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "thiserror"
version = "1.0.20"
name = "time"
version = "0.1.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dfdd070ccd8ccb78f4ad66bf1982dc37f620ef696c6b5028fe2ed83dd3d0d08"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd80fc12f73063ac132ac92aceea36734f04a1d93c1240c6944e23a3b8841793"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "thread_local"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d40c6d1b69745a6ec6fb1ca717914848da4b44ae29d9b3080cbee91d72a69b14"
dependencies = [
"lazy_static",
]
[[package]]
name = "toml"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffc92d160b1eef40665be3a05630d003936a3bc7da7421277846c2613e92c71a"
dependencies = [
"serde",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"redox_syscall 0.1.43 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "unicode-segmentation"
version = "1.6.0"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e83e153d1053cbb5a118eeff7fd5be06ed99153f00dbcd8ae310c5fb2b22edc0"
[[package]]
name = "unicode-width"
version = "0.1.7"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caaa9d531767d1ff2150b9332433f32a24622147e5ebb1f26409d5da67afd479"
[[package]]
name = "unicode-xid"
version = "0.2.0"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c"
[[package]]
name = "utf8-width"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9071ac216321a4470a69fb2b28cfc68dcd1a39acd877c8be8e014df6772d8efa"
[[package]]
name = "vec_map"
version = "0.8.2"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
[[package]]
name = "version_check"
version = "0.9.2"
name = "void"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed"
[[package]]
name = "wasi"
version = "0.9.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"
[[package]]
name = "which"
version = "4.0.0"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd3edc3cf5458851a4d6a2329232bd5f42c7f9bbe4c4782c4ef9ce37e5d101b2"
dependencies = [
"libc",
"thiserror",
"failure 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "winapi"
version = "0.3.8"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
"winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
dependencies = [
"winapi",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "zeroize"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45af6a010d13e4cf5b54c94ba5a2b2eba5596b9e46bf5875612d332a1f2b3f86"
[metadata]
"checksum ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b"
"checksum atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "9a7d5b8723950951411ee34d271d99dddcc2035a16ab25310ea2c8cfd4369652"
"checksum backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)" = "89a47830402e9981c5c41223151efcced65a0510c13097c769cede7efb34782a"
"checksum backtrace-sys 0.1.24 (registry+https://github.com/rust-lang/crates.io-index)" = "c66d56ac8dabd07f6aacdaf633f4b8262f5b3601a810a0dcddffd5c22c69daa0"
"checksum bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "228047a76f468627ca71776ecdebd732a3423081fcf5125585bcd7c49886ce12"
"checksum byteorder 1.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "94f88df23a25417badc922ab0f5716cc1330e87f71ddd9203b3a3ccd9cedf75d"
"checksum cc 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)" = "f159dfd43363c4d08055a07703eb7a3406b0dac4d0584d96965a3262db3c9d16"
"checksum cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "082bb9b28e00d3c9d39cc03e64ce4cea0f1bb9b3fde493f0cbc008472d22bdf4"
"checksum chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "45912881121cb26fad7c38c17ba7daa18764771836b34fab7d3fbd93ed633878"
"checksum clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b957d88f4b6a63b9d70d5f454ac8011819c6efa7727858f458ab71c756ce2d3e"
"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f"
"checksum failure 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "6dd377bcc1b1b7ce911967e3ec24fa19c3224394ec05b54aa7b083d498341ac7"
"checksum failure_derive 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "64c2d913fe8ed3b6c6518eedf4538255b989945c14c2a7d5cbff62a5e2120596"
"checksum fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82"
"checksum fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7"
"checksum heck 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ea04fa3ead4e05e51a7c806fc07271fdbde4e246a6c6d1efd52e72230b771b82"
"checksum libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)" = "10923947f84a519a45c8fefb7dd1b3e8c08747993381adee176d7a82b4195311"
"checksum log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c84ec4b527950aa83a329754b01dbe3f58361d1c5efacd1f6d68c494d08a17c6"
"checksum nix 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "921f61dc817b379d0834e45d5ec45beaacfae97082090a49c2cf30dcbc30206f"
"checksum num-integer 0.1.39 (registry+https://github.com/rust-lang/crates.io-index)" = "e83d528d2677f0518c570baf2b7abdcf0cd2d248860b68507bdcb3e91d4c0cea"
"checksum num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "0b3a5d7cc97d6d30d8b9bc8fa19bf45349ffe46241e8816f50f62f6d6aaabee1"
"checksum proc-macro2 0.4.24 (registry+https://github.com/rust-lang/crates.io-index)" = "77619697826f31a02ae974457af0b29b723e5619e113e9397b8b82c6bd253f09"
"checksum quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)" = "53fa22a1994bd0f9372d7a816207d8a2677ad0325b073f5c5332760f0fb62b5c"
"checksum rand 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ae9d223d52ae411a33cf7e54ec6034ec165df296ccd23533d671a28252b6f66a"
"checksum rand_chacha 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "771b009e3a508cb67e8823dda454aaa5368c7bc1c16829fb77d3e980440dd34a"
"checksum rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0905b6b7079ec73b314d4c748701f6931eb79fd97c668caa3f1899b22b32c6db"
"checksum rand_hc 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7b40677c7be09ae76218dc623efbf7b18e34bced3f38883af07bb75630a21bc4"
"checksum rand_isaac 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ded997c9d5f13925be2a6fd7e66bf1872597f759fd9dd93513dd7e92e5a5ee08"
"checksum rand_pcg 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "086bd09a33c7044e56bb44d5bdde5a60e7f119a9e95b0775f545de759a32fe05"
"checksum rand_xorshift 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "effa3fcaa47e18db002bdde6060944b6d2f9cfd8db471c30e873448ad9187be3"
"checksum redox_syscall 0.1.43 (registry+https://github.com/rust-lang/crates.io-index)" = "679da7508e9a6390aeaf7fbd02a800fdc64b73fe2204dd2c8ae66d22d9d5ad5d"
"checksum redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7e891cfe48e9100a70a3b6eb652fef28920c117d366339687bd5576160db0f76"
"checksum remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3488ba1b9a2084d38645c4c08276a1752dcbf2c7130d74f1569681ad5d2799c5"
"checksum rustc-demangle 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "bcfe5b13211b4d78e5c2cadfebd7769197d95c639c35a50057eb4c05de811395"
"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"
"checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403"
"checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"
"checksum simplelog 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2e95345f185d5adeb8ec93459d2dc99654e294cc6ccf5b75414d8ea262de9a13"
"checksum strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bb4f380125926a99e52bc279241539c018323fab05ad6368b56f93d9369ff550"
"checksum structopt 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)" = "41c4a2479a078509940d82773d90ff824a8c89533ab3b59cd3ce8b0c0e369c02"
"checksum structopt-derive 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)" = "5352090cfae7a2c85e1a31146268b53396106c88ca5d6ccee2e3fae83b6e35c2"
"checksum syn 0.15.22 (registry+https://github.com/rust-lang/crates.io-index)" = "ae8b29eb5210bc5cf63ed6149cbf9adfc82ac0be023d8735c176ee74a2db4da7"
"checksum synstructure 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "73687139bf99285483c96ac0add482c3776528beac1d97d444f6e91f203a2015"
"checksum tempfile 3.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "7e91405c14320e5c79b3d148e1c86f40749a36e490642202a31689cb1a3452b2"
"checksum term 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5e6b677dd1e8214ea1ef4297f85dbcbed8e8cdddb561040cc998ca2551c37561"
"checksum termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "689a3bdfaab439fd92bc87df5c4c78417d3cbe537487274e9b0b2dce76e92096"
"checksum textwrap 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "307686869c93e71f94da64286f9a9524c0f308a9e1c87a583de8e9c9039ad3f6"
"checksum time 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)" = "d825be0eb33fda1a7e68012d51e9c7f451dc1a69391e7fdc197060bb8c56667b"
"checksum unicode-segmentation 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "aa6024fc12ddfd1c6dbc14a80fa2324d4568849869b779f6bd37e5e4c03344d1"
"checksum unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "882386231c45df4700b275c7ff55b6f3698780a650026380e72dabe76fa46526"
"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc"
"checksum vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "05c78687fb1a80548ae3250346c3db86a80a7cdd77bda190189f2d0a0987c81a"
"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d"
"checksum which 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b57acb10231b9493c8472b20cb57317d0679a49e0bdbee44b3b803a6473af164"
"checksum winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "92c1eb33641e276cfa214a0522acad57be5c56b10cb348b3c5117db75f3ac4b0"
"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"

View File

@ -1,20 +1,13 @@
[package]
name = "alma"
version = "0.10.0"
version = "0.4.0"
authors = ["Roey Darwish Dror"]
edition = "2018"
[dependencies]
which = "4"
log = "0.4"
structopt = "0.3"
tempfile = "3"
serde = { version = "1", features = ["derive"] }
toml = "0.5"
byte-unit = "4.0"
nix = "0.19"
env_logger = "0.8"
pretty_env_logger = "0.4"
dialoguer = "0.7"
console = "0.13"
anyhow = "1"
which = "2.0.1"
failure = "0.1.3"
log = "0.4.6"
structopt = "0.2.13"
simplelog = "0.5.3"
tempfile = "3.0.5"
nix = "0.12.0"

View File

@ -1,11 +0,0 @@
FROM rust AS builder
ADD . /src
WORKDIR /src
RUN cargo build --release
FROM archlinux/base
RUN pacman -Sy --needed --noconfirm gptfdisk parted arch-install-scripts dosfstools coreutils util-linux cryptsetup
COPY --from=builder /src/target/release/alma /usr/bin/alma
CMD alma
WORKDIR /work

View File

@ -1,36 +0,0 @@
# Maintainer: James McMurray <jamesmcm03@gmail.com>
# Contributor: Roey Darwish Dror <roey.ghost@gmail.com>
_pkgname="alma"
pkgname="alma-git"
pkgver=r108.3ca2e01
pkgrel=1
pkgdesc='Create Arch Linux based live USB'
arch=('x86_64')
url='https://github.com/philmmanjaro/alma'
license=('GPL3')
makedepends=('git' 'rust')
depends=('gptfdisk' 'parted' 'arch-install-scripts' 'dosfstools' 'coreutils' 'util-linux')
optdepends=('cryptsetup: for root filesystem encryption')
source=("git+https://github.com/philmmanjaro/${_pkgname}")
provides=('alma')
conflicts=('alma')
sha256sums=('SKIP')
pkgver() {
cd "${srcdir}/${_pkgname}"
printf "r%s.%s" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
}
build() {
cd "${srcdir}/${_pkgname}"
cargo build --release
}
package() {
cd "${srcdir}/${_pkgname}"
install -Dm755 target/release/${_pkgname} "${pkgdir}/usr/bin/${_pkgname}"
install -Dm644 LICENSE "${pkgdir}/usr/share/licenses/${_pkgname}/LICENSE"
}

184
README.md
View File

@ -1,29 +1,29 @@
# ALMA - Arch Linux Mobile Appliance
Almost every live Linux distribution out there is meant for a specific purpose, whether it's data
rescue, privacy, penetration testing or anything else. There are some more generic distributions
but all of them are based on squashfs, meaning that changes don't persist reboots.
ALMA is meant for those who wish to have a **mutable** live environment. It installs Arch
Linux into a USB or an SD card, almost as if it was a hard drive. Some configuration is applied in
order to minimize writes to the USB and making sure the system is bootable on both BIOS and UEFI
systems.
Upgrading your packages is as easy as running `pacman -Syu` (or [Topgrade](https://github.com/r-darwish/topgrade/)) while the system is
booted. This tool also provides an easy chroot command, so you can keep your live environment up to
date without having to boot it. Encrypting the root partition is as easy as providing the `-e` flag
This tool installs Arch Linux into a USB drive, making it a customized live Arch Linux bootable
drive. It was inspired by [this](http://valleycat.org/linux/arch-usb.html) article. The USB drive
should be bootable both by UEFI and legacy boot.
## Installation
You can either build the project using cargo build or install the `alma` package from AUR.
### Using Arch Linux derivatives
## Requirements
Using Arch Linux derivatives, is supported with this ALMA fork. You may edit the base.toml as needed.
This tool should be ran from an exiting Arch Linux installations. It depends on the following tools:
* sgdisk
* partprobe
* Arch install scripts
* mkfs.fat
* mkfs.ext4
* *Optional*: cryptsetup
Dependencies will be handled for you if you install alma from AUR.
## Usage
### Image creation on removable device
### Creation
``` shell
sudo alma create /dev/disk/by-id/usb-Generic_USB_Flash_Disk-0:0
```
@ -31,154 +31,34 @@ sudo alma create /dev/disk/by-id/usb-Generic_USB_Flash_Disk-0:0
This will wipe the entire disk and create a bootable installation of Arch Linux. You can use either
removable devices or loop devices. As a precaution, ALMA will not wipe non-removable devices.
Not specifying any path will cause ALMA to interactively prompt the user for a removable device.
### Disk encryption
You can enable disk encryption with the `-e` flag:
``` shell
sudo alma create -e /dev/disk/by-id/usb-Generic_USB_Flash_Disk-0:0
```
You will be prompted to enter and confirm the encryption passphrase during image creation.
### chroot
After the installation is done you can either boot from it immediately or use `arch-chroot` to
perform further customizations before your first boot (e.g. installing wireless device drivers).
perform further customizations before your first boot.
You can run `arch-chroot` via ALMA:
### Chrooting to exiting Live USB
``` shell
sudo alma chroot /dev/disk/by-id/usb-Generic_USB_Flash_Disk-0:0
```
### Create raw image and boot in qemu
### Flags
* `-p / --extra-packages` - Specify extra packages to install. For example: `-p htop tmux`
* `-i / --interactive` - Drop you into interactive chroot to perform further customization
* `-e / --encrypted-root` - Encrypt the root filesystem.
For development and testing it may be useful to generate and boot the image in qemu.
## What exactly does it do?
Creating a 10GiB raw image, with disk encryption:
This tool doesn't aspire to be a generic installer for Arch Linux. Instead, it does the minimum
steps required to create a bootable USB with a few tweaks.
``` shell
sudo alma create -e --image 10GiB almatest.img
```
If you receive the following error:
```
Error setting up a loop device: losetup: cannot find an unused loop device
```
Check that you are running ALMA with sudo privileges, and reboot if you have installed a kernel update since your last reboot.
Mounting the raw image to a loop device:
``` shell
sudo losetup -f ./almatest.img
```
Check loop device:
``` shell
sudo losetup -j ./almatest.img
```
```
/dev/loop0: [2070]:6865917 (/path/to/image/almatest.img)
```
Note that your loop device number may differ.
Run qemu via ALMA:
``` shell
sudo alma qemu /dev/loop0
```
This will boot the image in qemu.
## Presets
Reproducing a build can be easily done using a preset file.
Preset files are simple TOML files which contain:
* A list of packages to install: `packages = ["mypackage"]`
* A post-installation script: `script = """ ... """`
* Environment variables required by the preset (e.g. used in the script): `enironment_variables = ["USERNAME"]`
* A list of shared directories `shared_directories = ["subdirectory"]` - where subdirectory would be available at `/shared_dirs/subdirectory/` for use in the script of the preset.
See the presets directory for examples.
Presets are used via the `--presets` argument (multiple preset files or directories may be provided):
``` shell
sudo ALMA_USER=archie alma create /dev/disk/by-id/usb-Generic_USB_Flash_Disk-0:0 --presets ./presets/user.toml ./presets/custom_preset.toml
```
Preset scripts are executed in the same order they are provided.
If a directory is provided, then all files and subdirectories in the directory are recursively crawled in alphanumeric order (all files must be ALMA .toml files). This allows you to use the following structure to compose many scripts in a specific order:
```
.
├── 00-add_user.toml
├── 01-xorg
│   ├── 00-install.toml
│   └── 01-config.toml
└── 02-i3
├── 00-install.toml
└── 01-copy_dotfiles.toml
```
Example preset TOML:
``` toml
packages = ["sudo"]
script = """
set -eux
useradd -m ${ALMA_USER}
passwd ${ALMA_USER}
usermod -G wheel -a ${ALMA_USER}
echo "%wheel ALL=(ALL) ALL" > /etc/sudoers.d/wheel
"""
environment_variables = ["ALMA_USER"]
```
Note that shared directories in the preset scripts are mounted as bind mounts, so they are *not* mounted read-only. Any changes the custom script makes to the shared directory will be carried out in the preset shared directory of the host system, so be sure to copy (not move) files from the shared directories.
### Order of execution
ALMA installs the packages and presets in the following order:
1. All non-AUR packages are installed
2. If AUR packages are present in the toml files, yay (or another
specified AUR helper) is installed
3. All AUR packages are installed.
4. Preset scripts are executed according to their filenames in
alphanumeric order.
Note this may mean you have to workaround some package installations if
they depend on preset scripts.
For example, at the moment you cannot install Rust-based AUR packages in
the `aur_packages` array of the Preset TOMLs if you use rustup,
since rustup needs to be given the toolchain to
install first. This can be worked around by carrying out the AUR
package installation inside the preset script itself in these cases.
## Troubleshooting
### mkinitcpio: /etc/mkinitcpio.d/linux.preset: No such file or directory
Ensure you have both the `linux` and `base` packages installed. Note
that only Arch Linux is supported, not Arch Linux derivatives such as
Manjaro.
### Problem opening /dev/... for reading! Error is 123.
Delete all partitions on the disk first (e.g. with gparted) and try
again.
1. Partition the disk as suggested [here](http://valleycat.org/linux/arch-usb.html). The last
partition will be formatted as ext4
1. Bootstrap the system using `pacstrap -c`. The `-c` flag will use the host's cache instead the
drive's cache, which will speed up things when you create multiple drives. This tool will install
the base system, grub, intel-ucode and NetworkManager
1. Generate initramfs without the `autodetect` hook
1. Set NetworkManager to start at boot
1. Install GRUB in both legacy and UEFI modes
## Similar projects
* [NomadBSD](http://nomadbsd.org/)
## Useful Resources
* [Arch Wiki: Installing Arch Linux on a USB key](https://wiki.archlinux.org/index.php/Install_Arch_Linux_on_a_USB_key)
* [ValleyCat's Arch Linux USB guide](http://valleycat.org/linux/arch-usb.html?i=1)

View File

@ -1 +0,0 @@
packages = ["alsa-firmware", "alsa-utils", "pavucontrol", "pulseaudio-bluetooth", "pulseaudio-ctl", "pulseaudio-zeroconf"]

View File

@ -1,2 +0,0 @@
packages = ["clang"]
aur_packages = ["bat-cat-git"]

View File

@ -1 +0,0 @@
packages = ["linux61", "linux61-broadcom-wl", "linux-firmware", "grub", "efibootmgr", "intel-ucode", "amd-ucode", "networkmanager"]

View File

@ -1,5 +0,0 @@
script = """
ls /shared_dirs/copy_file_example/
cp /shared_dirs/copy_file_example/testfile.txt /root/
"""
shared_directories = ["copy_file_example"]

View File

@ -1 +0,0 @@
test

View File

@ -1,11 +0,0 @@
packages = ["plasma-desktop", "plasma-nm", "plasma-pa", "dolphin", "gwenview", "konsole", "ttf-dejavu", "sddm", "kate", "xdg-desktop-portal-kde", "discover", "falkon"]
script = """
set -exu
systemctl enable sddm
# Set theme
mkdir -p /etc/sddm.conf.d
echo "[Theme]" > /etc/sddm.conf.d/00_theme_settings.conf
echo "Current=breeze" >> /etc/sddm.conf.d/00_theme_settings.conf
"""

View File

@ -1,9 +0,0 @@
packages = ["pamac-gtk", "pamac-snap-plugin", "pamac-flatpak-plugin"]
script = """
set -exu
systemctl enable apparmor
systemctl enable snapd.apparmor
systemctl enable snapd
"""

View File

@ -1 +0,0 @@
../base.toml

View File

@ -1 +0,0 @@
../xorg.toml

View File

@ -1 +0,0 @@
../user.toml

View File

@ -1 +0,0 @@
../kde.toml

View File

@ -1 +0,0 @@
../steam.toml

View File

@ -1 +0,0 @@
../audio.toml

View File

@ -1 +0,0 @@
../base.toml

View File

@ -1 +0,0 @@
../xorg.toml

View File

@ -1 +0,0 @@
../user.toml

View File

@ -1 +0,0 @@
../kde.toml

View File

@ -1 +0,0 @@
../audio.toml

View File

@ -1,13 +0,0 @@
packages = ["steam", "gamescope-session-git", "gamescope-plus", "wget", "vulkan-icd-loader", "lib32-vulkan-icd-loader", "vulkan-intel", "lib32-vulkan-intel", "vulkan-radeon", "lib32-vulkan-radeon", "ttf-liberation", "adobe-source-sans-pro-fonts", "adobe-source-han-sans-jp-fonts", "adobe-source-han-sans-kr-fonts", "adobe-source-han-sans-cn-fonts"]
script = """
set -eux
wget -v https://gitlab.com/evlaV/jupiter_steam-jupiter-stable-PKGBUILD/-/raw/5cd60f3cd66527a95f93e6fefd9371fd659a5aea/steam_jupiter_stable_bootstrapped_20230316.1.tar.xz -O /usr/lib/steam/bootstraplinux_ubuntu12_32.tar.xz
mkdir -p /etc/sddm.conf.d
echo "# Created by Manjaro ALMA" > /etc/sddm.conf.d/99-autologin.conf
echo "[Autologin]" >> /etc/sddm.conf.d/99-autologin.conf
echo "User=${ALMA_USER}" >> /etc/sddm.conf.d/99-autologin.conf
echo "Session=gamescope-session.desktop" >> /etc/sddm.conf.d/99-autologin.conf
"""
environment_variables = ["ALMA_USER"]

View File

@ -1,9 +0,0 @@
packages = ["sudo"]
script = """
set -eux
useradd -m ${ALMA_USER} -p $(openssl passwd -6 ${ALMA_USER_PASSWORD})
usermod -G users,lp,video,network,storage,wheel,audio -a ${ALMA_USER}
echo "%wheel ALL=(ALL) ALL" > /etc/sudoers.d/wheel
"""
environment_variables = ["ALMA_USER", "ALMA_USER_PASSWORD"]

View File

@ -1,5 +0,0 @@
packages = ["manjaro-xfce-settings", "manjaro-hello", "manjaro-application-utility", "manjaro-settings-manager-notifier", "manjaro-documentation-en", "manjaro-browser-settings", "manjaro-release", "manjaro-firmware", "manjaro-system"]
script = """
cp /shared_dirs/xfce-branding/lightdm-gtk-greeter.conf /etc/lightdm/lightdm-gtk-greeter.conf
"""
shared_directories = ["xfce-branding"]

View File

@ -1,16 +0,0 @@
[greeter]
background = /usr/share/backgrounds/illyria-default-lockscreen.jpg
user-background = false
font-name = Cantarell Bold 12
xft-antialias = true
icon-theme-name = Adapta-Papirus-Maia
screensaver-timeout = 60
theme-name = Matcha-sea
cursor-theme-name = xcursor-breeze
show-clock = false
default-user-image = #manjaro
xft-hintstyle = hintfull
position = 50%,center 57%,center
clock-format =
panel-position = bottom
indicators = ~host;~spacer;~clock;~spacer;~language;~session;~a11y;~power

View File

@ -1,2 +0,0 @@
packages = ["xfce4-goodies", "xfce4-pulseaudio-plugin", "pulseaudio", "pavucontrol", "mugshot", "engrampa", "catfish", "firefox", "screenfetch", "thunderbird", "network-manager-applet"]

View File

@ -1 +0,0 @@
../base.toml

View File

@ -1 +0,0 @@
../xorg.toml

View File

@ -1 +0,0 @@
../user.toml

View File

@ -1 +0,0 @@
../xfce.toml

View File

@ -1 +0,0 @@
../xfce-goodies.toml

View File

@ -1 +0,0 @@
../xfce-branding.toml

View File

@ -1 +0,0 @@
../pamac.toml

View File

@ -1 +0,0 @@
../audio.toml

View File

@ -1 +0,0 @@
../xfce-branding

View File

@ -1,6 +0,0 @@
packages = ["xfce4", "ttf-dejavu", "lightdm-gtk-greeter-settings", "accountsservice"]
script = """
set -exu
systemctl enable lightdm
"""

View File

@ -1 +0,0 @@
../base.toml

View File

@ -1 +0,0 @@
../xorg.toml

View File

@ -1 +0,0 @@
../user.toml

View File

@ -1 +0,0 @@
../xfce.toml

View File

@ -1 +0,0 @@
../audio.toml

View File

@ -1 +0,0 @@
packages = ["xf86-input-libinput", "xf86-video-amdgpu", "xf86-video-ati", "xf86-video-nouveau", "xorg-server", "xterm"]

53
src/alma.rs Normal file
View File

@ -0,0 +1,53 @@
use super::block::BlockDevice;
use super::cryptsetup::EncryptedDevice;
use super::error::{Error, ErrorKind};
use super::mountstack::{Filesystem, MountStack};
use failure::ResultExt;
use log::{debug, info};
use std::fs;
use std::path::{Path, PathBuf};
pub struct ALMA<'a> {
block: BlockDevice,
encrypted_root: Option<EncryptedDevice<'a>>,
}
impl<'a> ALMA<'a> {
pub fn new(block: BlockDevice, encrypted_root: Option<EncryptedDevice<'a>>) -> Self {
Self {
block,
encrypted_root,
}
}
pub fn mount<'b>(&self, path: &'b Path) -> Result<MountStack<'b>, Error> {
let mut mount_stack = MountStack::new();
let root_device = if let Some(encrypted_root) = &self.encrypted_root {
PathBuf::from(encrypted_root.path())
} else {
self.block.partition_device_path(3)?
};
debug!("Root partition: {}", root_device.display());
info!("Mounting filesystems to {}", path.display());
mount_stack
.mount(&root_device, path, Filesystem::Ext4, None)
.context(ErrorKind::Mounting)?;
let boot_point = path.join("boot");
if !boot_point.exists() {
fs::create_dir(&boot_point).context(ErrorKind::CreateBoot)?;
}
mount_stack
.mount(
&self.block.partition_device_path(2)?,
boot_point,
Filesystem::Vfat,
None,
).context(ErrorKind::Mounting)?;
Ok(mount_stack)
}
}

View File

@ -1,119 +0,0 @@
use super::aur::AurHelper;
use byte_unit::Byte;
use std::path::PathBuf;
use structopt::StructOpt;
/// Parse size argument as bytes
/// e.g. 10GB, 10GiB, etc.
fn parse_bytes(src: &str) -> Result<Byte, &'static str> {
Byte::from_str(src).map_err(|_| "Invalid image size")
}
#[derive(StructOpt)]
#[structopt(name = "alma", about = "Arch Linux Mobile Appliance")]
pub struct App {
/// Verbose output
#[structopt(short = "v", long = "verbose")]
pub verbose: bool,
#[structopt(subcommand)]
pub cmd: Command,
}
#[derive(StructOpt)]
pub enum Command {
#[structopt(name = "create", about = "Create a new Arch Linux USB")]
Create(CreateCommand),
#[structopt(name = "chroot", about = "Chroot into exiting Live USB")]
Chroot(ChrootCommand),
#[structopt(name = "qemu", about = "Boot the USB with Qemu")]
Qemu(QemuCommand),
}
#[derive(StructOpt)]
pub struct CreateCommand {
/// Either a path to a removable block device or a nonexiting file if --image is specified
#[structopt(parse(from_os_str))]
pub path: Option<PathBuf>,
/// Path to a pacman.conf file which will be used to pacstrap packages into the image.
///
/// This pacman.conf will also be copied into the resulting Arch Linux image.
#[structopt(short = "c", long = "pacman-conf", value_name = "pacman_conf")]
pub pacman_conf: Option<PathBuf>,
/// Additional packages to install
#[structopt(short = "p", long = "extra-packages", value_name = "package")]
pub extra_packages: Vec<String>,
/// Additional packages to install
#[structopt(long = "aur-packages", value_name = "aurpackage")]
pub aur_packages: Vec<String>,
/// Boot partition size in megabytes
#[structopt(long = "boot-size")]
pub boot_size: Option<u32>,
/// Enter interactive chroot before unmounting the drive
#[structopt(short = "i", long = "interactive")]
pub interactive: bool,
/// Encrypt the root partition
#[structopt(short = "e", long = "encrypted-root")]
pub encrypted_root: bool,
/// Path to preset files
#[structopt(long = "presets", value_name = "preset")]
pub presets: Vec<PathBuf>,
/// Create an image with a certain size in the given path instead of using an actual block device
#[structopt(
long = "image",
parse(try_from_str = parse_bytes),
value_name = "size",
requires = "path"
)]
pub image: Option<Byte>,
/// Overwrite existing image files. Use with caution!
#[structopt(long = "overwrite")]
pub overwrite: bool,
/// Allow installation on non-removable devices. Use with extreme caution!
///
/// If no device is specified in the command line, the device selection menu will
/// show non-removable devices
#[structopt(long = "allow-non-removable")]
pub allow_non_removable: bool,
#[structopt(long = "aur-helper", possible_values=&["paru", "yay"], default_value="paru")]
pub aur_helper: AurHelper,
}
#[derive(StructOpt)]
pub struct ChrootCommand {
/// Path starting with /dev/disk/by-id for the USB drive
#[structopt(parse(from_os_str))]
pub block_device: PathBuf,
/// Allow installation on non-removable devices. Use with extreme caution!
#[structopt(long = "allow-non-removable")]
pub allow_non_removable: bool,
/// Optional command to run
#[structopt()]
pub command: Vec<String>,
}
#[derive(StructOpt)]
pub struct QemuCommand {
/// Path starting with /dev/disk/by-id for the USB drive
#[structopt(parse(from_os_str))]
pub block_device: PathBuf,
/// Arguments to pass to qemu
#[structopt()]
pub args: Vec<String>,
}

View File

@ -1,60 +0,0 @@
use anyhow::anyhow;
use std::str::FromStr;
pub struct AurHelper {
pub name: String,
pub package_name: String,
pub install_command: Vec<String>,
}
impl FromStr for AurHelper {
type Err = anyhow::Error;
fn from_str(s: &str) -> anyhow::Result<Self> {
match s {
"paru" => Ok(Self {
name: String::from("paru"),
package_name: String::from("paru-bin"),
install_command: vec![
String::from("paru"),
String::from("-S"),
String::from("--skipreview"),
String::from("--noupgrademenu"),
String::from("--useask"),
String::from("--removemake"),
String::from("--norebuild"),
String::from("--nocleanafter"),
String::from("--noredownload"),
String::from("--mflags"),
String::from(""),
String::from("--noconfirm"),
String::from("--batchinstall"),
],
}),
"yay" => Ok(Self {
name: String::from("yay"),
package_name: String::from("yay-bin"),
install_command: vec![
String::from("yay"),
String::from("-S"),
String::from("--nocleanmenu"),
String::from("--nodiffmenu"),
String::from("--noeditmenu"),
String::from("--noupgrademenu"),
String::from("--useask"),
String::from("--removemake"),
String::from("--norebuild"),
String::from("--answerdiff"),
String::from("None"),
String::from("--answeredit"),
String::from("None"),
String::from("--answerclean"),
String::from("None"),
String::from("--mflags"),
String::from("--noconfirm"),
],
}),
_ => Err(anyhow!("Error parsing AUR helper string: {}", s)),
}
}
}

79
src/block.rs Normal file
View File

@ -0,0 +1,79 @@
use super::error::{Error, ErrorKind};
use failure::ResultExt;
use log::debug;
use std::fs::read_to_string;
use std::path::PathBuf;
#[derive(Debug)]
pub struct BlockDevice {
name: String,
}
impl BlockDevice {
pub fn from_path(path: PathBuf) -> Result<Self, Error> {
let real_path = path.canonicalize().context(ErrorKind::DeviceQuery)?;
let device_name = real_path
.file_name()
.and_then(|s| s.to_str())
.map(String::from)
.ok_or_else(|| Error::from(ErrorKind::InvalidDeviceName))?;
debug!(
"path: {:?}, real path: {:?}, device name: {:?}",
path, real_path, device_name
);
drop(path);
let _self = Self { name: device_name };
if !(_self.is_removable()? || _self.is_loop_device()) {
return Err(ErrorKind::DangerousDevice)?;
}
Ok(_self)
}
fn sys_path(&self) -> PathBuf {
let mut path = PathBuf::from("/sys/block");
path.push(self.name.clone());
path
}
fn is_removable(&self) -> Result<bool, Error> {
let mut path = self.sys_path();
path.push("removable");
debug!("Reading: {:?}", path);
let result = read_to_string(&path).context(ErrorKind::DeviceQuery)?;
debug!("{:?} -> {}", path, result);
Ok(result == "1\n")
}
fn is_loop_device(&self) -> bool {
let mut path = self.sys_path();
path.push("loop");
path.exists()
}
pub fn device_path(&self) -> PathBuf {
let mut path = PathBuf::from("/dev");
path.push(self.name.clone());
path
}
pub fn partition_device_path(&self, index: u8) -> Result<PathBuf, Error> {
let name = if self.name.chars().rev().next().unwrap().is_digit(10) {
format!("{}p{}", self.name, index)
} else {
format!("{}{}", self.name, index)
};
let mut path = PathBuf::from("/dev");
path.push(name);
debug!("Partition {} for {} is in {:?}", index, self.name, path);
if !path.exists() {
return Err(ErrorKind::NoSuchPartition(index).into());
}
Ok(path)
}
}

View File

@ -1,12 +0,0 @@
pub const BOOT_PARTITION_INDEX: u8 = 1;
pub const ROOT_PARTITION_INDEX: u8 = 3;
pub static JOURNALD_CONF: &str = "
[Journal]
Storage=volatile
SystemMaxUse=16M
";
pub const BASE_PACKAGES: [&str; 1] = ["base"];
pub const AUR_DEPENDENCIES: [&str; 3] = ["base-devel", "git", "sudo"];

68
src/cryptsetup.rs Normal file
View File

@ -0,0 +1,68 @@
use super::error::{Error, ErrorKind};
use super::process::CommandExt;
use super::tool::Tool;
use log::{debug, warn};
use std::path::{Path, PathBuf};
pub struct EncryptedDevice<'a> {
cryptsetup: &'a Tool,
name: &'a str,
path: PathBuf,
}
impl<'a> EncryptedDevice<'a> {
pub fn prepare(cryptsetup: &Tool, device: &Path) -> Result<(), Error> {
debug!("Preparing encrypted device in {}", device.display());
cryptsetup
.execute()
.arg("luksFormat")
.arg("-q")
.arg(device)
.run(ErrorKind::LuksSetup)?;
Ok(())
}
pub fn open(
cryptsetup: &'a Tool,
device: &Path,
name: &'a str,
) -> Result<EncryptedDevice<'a>, Error> {
debug!("Opening encrypted device {} as {}", device.display(), name);
cryptsetup
.execute()
.arg("open")
.arg(device)
.arg(name)
.run(ErrorKind::LuksOpen)?;
Ok(Self {
cryptsetup,
name,
path: PathBuf::from("/dev/mapper").join(name),
})
}
fn _close(&mut self) -> Result<(), Error> {
debug!("Closing encrypted device {}", self.name);
self.cryptsetup
.execute()
.arg("close")
.arg(self.name)
.run(ErrorKind::LuksClose)?;
Ok(())
}
pub fn path(&self) -> &Path {
&self.path
}
}
impl<'a> Drop for EncryptedDevice<'a> {
fn drop(&mut self) {
if self._close().is_err() {
warn!("Error closing {}", self.name);
}
}
}

100
src/error.rs Normal file
View File

@ -0,0 +1,100 @@
use failure::{Backtrace, Context, Fail};
use std::fmt::{self, Display};
#[derive(Debug)]
pub struct Error {
inner: Context<ErrorKind>,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug, Fail)]
pub enum ErrorKind {
#[fail(display = "Error quering information about the block device")]
DeviceQuery,
#[fail(display = "Invalid device name")]
InvalidDeviceName,
#[fail(display = "The given block device is neither removable nor a loop device")]
DangerousDevice,
#[fail(display = "Partition {} does not exist", _0)]
NoSuchPartition(u8),
#[fail(display = "Could not find {}", _0)]
NoTool(&'static str),
#[fail(display = "Error creating a temporary directory")]
TmpDirError,
#[fail(display = "Partitioning error")]
Partitioning,
#[fail(display = "Error formatting filesystems")]
Formatting,
#[fail(display = "Error mounting filesystems")]
Mounting,
#[fail(display = "Error creating the boot directory")]
CreateBoot,
#[fail(display = "Pacstrap error")]
Pacstrap,
#[fail(display = "fstab error")]
Fstab,
#[fail(display = "Post installation configuration error")]
PostInstallation,
#[fail(display = "Initramfs error")]
Initramfs,
#[fail(display = "Bootloader error")]
Bootloader,
#[fail(display = "Error caused by the interactive mode")]
Interactive,
#[fail(display = "Failed umounting filesystems")]
UmountFailure,
#[fail(display = "Error setting up an encrypted device")]
LuksSetup,
#[fail(display = "Error opening the encrypted device")]
LuksOpen,
#[fail(display = "Error closing the encrypted device")]
LuksClose,
}
impl Fail for Error {
fn cause(&self) -> Option<&Fail> {
self.inner.cause()
}
fn backtrace(&self) -> Option<&Backtrace> {
self.inner.backtrace()
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&self.inner, f)
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Error {
Error {
inner: Context::new(kind),
}
}
}
impl From<Context<ErrorKind>> for Error {
fn from(inner: Context<ErrorKind>) -> Error {
Error { inner }
}
}

View File

@ -1,36 +0,0 @@
use std::fmt::Write;
pub struct Initcpio {
encrypted: bool,
plymouth: bool,
}
impl Initcpio {
pub fn new(encrypted: bool, plymouth: bool) -> Self {
Self {
encrypted,
plymouth,
}
}
pub fn to_config(&self) -> anyhow::Result<String> {
let mut output = String::from(
"MODULES=()
BINARIES=()
FILES=()
HOOKS=(base udev autodetect modconf kms keyboard keymap consolefont block ",
);
if self.encrypted {
output.write_str("encrypt ")?;
}
if self.plymouth {
output.write_str("filesystems plymouth)\n")?;
} else {
output.write_str("filesystems fsck)\n")?;
}
Ok(output)
}
}

View File

@ -1,62 +1,98 @@
mod args;
mod aur;
mod constants;
mod initcpio;
mod presets;
extern crate failure;
extern crate log;
extern crate nix;
extern crate simplelog;
extern crate structopt;
extern crate tempfile;
extern crate which;
use nix::sys::signal;
mod alma;
mod block;
mod cryptsetup;
mod error;
mod mountstack;
mod process;
mod storage;
mod tool;
use anyhow::{anyhow, Context};
use args::Command;
use byte_unit::Byte;
use console::style;
use dialoguer::{theme::ColorfulTheme, Select};
use log::{debug, error, info, log_enabled, Level, LevelFilter};
use alma::ALMA;
use cryptsetup::EncryptedDevice;
use error::*;
use failure::{Fail, ResultExt};
use log::{debug, error, info, warn};
use process::CommandExt;
use std::collections::HashSet;
use simplelog::*;
use std::fs;
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::Command as ProcessCommand;
use std::path::PathBuf;
use std::process::exit;
use std::thread;
use std::time::Duration;
use storage::EncryptedDevice;
use storage::{BlockDevice, Filesystem, FilesystemType, LoopDevice, MountStack};
use structopt::StructOpt;
use tempfile::tempdir;
use tool::Tool;
fn main() -> anyhow::Result<()> {
// Get struct of args using structopt
let app = args::App::from_args();
static MKINITCPIO: &'static str = "MODULES=()
BINARIES=()
FILES=()
HOOKS=(base udev keyboard consolefont block encrypt filesystems keyboard fsck)";
// Set up logging
let mut builder = pretty_env_logger::formatted_timed_builder();
let log_level = if app.verbose {
LevelFilter::Debug
} else {
LevelFilter::Info
};
builder.filter_level(log_level);
builder.init();
static JOURNALD_CONF: &'static str = "
[Journal]
Storage=volatile
SystemMaxUse=16M
";
// Match command from arguments and run relevant code
match app.cmd {
Command::Create(command) => create(command),
Command::Chroot(command) => tool::chroot(command),
Command::Qemu(command) => tool::qemu(command),
}?;
#[derive(StructOpt)]
#[structopt(name = "alma", about = "Arch Linux Mobile Appliance")]
struct App {
/// Verbose output
#[structopt(short = "v", long = "verbose")]
verbose: bool,
Ok(())
#[structopt(subcommand)]
cmd: Command,
}
#[derive(StructOpt)]
enum Command {
#[structopt(name = "create", about = "Create a new Arch Linux USB")]
Create(CreateCommand),
#[structopt(name = "chroot", about = "Chroot into exiting Live USB")]
Chroot(ChrootCommand),
}
#[derive(StructOpt)]
struct CreateCommand {
/// Path starting with /dev/disk/by-id for the USB drive
#[structopt(parse(from_os_str),)]
block_device: PathBuf,
/// Additional pacakges to install
#[structopt(short = "p", long = "extra-packages", value_name = "package",)]
extra_packages: Vec<String>,
/// Enter interactive chroot before unmounting the drive
#[structopt(short = "i", long = "interactive")]
interactive: bool,
/// Encrypt the root partition
#[structopt(short = "e", long = "encrypted-root")]
encrypted_root: bool,
}
#[derive(StructOpt)]
struct ChrootCommand {
/// Path starting with /dev/disk/by-id for the USB drive
#[structopt(parse(from_os_str),)]
block_device: PathBuf,
/// Open an encrypted root partition
#[structopt(short = "e", long = "encrypted-root")]
encrypted_root: bool,
}
/// Remove swap entry from fstab and any commented lines
/// Returns an owned String
///
/// # Arguments
/// * `fstab` - A string slice holding the contents of the fstab file
fn fix_fstab(fstab: &str) -> String {
fstab
.lines()
@ -65,57 +101,7 @@ fn fix_fstab(fstab: &str) -> String {
.join("\n")
}
/// Creates a file at the path provided, and mounts it to a loop device
fn create_image(path: &Path, size: Byte, overwrite: bool) -> anyhow::Result<LoopDevice> {
{
let mut options = fs::OpenOptions::new();
options.write(true);
if overwrite {
options.create(true);
} else {
options.create_new(true);
}
let file = options.open(path).context("Error creating the image")?;
file.set_len(size.get_bytes() as u64)
.context("Error creating the image")?;
}
LoopDevice::create(path)
}
/// Requests selection of block device (no device was given in the arguments)
fn select_block_device(allow_non_removable: bool) -> anyhow::Result<PathBuf> {
let devices = storage::get_storage_devices(allow_non_removable)?;
if devices.is_empty() {
return Err(anyhow!("There are no removable devices"));
}
if allow_non_removable {
println!(
"{}\n",
style("Showing non-removable devices. Make sure you select the correct device.")
.red()
.bold()
);
}
let selection = Select::with_theme(&ColorfulTheme::default())
.with_prompt("Select a removable device")
.default(0)
.items(&devices)
.interact()?;
Ok(PathBuf::from("/dev").join(&devices[selection].name))
}
/// Creates the installation
#[allow(clippy::cognitive_complexity)] // TODO: Split steps into functions and remove this
fn create(command: args::CreateCommand) -> anyhow::Result<()> {
let presets = presets::PresetsCollection::load(&command.presets)?;
fn create(command: CreateCommand) -> Result<(), Error> {
let sgdisk = Tool::find("sgdisk")?;
let pacstrap = Tool::find("pacstrap")?;
let arch_chroot = Tool::find("arch-chroot")?;
@ -133,375 +119,147 @@ fn create(command: args::CreateCommand) -> anyhow::Result<()> {
None
};
let storage_device_path = if let Some(path) = command.path {
path
} else {
select_block_device(command.allow_non_removable)?
};
let block_device = block::BlockDevice::from_path(command.block_device)?;
let image_loop = if let Some(size) = command.image {
Some(create_image(&storage_device_path, size, command.overwrite)?)
} else {
None
};
let mount_point = tempdir().context(ErrorKind::TmpDirError)?;
let storage_device = storage::StorageDevice::from_path(
image_loop
.as_ref()
.map(|loop_dev| {
info!("Using loop device at {}", loop_dev.path().display());
loop_dev.path()
})
.unwrap_or(&storage_device_path),
command.allow_non_removable,
)?;
let mount_point = tempdir().context("Error creating a temporary directory")?;
let disk_path = storage_device.path();
let disk_path = block_device.device_path();
info!("Partitioning the block device");
debug!("{:?}", disk_path);
let boot_size = command.boot_size.unwrap_or(300);
sgdisk
.execute()
.args([
.args(&[
"-Z",
"-o",
&format!("--new=1::+{}M", boot_size),
"--new=2::+1M",
"--new=1::+10M",
"--new=2::+150M",
"--largest-new=3",
"--typecode=1:EF00",
"--typecode=2:EF02",
])
.arg(disk_path)
.run()
.context("Partitioning error")?;
"--typecode=1:EF02",
"--typecode=2:EF00",
]).arg(&disk_path)
.run(ErrorKind::Partitioning)?;
thread::sleep(Duration::from_millis(1000));
info!("Formatting filesystems");
let boot_partition = storage_device.get_partition(constants::BOOT_PARTITION_INDEX)?;
let boot_filesystem = Filesystem::format(&boot_partition, FilesystemType::Vfat, &mkfat)?;
let boot_partition = block_device.partition_device_path(2)?;
mkfat
.execute()
.arg("-F32")
.arg(&boot_partition)
.run(ErrorKind::Formatting)?;
let root_partition_base = storage_device.get_partition(constants::ROOT_PARTITION_INDEX)?;
let root_partition = block_device.partition_device_path(3)?;
let encrypted_root = if let Some(cryptsetup) = &cryptsetup {
info!("Encrypting the root filesystem");
EncryptedDevice::prepare(cryptsetup, &root_partition_base)?;
EncryptedDevice::prepare(&cryptsetup, &root_partition)?;
Some(EncryptedDevice::open(
cryptsetup,
&root_partition_base,
"alma_root".into(),
&root_partition,
"alma_root",
)?)
} else {
None
};
let root_partition = if let Some(e) = encrypted_root.as_ref() {
e as &dyn BlockDevice
} else {
&root_partition_base as &dyn BlockDevice
};
mkext4
.execute()
.arg("-F")
.arg(if let Some(device) = &encrypted_root {
device.path()
} else {
&root_partition
}).run(ErrorKind::Formatting)?;
let root_filesystem = Filesystem::format(root_partition, FilesystemType::Ext4, &mkext4)?;
let mount_stack = tool::mount(mount_point.path(), &boot_filesystem, &root_filesystem)?;
if log_enabled!(Level::Debug) {
debug!("lsblk:");
ProcessCommand::new("lsblk")
.arg("--fs")
.spawn()
.and_then(|mut p| p.wait())
.map_err(|e| {
error!("Error running lsblk: {}", e);
})
.ok();
}
let mut packages: HashSet<String> = constants::BASE_PACKAGES
.iter()
.map(|s| String::from(*s))
.collect();
packages.extend(presets.packages);
let aur_packages = {
let mut p = vec![String::from("shim-signed")];
p.extend(presets.aur_packages);
p.extend(command.aur_packages);
p
};
packages.extend(constants::AUR_DEPENDENCIES.iter().map(|s| String::from(*s)));
let pacman_conf_path = command
.pacman_conf
.unwrap_or_else(|| "/etc/pacman.conf".into());
let alma = ALMA::new(block_device, encrypted_root);
let mount_stack = alma.mount(mount_point.path())?;
info!("Bootstrapping system");
pacstrap
.execute()
.arg("-C")
.arg(&pacman_conf_path)
.arg("-c")
.arg(mount_point.path())
.args(packages)
.args(&command.extra_packages)
.run()
.context("Pacstrap error")?;
// Copy pacman.conf to the image.
fs::copy(pacman_conf_path, mount_point.path().join("etc/pacman.conf"))
.context("Failed copying pacman.conf")?;
.args(&[
"base",
"grub",
"efibootmgr",
"intel-ucode",
"networkmanager",
"broadcom-wl",
]).args(&command.extra_packages)
.run(ErrorKind::Pacstrap)?;
let fstab = fix_fstab(
&genfstab
.execute()
.arg("-U")
.arg(mount_point.path())
.run_text_output()
.context("fstab error")?,
.run_text_output(ErrorKind::Fstab)?,
);
debug!("fstab:\n{}", fstab);
fs::write(mount_point.path().join("etc/fstab"), fstab).context("fstab error")?;
fs::write(mount_point.path().join("etc/fstab"), fstab).context(ErrorKind::Fstab)?;
arch_chroot
.execute()
.arg(mount_point.path())
.args(["passwd", "-d", "root"])
.run()
.context("Failed to delete the root password")?;
info!("Setting locale");
fs::OpenOptions::new()
.append(true)
.write(true)
.open(mount_point.path().join("etc/locale.gen"))
.and_then(|mut locale_gen| locale_gen.write_all(b"en_US.UTF-8 UTF-8\n"))
.context("Failed to create locale.gen")?;
fs::write(
mount_point.path().join("etc/locale.conf"),
"LANG=en_US.UTF-8",
)
.context("Failed to write to locale.conf")?;
arch_chroot
.execute()
.arg(mount_point.path())
.arg("locale-gen")
.run()
.context("locale-gen failed")?;
info!("Installing AUR packages");
arch_chroot
.execute()
.arg(mount_point.path())
.args(["useradd", "-m", "aur"])
.run()
.context("Failed to create temporary user to install AUR packages")?;
let aur_sudoers = mount_point.path().join("etc/sudoers.d/aur");
fs::write(&aur_sudoers, "aur ALL=(ALL) NOPASSWD: ALL")
.context("Failed to modify sudoers file for AUR packages")?;
arch_chroot
.execute()
.arg(mount_point.path())
.args(["sudo", "-u", "aur"])
.arg("git")
.arg("clone")
.arg(format!(
"https://aur.archlinux.org/{}.git",
&command.aur_helper.package_name
))
.arg(format!("/home/aur/{}", &command.aur_helper.name))
.run()
.context("Failed to clone AUR helper package")?;
arch_chroot
.execute()
.arg(mount_point.path())
.args([
"bash",
"-c",
&format!(
"cd /home/aur/{} && sudo -u aur makepkg -s -i --noconfirm",
&command.aur_helper.name
),
])
.run()
.context("Failed to build AUR helper")?;
arch_chroot
.execute()
.arg(mount_point.path())
.args(["sudo", "-u", "aur"])
.args(command.aur_helper.install_command)
.args(aur_packages)
.run()
.context("Failed to install AUR packages")?;
// Clean up aur user:
arch_chroot
.execute()
.arg(mount_point.path())
.args(["userdel", "-r", "aur"])
.run()
.context("Failed to delete temporary aur user")?;
fs::remove_file(&aur_sudoers).context("Cannot delete the AUR sudoers temporary file")?;
if !presets.scripts.is_empty() {
info!("Running custom scripts");
}
for script in presets.scripts {
let mut bind_mount_stack = MountStack::new();
if let Some(shared_dirs) = &script.shared_dirs {
for dir in shared_dirs {
// Create shared directories mount points inside chroot
std::fs::create_dir_all(
mount_point
.path()
.join(PathBuf::from("shared_dirs/"))
.join(dir.file_name().expect("Dir had no filename")),
)
.context("Failed mounting shared directories in preset")?;
// Bind mount shared directories
let target = mount_point
.path()
.join(PathBuf::from("shared_dirs/"))
.join(dir.file_name().expect("Dir had no filename"));
bind_mount_stack
.bind_mount(dir.clone(), target, None)
.context("Failed mounting shared directories in preset")?;
}
}
let mut script_file = tempfile::NamedTempFile::new_in(mount_point.path())
.context("Failed creating temporary preset script")?;
script_file
.write_all(script.script_text.as_bytes())
.and_then(|_| script_file.as_file_mut().metadata())
.and_then(|metadata| {
let mut permissions = metadata.permissions();
permissions.set_mode(0o755);
fs::set_permissions(script_file.path(), permissions)
})
.context("Failed creating temporary preset script")?;
let script_path = script_file.into_temp_path();
arch_chroot
.execute()
.arg(mount_point.path())
.arg(
Path::new("/").join(
script_path
.file_name()
.expect("Script path had no file name"),
),
)
.run()
.with_context(|| format!("Failed running preset script:\n{}", script.script_text))?;
}
info!("Performing post installation tasks");
arch_chroot
.execute()
.arg(mount_point.path())
.args(["systemctl", "enable", "NetworkManager"])
.run()
.context("Failed to enable NetworkManager")?;
.args(&["systemctl", "enable", "NetworkManager"])
.run(ErrorKind::PostInstallation)?;
info!("Configuring journald");
fs::write(
mount_point.path().join("etc/systemd/journald.conf"),
constants::JOURNALD_CONF,
)
.context("Failed to write to journald.conf")?;
JOURNALD_CONF,
).context(ErrorKind::PostInstallation)?;
info!("Generating initramfs");
let plymouth_exists = Path::new(&mount_point.path().join("usr/bin/plymouth")).exists();
fs::write(
mount_point.path().join("etc/mkinitcpio.conf"),
initcpio::Initcpio::new(encrypted_root.is_some(), plymouth_exists).to_config()?,
)
.context("Failed to write to mkinitcpio.conf")?;
fs::write(mount_point.path().join("etc/mkinitcpio.conf"), MKINITCPIO)
.context(ErrorKind::Initramfs)?;
arch_chroot
.execute()
.arg(mount_point.path())
.args(["mkinitcpio", "-P"])
.run()
.context("Failed to run mkinitcpio - do you have the base and linux packages installed?")?;
.args(&["mkinitcpio", "-p", "linux"])
.run(ErrorKind::Initramfs)?;
if encrypted_root.is_some() {
if cryptsetup.is_some() {
debug!("Setting up GRUB for an encrypted root partition");
let uuid = blkid
.expect("No tool for blkid")
.unwrap()
.execute()
.arg(root_partition_base.path())
.args(["-o", "value", "-s", "UUID"])
.run_text_output()
.context("Failed to run blkid")?;
.arg(root_partition)
.args(&["-o", "value", "-s", "UUID"])
.run_text_output(ErrorKind::Partitioning)?;
let trimmed = uuid.trim();
debug!("Root partition UUID: {}", trimmed);
let mut grub_file = fs::OpenOptions::new()
.append(true)
.open(mount_point.path().join("etc/default/grub"))
.context("Failed to create /etc/default/grub")?;
.context(ErrorKind::Bootloader)?;
write!(
&mut grub_file,
"GRUB_CMDLINE_LINUX=\"cryptdevice=UUID={}:luks_root\"",
trimmed
)
.context("Failed to write to /etc/default/grub")?;
).context(ErrorKind::Bootloader)?;
}
info!("Installing the Bootloader");
arch_chroot
.execute()
.arg(mount_point.path())
.args(["bash", "-c"])
.args(&["bash", "-c"])
.arg(format!("grub-install --target=i386-pc --boot-directory /boot {} && grub-install --target=x86_64-efi --efi-directory /boot --boot-directory /boot --removable && grub-mkconfig -o /boot/grub/grub.cfg", disk_path.display()))
.run().context("Failed to install grub")?;
let bootloader = mount_point.path().join("boot/EFI/BOOT/BOOTX64.efi");
fs::rename(
&bootloader,
mount_point.path().join("boot/EFI/BOOT/grubx64.efi"),
)
.context("Cannot move out grub")?;
fs::copy(
mount_point.path().join("usr/share/shim-signed/mmx64.efi"),
mount_point.path().join("boot/EFI/BOOT/mmx64.efi"),
)
.context("Failed copying mmx64")?;
fs::copy(
mount_point.path().join("usr/share/shim-signed/shimx64.efi"),
bootloader,
)
.context("Failed copying shim")?;
debug!(
"GRUB configuration: {}",
fs::read_to_string(mount_point.path().join("boot/grub/grub.cfg"))
.unwrap_or_else(|e| e.to_string())
);
.run(ErrorKind::Bootloader)?;
if command.interactive {
info!("Dropping you to chroot. Do as you wish to customize the installation. Please exit by typing 'exit' instead of using Ctrl+D");
info!("Dropping you to chroot. Do as you wish to customize the installation");
arch_chroot
.execute()
.arg(mount_point.path())
.run()
.context("Failed to enter interactive chroot")?;
.run(ErrorKind::Interactive)?;
}
info!("Unmounting filesystems");
@ -509,3 +267,83 @@ fn create(command: args::CreateCommand) -> anyhow::Result<()> {
Ok(())
}
fn chroot(command: ChrootCommand) -> Result<(), Error> {
let arch_chroot = Tool::find("arch-chroot")?;
let cryptsetup = if command.encrypted_root {
Some(Tool::find("cryptsetup")?)
} else {
None
};
let block_device = block::BlockDevice::from_path(command.block_device)?;
let mount_point = tempdir().context(ErrorKind::TmpDirError)?;
let root_partition = block_device.partition_device_path(3)?;
let encrypted_root = if let Some(cryptsetup) = &cryptsetup {
Some(EncryptedDevice::open(
cryptsetup,
&root_partition,
"alma_root",
)?)
} else {
None
};
let alma = ALMA::new(block_device, encrypted_root);
let mount_stack = alma.mount(mount_point.path())?;
arch_chroot
.execute()
.arg(mount_point.path())
.run(ErrorKind::Interactive)?;
info!("Unmounting filesystems");
mount_stack.umount()?;
Ok(())
}
extern "C" fn handle_sigint(_: i32) {
warn!("Interrupted");
}
fn main() {
let app = App::from_args();
let log_level = if app.verbose {
LevelFilter::Debug
} else {
LevelFilter::Info
};
CombinedLogger::init(vec![TermLogger::new(log_level, Config::default()).unwrap()]).unwrap();
let sig_action = signal::SigAction::new(
signal::SigHandler::Handler(handle_sigint),
signal::SaFlags::empty(),
signal::SigSet::empty(),
);
unsafe {
signal::sigaction(signal::SIGINT, &sig_action).unwrap();
signal::sigaction(signal::SIGTERM, &sig_action).unwrap();
signal::sigaction(signal::SIGQUIT, &sig_action).unwrap();
}
let result = match app.cmd {
Command::Create(command) => create(command),
Command::Chroot(command) => chroot(command),
};
match result {
Ok(()) => {
exit(0);
}
Err(error) => {
error!("{}", error);
if let Some(cause) = error.cause() {
error!("Caused by: {}", cause);
}
exit(1);
}
}
}

80
src/mountstack.rs Normal file
View File

@ -0,0 +1,80 @@
use super::error::{Error, ErrorKind};
use failure::Fail;
use log::{debug, warn};
use nix;
use nix::mount::{mount, umount, MsFlags};
use std::borrow::Cow;
use std::path::Path;
#[derive(Debug, Clone, Copy)]
pub enum Filesystem {
Ext4,
Vfat,
}
impl Filesystem {
fn to_type(self) -> &'static str {
match self {
Filesystem::Ext4 => "ext4",
Filesystem::Vfat => "vfat",
}
}
}
pub struct MountStack<'a> {
targets: Vec<Cow<'a, Path>>,
}
impl<'a> MountStack<'a> {
pub fn new() -> Self {
MountStack {
targets: Vec::new(),
}
}
#[must_use]
pub fn mount<T: Into<Cow<'a, Path>>>(
&mut self,
source: &Path,
target: T,
filesystem: Filesystem,
options: Option<&str>,
) -> nix::Result<()> {
let target = target.into();
debug!("Mounting {:?} ({:?}) to {:?}", source, filesystem, target);
mount(
Some(source),
target.as_ref(),
Some(filesystem.to_type()),
MsFlags::MS_NOATIME,
options,
)?;
self.targets.push(target);
Ok(())
}
fn _umount(&mut self) -> Result<(), Error> {
let mut result = Ok(());
while let Some(target) = self.targets.pop() {
debug!("Unmounting {}", target.display());
if let Err(e) = umount(target.as_ref()) {
warn!("Unable to umount {}: {}", target.display(), e);
result = Err(Error::from(e.context(ErrorKind::UmountFailure)));
};
}
result
}
pub fn umount(mut self) -> Result<(), Error> {
self._umount()
}
}
impl<'a> Drop for MountStack<'a> {
fn drop(&mut self) {
self._umount().ok();
}
}

View File

@ -1,158 +0,0 @@
use anyhow::{anyhow, Context};
use serde::Deserialize;
use std::collections::HashSet;
use std::env;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
#[derive(Deserialize)]
struct Preset {
packages: Option<Vec<String>>,
script: Option<String>,
environment_variables: Option<Vec<String>>,
shared_directories: Option<Vec<PathBuf>>,
aur_packages: Option<Vec<String>>,
}
fn visit_dirs(dir: &Path, filevec: &mut Vec<PathBuf>) -> Result<(), io::Error> {
if dir.is_dir() {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
visit_dirs(&path, filevec)?;
} else if entry.path().extension() == Some(&std::ffi::OsString::from("toml")) {
filevec.push(entry.path());
}
}
}
Ok(())
}
impl Preset {
fn load(path: &Path) -> anyhow::Result<Self> {
let data = fs::read_to_string(path).with_context(|| format!("{}", path.display()))?;
toml::from_str(&data).with_context(|| format!("{}", path.display()))
}
fn process(
&self,
packages: &mut HashSet<String>,
scripts: &mut Vec<Script>,
environment_variables: &mut HashSet<String>,
path: &Path,
aur_packages: &mut HashSet<String>,
) -> anyhow::Result<()> {
if let Some(preset_packages) = &self.packages {
packages.extend(preset_packages.clone());
}
if let Some(preset_aur_packages) = &self.aur_packages {
aur_packages.extend(preset_aur_packages.clone());
}
if let Some(preset_environment_variables) = &self.environment_variables {
environment_variables.extend(preset_environment_variables.clone());
}
if let Some(script_text) = &self.script {
scripts.push(Script {
script_text: script_text.clone(),
shared_dirs: self
.shared_directories
.clone()
.map(|x| {
// Convert directories to absolute paths
// If any shared directory is not a directory then throw an error
x.iter()
.cloned()
.map(|y| {
let full_path = path.parent().expect("Path has no parent").join(&y);
if full_path.is_dir() {
Ok(full_path)
} else {
Err(anyhow!(
"Preset: {} - shared directory: {} is not directory",
path.display(),
y.display()
))
}
})
.collect::<anyhow::Result<Vec<_>>>()
})
.map_or(Ok(None), |r| r.map(Some))?,
});
}
Ok(())
}
}
pub struct Script {
pub script_text: String,
pub shared_dirs: Option<Vec<PathBuf>>,
}
pub struct PresetsCollection {
pub packages: HashSet<String>,
pub aur_packages: HashSet<String>,
pub scripts: Vec<Script>,
}
impl PresetsCollection {
pub fn load(list: &[PathBuf]) -> anyhow::Result<Self> {
let mut packages = HashSet::new();
let mut aur_packages = HashSet::new();
let mut scripts: Vec<Script> = Vec::new();
let mut environment_variables = HashSet::new();
for preset in list {
if preset.is_dir() {
// Build vector of paths to files, then sort by path name
// Recursively load directories of preset files
let mut dir_paths: Vec<PathBuf> = Vec::new();
visit_dirs(preset, &mut dir_paths)
.with_context(|| format!("{}", preset.display()))?;
// Order not guaranteed so we sort
// In the future may want to support numerical sort i.e. 15_... < 100_...
dir_paths.sort();
for path in dir_paths {
Preset::load(&path)?.process(
&mut packages,
&mut scripts,
&mut environment_variables,
&path,
&mut aur_packages,
)?;
}
} else {
Preset::load(preset)?.process(
&mut packages,
&mut scripts,
&mut environment_variables,
preset,
&mut aur_packages,
)?;
}
}
let missing_envrionments: Vec<String> = environment_variables
.into_iter()
.filter(|var| env::var(var).is_err())
.collect();
if !missing_envrionments.is_empty() {
return Err(anyhow!(
"Missing environment variables {:?}",
missing_envrionments
));
}
Ok(Self {
packages,
aur_packages,
scripts,
})
}
}

View File

@ -1,35 +1,51 @@
use anyhow::anyhow;
use super::error::*;
use failure::{Fail, ResultExt};
use log::error;
use std::process::Command;
use std::process::{Command, ExitStatus};
use std::str;
#[derive(Debug, Fail)]
enum ProcessError {
#[fail(display = "{}", _0)]
BadExitCode(ExitStatus),
#[fail(display = "Process output isn't valid UTF-8")]
InvalidUtf8,
}
pub trait CommandExt {
fn run(&mut self) -> anyhow::Result<()>;
fn run_text_output(&mut self) -> anyhow::Result<String>;
fn run(&mut self, context: ErrorKind) -> Result<(), Error>;
fn run_text_output(&mut self, context: ErrorKind) -> Result<String, Error>;
}
impl CommandExt for Command {
fn run(&mut self) -> anyhow::Result<()> {
let exit_status = self.spawn()?.wait()?;
fn run(&mut self, context: ErrorKind) -> Result<(), Error> {
let exit_status = self.spawn().context(context)?.wait().context(context)?;
if !exit_status.success() {
return Err(anyhow!("Bad exit code: {}", exit_status));
return Err(ProcessError::BadExitCode(exit_status)
.context(context)
.into());
}
Ok(())
}
fn run_text_output(&mut self) -> anyhow::Result<String> {
let output = self.output()?;
fn run_text_output(&mut self, context: ErrorKind) -> Result<String, Error> {
let output = self.output().context(context)?;
if !output.status.success() {
let error = str::from_utf8(&output.stderr).unwrap_or("[INVALID UTF8]");
error!("{}", error);
return Err(anyhow!("Bad exit code: {}", output.status));
return Err(ProcessError::BadExitCode(output.status)
.context(context)
.into());
}
Ok(String::from(str::from_utf8(&output.stdout).map_err(
|_| anyhow!("Process output is not valid UTF-8"),
)?))
Ok(String::from(
str::from_utf8(&output.stdout)
.map_err(|_| ProcessError::InvalidUtf8)
.context(context)?,
))
}
}

View File

@ -1,102 +0,0 @@
use super::markers::BlockDevice;
use crate::process::CommandExt;
use crate::tool::Tool;
use anyhow::Context;
use log::{debug, warn};
use std::fs;
use std::io::Read;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
static LUKS_MAGIC_1: &[u8] = &[0x4c, 0x55, 0x4b, 0x53, 0xba, 0xbe];
static LUKS_MAGIC_2: &[u8] = &[0x53, 0x4b, 0x55, 0x4c, 0xba, 0xbe];
#[derive(Debug)]
pub struct EncryptedDevice<'t, 'o> {
cryptsetup: &'t Tool,
name: String,
path: PathBuf,
origin: PhantomData<&'o dyn BlockDevice>,
}
impl<'t, 'o> EncryptedDevice<'t, 'o> {
pub fn prepare(cryptsetup: &Tool, device: &dyn BlockDevice) -> anyhow::Result<()> {
debug!("Preparing encrypted device in {}", device.path().display());
cryptsetup
.execute()
.arg("luksFormat")
.arg("-q")
.arg(device.path())
.run()
.context("Error setting up an encrypted device")?;
Ok(())
}
pub fn open(
cryptsetup: &'t Tool,
device: &'o dyn BlockDevice,
name: String,
) -> anyhow::Result<EncryptedDevice<'t, 'o>> {
debug!(
"Opening encrypted device {} as {}",
device.path().display(),
name
);
cryptsetup
.execute()
.arg("open")
.arg(device.path())
.arg(&name)
.run()
.context("Error opening the encrypted device")?;
let path = PathBuf::from("/dev/mapper").join(&name);
Ok(Self {
cryptsetup,
name,
path,
origin: PhantomData,
})
}
fn _close(&mut self) -> anyhow::Result<()> {
debug!("Closing encrypted device {}", self.name);
self.cryptsetup
.execute()
.arg("close")
.arg(&self.name)
.run()
.context("Error closing the encrypted device")?;
Ok(())
}
}
impl<'t, 'o> Drop for EncryptedDevice<'t, 'o> {
fn drop(&mut self) {
if self._close().is_err() {
warn!("Error closing {}", self.name);
}
}
}
impl<'t, 'o> BlockDevice for EncryptedDevice<'t, 'o> {
fn path(&self) -> &Path {
&self.path
}
}
pub fn is_encrypted_device(device: &dyn BlockDevice) -> anyhow::Result<bool> {
let mut f = fs::OpenOptions::new()
.read(true)
.write(false)
.open(device.path())
.context("Error detecting whether the root partition is an encrypted device")?;
let mut buffer = [0; 6];
f.read_exact(&mut buffer)
.context("Error detecting whether the root partition is an encrypted device")?;
Ok(buffer == LUKS_MAGIC_1 || buffer == LUKS_MAGIC_2)
}

View File

@ -1,54 +0,0 @@
use super::markers::BlockDevice;
use crate::{process::CommandExt, tool::Tool};
use anyhow::Context;
#[derive(Debug, Clone, Copy)]
pub enum FilesystemType {
Ext4,
Vfat,
}
impl FilesystemType {
pub fn to_mount_type(self) -> &'static str {
match self {
FilesystemType::Ext4 => "ext4",
FilesystemType::Vfat => "vfat",
}
}
}
#[derive(Debug)]
pub struct Filesystem<'a> {
fs_type: FilesystemType,
block: &'a dyn BlockDevice,
}
impl<'a> Filesystem<'a> {
pub fn format(
block: &'a dyn BlockDevice,
fs_type: FilesystemType,
mkfs: &Tool,
) -> anyhow::Result<Self> {
let mut command = mkfs.execute();
match fs_type {
FilesystemType::Ext4 => command.arg("-F").arg(block.path()),
FilesystemType::Vfat => command.arg("-F32").arg(block.path()),
};
command.run().context("Error formatting filesystem")?;
Ok(Self { fs_type, block })
}
pub fn from_partition(block: &'a dyn BlockDevice, fs_type: FilesystemType) -> Self {
Self { fs_type, block }
}
pub fn block(&self) -> &dyn BlockDevice {
self.block
}
pub fn fs_type(&self) -> FilesystemType {
self.fs_type
}
}

View File

@ -1,53 +0,0 @@
use crate::tool::Tool;
use anyhow::{anyhow, Context};
use log::info;
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct LoopDevice {
path: PathBuf,
losetup: Tool,
}
impl LoopDevice {
pub fn create(file: &Path) -> anyhow::Result<Self> {
let losetup = Tool::find("losetup")?;
let output = losetup
.execute()
.args(["--find", "-P", "--show"])
.arg(file)
.output()
.context("Error creating the image")?;
if !output.status.success() {
return Err(anyhow!(String::from_utf8(output.stderr)?));
}
let path = PathBuf::from(
String::from_utf8(output.stdout)
.context("Output not valid UTF-8")?
.trim(),
);
info!("Mounted {} to {}", file.display(), path.display());
Ok(Self { path, losetup })
}
pub fn path(&self) -> &Path {
&self.path
}
}
impl Drop for LoopDevice {
fn drop(&mut self) {
info!("Detaching loop device {}", self.path.display());
self.losetup
.execute()
.arg("-d")
.arg(&self.path)
.spawn()
.expect("Failed to spawn command to detach loop device")
.wait()
.ok();
}
}

View File

@ -1,7 +0,0 @@
use std::path::Path;
// Marker traits
pub trait BlockDevice: std::fmt::Debug {
fn path(&self) -> &Path;
}
pub trait Origin {}

View File

@ -1,16 +0,0 @@
mod crypt;
mod filesystem;
mod loop_device;
mod markers;
mod mount_stack;
mod partition;
mod removeable_devices;
mod storage_device;
pub use crypt::{is_encrypted_device, EncryptedDevice};
pub use filesystem::{Filesystem, FilesystemType};
pub use loop_device::LoopDevice;
pub use markers::BlockDevice;
pub use mount_stack::MountStack;
pub use removeable_devices::get_storage_devices;
pub use storage_device::StorageDevice;

View File

@ -1,85 +0,0 @@
use super::Filesystem;
use anyhow::anyhow;
use log::{debug, warn};
use nix::mount::{mount, umount, MsFlags};
use std::marker::PhantomData;
use std::path::PathBuf;
pub struct MountStack<'a> {
targets: Vec<PathBuf>,
filesystems: PhantomData<Filesystem<'a>>,
}
impl<'a> MountStack<'a> {
pub fn new() -> Self {
MountStack {
targets: Vec::new(),
filesystems: PhantomData,
}
}
pub fn mount(
&mut self,
filesystem: &'a Filesystem,
target: PathBuf,
options: Option<&str>,
) -> nix::Result<()> {
let source = filesystem.block().path();
debug!("Mounting {:?} to {:?}", filesystem, target);
mount(
Some(source),
&target,
Some(filesystem.fs_type().to_mount_type()),
MsFlags::MS_NOATIME,
options,
)?;
self.targets.push(target);
Ok(())
}
pub fn bind_mount(
&mut self,
source: PathBuf,
target: PathBuf,
options: Option<&str>,
) -> nix::Result<()> {
debug!("Mounting {:?} to {:?}", source, target);
mount::<_, _, str, _>(
Some(&source),
&target,
None,
MsFlags::MS_BIND | MsFlags::MS_NOATIME, // Read-only flag has no effect for bind mounts
options,
)?;
self.targets.push(target);
Ok(())
}
fn _umount(&mut self) -> anyhow::Result<()> {
let mut result = Ok(());
while let Some(target) = self.targets.pop() {
debug!("Unmounting {}", target.display());
if let Err(e) = umount(&target) {
warn!("Unable to umount {}: {}", target.display(), e);
result = Err(anyhow!(
"Failed unmounting filesystem: {}, {}",
target.display(),
e
));
};
}
result
}
pub fn umount(mut self) -> anyhow::Result<()> {
self._umount()
}
}
impl<'a> Drop for MountStack<'a> {
fn drop(&mut self) {
self._umount().ok();
}
}

View File

@ -1,24 +0,0 @@
use super::markers::{BlockDevice, Origin};
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct Partition<'a> {
path: PathBuf,
origin: PhantomData<&'a dyn Origin>,
}
impl<'a> Partition<'a> {
pub fn new<T: Origin + 'a>(path: PathBuf) -> Self {
Self {
path,
origin: PhantomData,
}
}
}
impl<'a> BlockDevice for Partition<'a> {
fn path(&self) -> &Path {
&self.path
}
}

View File

@ -1,86 +0,0 @@
use anyhow::Context;
use byte_unit::Byte;
use std::{fmt, fs};
#[derive(Debug)]
pub struct Device {
model: String,
vendor: String,
size: Byte,
pub name: String,
}
impl fmt::Display for Device {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{} {} ({})",
self.vendor,
self.model,
self.size.get_appropriate_unit(true)
)
}
}
fn trimmed(source: String) -> String {
String::from(source.trim_end())
}
pub fn get_storage_devices(allow_non_removable: bool) -> anyhow::Result<Vec<Device>> {
let mut result = Vec::new();
for entry in fs::read_dir("/sys/block").context("Error querying storage devices")? {
let entry = entry.context("Error querying storage devices")?;
let removable = allow_non_removable
|| fs::read_to_string(entry.path().join("removable"))
.map(|v| v == "1\n")
.context("Error querying storage devices")?;
if !removable {
continue;
}
let model = fs::read_to_string(entry.path().join("device/model"))
.map(trimmed)
.context("Error querying storage devices")?;
if model == "CD-ROM" {
continue;
}
result.push(Device {
name: entry
.path()
.file_name()
.expect("Could not get file name for dir entry /sys/block")
.to_string_lossy()
.into_owned(),
model,
vendor: fs::read_to_string(entry.path().join("device/vendor"))
.map(trimmed)
.context("Error querying storage devices")?,
size: Byte::from_bytes(
fs::read_to_string(entry.path().join("size"))
.context("Error querying storage devices")?
.trim()
.parse::<u128>()
.context("Could not parse block size to unsigned integer (u128)")?
* 512,
),
});
}
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sanity() {
let devices = get_storage_devices(false).expect("No devices");
println!("{:?}", devices);
}
}

View File

@ -1,102 +0,0 @@
use super::markers::{BlockDevice, Origin};
use super::partition::Partition;
use anyhow::{anyhow, Context};
use log::debug;
use std::fs::read_to_string;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct StorageDevice<'a> {
name: String,
path: PathBuf,
origin: PhantomData<&'a dyn Origin>,
}
impl<'a> StorageDevice<'a> {
pub fn from_path(path: &'a Path, allow_non_removable: bool) -> anyhow::Result<Self> {
debug!("path: {:?}", path);
let path = path
.canonicalize()
.context("Error querying information about the block device")?;
let device_name = path
.file_name()
.and_then(std::ffi::OsStr::to_str)
.map(String::from)
.ok_or_else(|| anyhow!("Invalid device name: {}", path.display()))?;
debug!("real path: {:?}, device name: {:?}", path, device_name);
let _self = Self {
name: device_name,
path,
origin: PhantomData,
};
// If we only allow removable/loop devices, and the device is neither removable or a loop
// device then throw a DangerousDevice error
if !(allow_non_removable || _self.is_removable_device()? || _self.is_loop_device()) {
return Err(anyhow!(
"The given block device is neither removable nor a loop device: {}",
_self.name
));
}
Ok(_self)
}
fn sys_path(&self) -> PathBuf {
let mut path = PathBuf::from("/sys/block");
path.push(self.name.clone());
path
}
fn is_removable_device(&self) -> anyhow::Result<bool> {
let mut path = self.sys_path();
path.push("removable");
debug!("Reading: {:?}", path);
let result =
read_to_string(&path).context("Error querying information about the block device")?;
debug!("{:?} -> {}", path, result);
Ok(result == "1\n")
}
fn is_loop_device(&self) -> bool {
let mut path = self.sys_path();
path.push("loop");
path.exists()
}
pub fn get_partition(&self, index: u8) -> anyhow::Result<Partition> {
let name = if self
.name
.chars()
.rev()
.next()
.expect("Storage device name is empty")
.is_ascii_digit()
{
format!("{}p{}", self.name, index)
} else {
format!("{}{}", self.name, index)
};
let mut path = PathBuf::from("/dev");
path.push(name);
debug!("Partition {} for {} is in {:?}", index, self.name, path);
if !path.exists() {
return Err(anyhow!("Partition {} does not exist", index));
}
Ok(Partition::new::<Self>(path))
}
}
impl<'a> BlockDevice for StorageDevice<'a> {
fn path(&self) -> &Path {
&self.path
}
}
impl<'a> Origin for StorageDevice<'a> {}

View File

@ -1,12 +1,5 @@
mod chroot;
mod mount;
mod qemu;
use anyhow::Context;
pub use chroot::chroot;
pub use mount::mount;
pub use qemu::qemu;
use super::error::*;
use failure::ResultExt;
use std::path::PathBuf;
use std::process::Command;
use which::which;
@ -17,9 +10,9 @@ pub struct Tool {
}
impl Tool {
pub fn find(name: &'static str) -> anyhow::Result<Self> {
pub fn find(name: &'static str) -> Result<Self, Error> {
Ok(Self {
exec: which(name).context(format!("Cannot find {}", name))?,
exec: which(name).context(ErrorKind::NoTool(name))?,
})
}

View File

@ -1,75 +0,0 @@
use super::mount;
use super::Tool;
use crate::args;
use crate::constants::{BOOT_PARTITION_INDEX, ROOT_PARTITION_INDEX};
use crate::process::CommandExt;
use crate::storage;
use crate::storage::{is_encrypted_device, EncryptedDevice};
use crate::storage::{BlockDevice, Filesystem, FilesystemType, LoopDevice};
use anyhow::Context;
use log::info;
use tempfile::tempdir;
/// Use arch-chroot to chroot to the given device
/// Also handles encrypted root partitions (detected by checking for the LUKS magic header)
pub fn chroot(command: args::ChrootCommand) -> anyhow::Result<()> {
let arch_chroot = Tool::find("arch-chroot")?;
let cryptsetup;
let loop_device: Option<LoopDevice>;
let storage_device =
match storage::StorageDevice::from_path(&command.block_device, command.allow_non_removable)
{
Ok(b) => b,
Err(_) => {
loop_device = Some(LoopDevice::create(&command.block_device)?);
storage::StorageDevice::from_path(
loop_device.as_ref().expect("loop device not found").path(),
command.allow_non_removable,
)?
}
};
let mount_point = tempdir().context("Error creating a temporary directory")?;
let boot_partition = storage_device.get_partition(BOOT_PARTITION_INDEX)?;
let boot_filesystem = Filesystem::from_partition(&boot_partition, FilesystemType::Vfat);
let root_partition_base = storage_device.get_partition(ROOT_PARTITION_INDEX)?;
let encrypted_root = if is_encrypted_device(&root_partition_base)? {
cryptsetup = Some(Tool::find("cryptsetup")?);
Some(EncryptedDevice::open(
cryptsetup.as_ref().expect("cryptsetup not found"),
&root_partition_base,
"alma_root".into(),
)?)
} else {
None
};
let root_partition = if let Some(e) = encrypted_root.as_ref() {
e as &dyn BlockDevice
} else {
&root_partition_base as &dyn BlockDevice
};
let root_filesystem = Filesystem::from_partition(root_partition, FilesystemType::Ext4);
let mount_stack = mount(mount_point.path(), &boot_filesystem, &root_filesystem)?;
arch_chroot
.execute()
.arg(mount_point.path())
.args(&command.command)
.run()
.with_context(|| {
format!(
"Error running command in chroot: {}",
command.command.join(" "),
)
})?;
info!("Unmounting filesystems");
mount_stack.umount()?;
Ok(())
}

View File

@ -1,36 +0,0 @@
use crate::storage::{Filesystem, MountStack};
use anyhow::Context;
use log::{debug, info};
use std::fs;
use std::path::Path;
/// Mounts root filesystem to given mount_path
/// Mounts boot filesystem to mount_path/boot
/// Note we mount with noatime to reduce disk writes by not recording file access times
pub fn mount<'a>(
mount_path: &Path,
boot_filesystem: &'a Filesystem,
root_filesystem: &'a Filesystem,
) -> anyhow::Result<MountStack<'a>> {
let mut mount_stack = MountStack::new();
debug!(
"Root partition: {}",
root_filesystem.block().path().display()
);
info!("Mounting filesystems to {}", mount_path.display());
mount_stack
.mount(root_filesystem, mount_path.into(), None)
.with_context(|| format!("Error mounting filesystem to {}", mount_path.display()))?;
let boot_point = mount_path.join("boot");
if !boot_point.exists() {
fs::create_dir(&boot_point).context("Error creating the boot directory")?;
}
mount_stack
.mount(boot_filesystem, boot_point, None)
.context("Error mounting the boot point")?;
Ok(mount_stack)
}

View File

@ -1,42 +0,0 @@
use super::Tool;
use crate::args;
use anyhow::Context;
use log::debug;
use std::os::unix::process::CommandExt as UnixCommandExt;
use std::path::PathBuf;
/// Loads given block device in qemu
/// Uses kvm if it is enabled
pub fn qemu(command: args::QemuCommand) -> anyhow::Result<()> {
let qemu = Tool::find("qemu-system-x86_64")?;
let mut run = qemu.execute();
run.args([
"-m",
"4G",
"-netdev",
"user,id=user.0",
"-device",
"virtio-net-pci,netdev=user.0",
"-device",
"qemu-xhci,id=xhci",
"-device",
"usb-tablet,bus=xhci.0",
"-drive",
])
.arg(format!(
"file={},if=virtio,format=raw",
command.block_device.display()
))
.args(command.args);
if PathBuf::from("/dev/kvm").exists() {
debug!("KVM is enabled");
run.args(["-enable-kvm", "-cpu", "host"]);
}
let err = run.exec();
Err(err).context("Failed launching Qemu")?
}