| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | use std::fs::{DirBuilder, OpenOptions}; |
| 13 | use std::io::{Read, Write}; |
| 14 | use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; |
| 15 | use std::path::Path; |
| 16 | use std::process::ExitCode; |
| 17 | |
| 18 | use iz_core::config::Config; |
| 19 | use iz_core::manifest::write_manifest; |
| 20 | use iz_core::staging::blob_path; |
| 21 | use iz_core::store::export::{AttachmentRow, ReadOnly}; |
| 22 | use iz_core::time::now_stamp; |
| 23 | use sha2::{Digest, Sha256}; |
| 24 | |
| 25 | use super::{database_file, describe, existing_data_dir, fail, instance_key, take_lock}; |
| 26 | |
| 27 | |
| 28 | const BOARD_FILE: &str = "board.json"; |
| 29 | |
| 30 | const ATTACHMENTS_DIR: &str = "attachments"; |
| 31 | |
| 32 | const CHUNK: usize = 64 * 1024; |
| 33 | |
| 34 | |
| 35 | pub async fn run(config_path: &Path, out: &Path) -> ExitCode { |
| 36 | let config = match Config::load(config_path) { |
| 37 | Ok(config) => config, |
| 38 | Err(error) => return fail(describe(&error)), |
| 39 | }; |
| 40 | let data_dir = match existing_data_dir(&config) { |
| 41 | Ok(dir) => dir, |
| 42 | Err(message) => return fail(message), |
| 43 | }; |
| 44 | let _lock = match take_lock(&data_dir) { |
| 45 | Ok(lock) => lock, |
| 46 | Err(code) => return code, |
| 47 | }; |
| 48 | let key = match instance_key(&data_dir) { |
| 49 | Ok(key) => key, |
| 50 | Err(message) => return fail(message), |
| 51 | }; |
| 52 | if let Err(message) = prepare_out(out) { |
| 53 | return fail(message); |
| 54 | } |
| 55 | match write_export(&config, &data_dir, out, &key).await { |
| 56 | Ok(report) => { |
| 57 | println!( |
| 58 | "exported {} attachments with bytes and {} without to {}", |
| 59 | report.with_bytes, |
| 60 | report.without_bytes.len(), |
| 61 | out.display() |
| 62 | ); |
| 63 | if report.without_bytes.is_empty() { |
| 64 | return ExitCode::SUCCESS; |
| 65 | } |
| 66 | for (id, reason) in &report.without_bytes { |
| 67 | eprintln!("iz: attachment {id} has no bytes in the export: {reason}"); |
| 68 | } |
| 69 | eprintln!( |
| 70 | "iz: the export is incomplete; {} attachments have no bytes", |
| 71 | report.without_bytes.len() |
| 72 | ); |
| 73 | ExitCode::FAILURE |
| 74 | } |
| 75 | Err(message) => fail(message), |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | |
| 80 | struct Report { |
| 81 | |
| 82 | with_bytes: usize, |
| 83 | |
| 84 | without_bytes: Vec<(String, String)>, |
| 85 | } |
| 86 | |
| 87 | |
| 88 | |
| 89 | fn prepare_out(out: &Path) -> Result<(), String> { |
| 90 | match std::fs::symlink_metadata(out) { |
| 91 | Ok(meta) => { |
| 92 | if !meta.file_type().is_dir() { |
| 93 | return Err(format!("{} exists and is not a directory", out.display())); |
| 94 | } |
| 95 | let mut entries = std::fs::read_dir(out) |
| 96 | .map_err(|error| format!("cannot read {}: {error}", out.display()))?; |
| 97 | if entries.next().is_some() { |
| 98 | return Err(format!("{} is not empty", out.display())); |
| 99 | } |
| 100 | Ok(()) |
| 101 | } |
| 102 | Err(_) => DirBuilder::new() |
| 103 | .mode(0o700) |
| 104 | .create(out) |
| 105 | .map_err(|error| format!("cannot create {}: {error}", out.display())), |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | |
| 110 | |
| 111 | async fn write_export( |
| 112 | config: &Config, |
| 113 | data_dir: &Path, |
| 114 | out: &Path, |
| 115 | key: &[u8; 32], |
| 116 | ) -> Result<Report, String> { |
| 117 | let database = database_file(config)?; |
| 118 | let db = ReadOnly::open(&database) |
| 119 | .await |
| 120 | .map_err(|error| describe(&error))?; |
| 121 | let board_ids = db.board_ids().await.map_err(|error| describe(&error))?; |
| 122 | let [board_id] = board_ids.as_slice() else { |
| 123 | return Err(format!( |
| 124 | "expected one board in the database, found {}", |
| 125 | board_ids.len() |
| 126 | )); |
| 127 | }; |
| 128 | let dump = db |
| 129 | .export_board(board_id) |
| 130 | .await |
| 131 | .map_err(|error| describe(&error))?; |
| 132 | let rows = db |
| 133 | .board_attachment_rows(board_id) |
| 134 | .await |
| 135 | .map_err(|error| describe(&error))?; |
| 136 | |
| 137 | DirBuilder::new() |
| 138 | .mode(0o700) |
| 139 | .recursive(true) |
| 140 | .create(out.join(ATTACHMENTS_DIR)) |
| 141 | .map_err(|error| format!("cannot create the attachments directory: {error}"))?; |
| 142 | let mut written = vec![BOARD_FILE.to_owned()]; |
| 143 | let mut attachments = Vec::with_capacity(rows.len()); |
| 144 | let mut report = Report { |
| 145 | with_bytes: 0, |
| 146 | without_bytes: Vec::new(), |
| 147 | }; |
| 148 | for row in &rows { |
| 149 | |
| 150 | let source = blob_path(data_dir, &row.id).map_err(|error| describe(&error))?; |
| 151 | let mut entry = attachment_json(row); |
| 152 | if row.location == "local" { |
| 153 | match copy_blob(&source, &out.join(ATTACHMENTS_DIR).join(&row.id), row)? { |
| 154 | Ok(()) => { |
| 155 | let relative = format!("{ATTACHMENTS_DIR}/{}", row.id); |
| 156 | entry["bytes"] = serde_json::Value::Bool(true); |
| 157 | entry["file"] = serde_json::Value::String(relative.clone()); |
| 158 | written.push(relative); |
| 159 | report.with_bytes += 1; |
| 160 | } |
| 161 | Err(reason) => { |
| 162 | entry["bytes"] = serde_json::Value::Bool(false); |
| 163 | report.without_bytes.push((row.id.clone(), reason)); |
| 164 | } |
| 165 | } |
| 166 | } else { |
| 167 | entry["bytes"] = serde_json::Value::Bool(false); |
| 168 | report.without_bytes.push(( |
| 169 | row.id.clone(), |
| 170 | format!( |
| 171 | "location is {}, the bytes are not on this disk", |
| 172 | row.location |
| 173 | ), |
| 174 | )); |
| 175 | } |
| 176 | attachments.push(entry); |
| 177 | } |
| 178 | |
| 179 | let members = dump.members; |
| 180 | let board = serde_json::json!({ |
| 181 | "format": "iz-export", |
| 182 | "version": 1, |
| 183 | "exported_at": now_stamp(), |
| 184 | "board": dump.board, |
| 185 | "columns": dump.columns, |
| 186 | "tags": dump.tags, |
| 187 | "tasks": dump.tasks, |
| 188 | "assignees": dump.assignees, |
| 189 | "dependencies": dump.dependencies, |
| 190 | "comments": dump.comments, |
| 191 | "activity": dump.activity, |
| 192 | "attachments": attachments, |
| 193 | "members": members, |
| 194 | }); |
| 195 | let bytes = serde_json::to_vec_pretty(&board) |
| 196 | .map_err(|error| format!("encoding {BOARD_FILE}: {error}"))?; |
| 197 | write_new(&out.join(BOARD_FILE), &bytes)?; |
| 198 | |
| 199 | write_manifest(out, key, &now_stamp(), env!("IZ_BUILD_SHA"), &written) |
| 200 | .map_err(|error| describe(&error))?; |
| 201 | Ok(report) |
| 202 | } |
| 203 | |
| 204 | |
| 205 | fn attachment_json(row: &AttachmentRow) -> serde_json::Value { |
| 206 | serde_json::json!({ |
| 207 | "id": row.id, |
| 208 | "task_id": row.task_id, |
| 209 | "name": row.name, |
| 210 | "mime": row.mime, |
| 211 | "size": row.size, |
| 212 | "sha256": row.sha256, |
| 213 | "uploaded_by": row.uploaded_by, |
| 214 | "created_at": row.created_at, |
| 215 | "location": row.location, |
| 216 | }) |
| 217 | } |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | fn copy_blob( |
| 223 | source: &Path, |
| 224 | dest: &Path, |
| 225 | row: &AttachmentRow, |
| 226 | ) -> Result<Result<(), String>, String> { |
| 227 | let meta = match std::fs::symlink_metadata(source) { |
| 228 | Ok(meta) => meta, |
| 229 | Err(_) => return Ok(Err("the bytes are missing from the store".into())), |
| 230 | }; |
| 231 | if !meta.file_type().is_file() { |
| 232 | return Ok(Err("the stored entry is not a regular file".into())); |
| 233 | } |
| 234 | let mut input = std::fs::File::open(source) |
| 235 | .map_err(|error| format!("cannot read {}: {error}", source.display()))?; |
| 236 | let mut output = OpenOptions::new() |
| 237 | .write(true) |
| 238 | .create_new(true) |
| 239 | .mode(0o600) |
| 240 | .open(dest) |
| 241 | .map_err(|error| format!("cannot create {}: {error}", dest.display()))?; |
| 242 | let mut hasher = Sha256::new(); |
| 243 | let mut size: u64 = 0; |
| 244 | let mut buffer = vec![0u8; CHUNK]; |
| 245 | loop { |
| 246 | let read = input |
| 247 | .read(&mut buffer) |
| 248 | .map_err(|error| format!("cannot read {}: {error}", source.display()))?; |
| 249 | if read == 0 { |
| 250 | break; |
| 251 | } |
| 252 | output |
| 253 | .write_all(&buffer[..read]) |
| 254 | .map_err(|error| format!("cannot write {}: {error}", dest.display()))?; |
| 255 | hasher.update(&buffer[..read]); |
| 256 | size += read as u64; |
| 257 | } |
| 258 | output |
| 259 | .sync_all() |
| 260 | .map_err(|error| format!("cannot sync {}: {error}", dest.display()))?; |
| 261 | let digest = hex::encode(hasher.finalize()); |
| 262 | if size != row.size || digest != row.sha256 { |
| 263 | drop(output); |
| 264 | std::fs::remove_file(dest) |
| 265 | .map_err(|error| format!("cannot remove {}: {error}", dest.display()))?; |
| 266 | return Ok(Err( |
| 267 | "the bytes do not match the recorded size or digest".into() |
| 268 | )); |
| 269 | } |
| 270 | Ok(Ok(())) |
| 271 | } |
| 272 | |
| 273 | |
| 274 | fn write_new(path: &Path, bytes: &[u8]) -> Result<(), String> { |
| 275 | let mut file = OpenOptions::new() |
| 276 | .write(true) |
| 277 | .create_new(true) |
| 278 | .mode(0o600) |
| 279 | .open(path) |
| 280 | .map_err(|error| format!("cannot create {}: {error}", path.display()))?; |
| 281 | file.write_all(bytes) |
| 282 | .and_then(|()| file.sync_all()) |
| 283 | .map_err(|error| format!("cannot write {}: {error}", path.display())) |
| 284 | } |
| 285 | |
| 286 | #[cfg(test)] |
| 287 | mod tests { |
| 288 | use super::*; |
| 289 | |
| 290 | #[test] |
| 291 | fn export_refuses_a_non_empty_out_directory() { |
| 292 | let dir = tempfile::tempdir().expect("temp dir"); |
| 293 | std::fs::write(dir.path().join("keep.txt"), b"x").expect("seed file"); |
| 294 | let error = prepare_out(dir.path()).expect_err("non-empty must be refused"); |
| 295 | assert!(error.contains("is not empty"), "got: {error}"); |
| 296 | let empty = dir.path().join("fresh"); |
| 297 | prepare_out(&empty).expect("a missing directory is created"); |
| 298 | assert!(empty.is_dir()); |
| 299 | } |
| 300 | } |