leejunyoung5819 handmade-dataset-creator
공개고품질 LLM 데이터셋 수제작을 위한 생산성 도구
| 1 | //! 데이터셋 모델: .jsonl 한 줄 = 대화 턴 하나. |
| 2 | //! |
| 3 | //! 한 줄의 형식은 다음과 같다: |
| 4 | //! ```json |
| 5 | //! {"messages": [ |
| 6 | //! {"role": "system", "content": "..."}, |
| 7 | //! {"role": "tools", "content": [ ...도구 스키마... ]}, |
| 8 | //! {"role": "user", "content": "..."}, |
| 9 | //! {"role": "assistant", "reasoning_content": "...", "content": "...", |
| 10 | //! "tool_calls": [{"id": "...", "type": "function", "function": {"name": "...", "arguments": {...}}}]}, |
| 11 | //! {"role": "tool", "tool_call_id": "...", "content": "..."} |
| 12 | //! ]} |
| 13 | //! ``` |
| 14 | //! 모르는 필드는 그대로 보존하며, 수정하지 않은 줄은 원문 그대로 다시 저장된다. |
| 15 | |
| 16 | use serde_json::{Map, Value}; |
| 17 | use std::cell::OnceCell; |
| 18 | use std::fmt; |
| 19 | use std::io::Write; |
| 20 | use std::path::Path; |
| 21 | |
| 22 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 23 | pub enum Role { |
| 24 | System, |
| 25 | Tools, |
| 26 | Tool, |
| 27 | User, |
| 28 | Assistant, |
| 29 | } |
| 30 | |
| 31 | impl Role { |
| 32 | pub const ALL: [Role; 5] = [Role::System, Role::Tools, Role::User, Role::Assistant, Role::Tool]; |
| 33 | |
| 34 | pub fn as_str(self) -> &'static str { |
| 35 | match self { |
| 36 | Role::System => "system", |
| 37 | Role::Tools => "tools", |
| 38 | Role::Tool => "tool", |
| 39 | Role::User => "user", |
| 40 | Role::Assistant => "assistant", |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | pub fn parse(s: &str) -> Option<Role> { |
| 45 | Some(match s { |
| 46 | "system" => Role::System, |
| 47 | "tools" => Role::Tools, |
| 48 | "tool" => Role::Tool, |
| 49 | "user" => Role::User, |
| 50 | "assistant" => Role::Assistant, |
| 51 | _ => return None, |
| 52 | }) |
| 53 | } |
| 54 | |
| 55 | /// 앞 메시지의 역할만 보고 고르는 기본 역할. (도구 호출 여부까지 보려면 `Conversation::default_role_at`) |
| 56 | pub fn default_after(prev: Option<Role>) -> Role { |
| 57 | match prev { |
| 58 | None => Role::System, |
| 59 | Some(Role::System) => Role::Tools, |
| 60 | Some(Role::Tools) => Role::User, |
| 61 | Some(Role::Assistant) => Role::User, |
| 62 | Some(Role::User) | Some(Role::Tool) => Role::Assistant, |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | impl fmt::Display for Role { |
| 68 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 69 | f.write_str(self.as_str()) |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | const THINKING_KEYS: [&str; 3] = ["reasoning_content", "thinking", "reasoning"]; |
| 74 | const DEFAULT_THINKING_KEY: &str = "reasoning_content"; |
| 75 | |
| 76 | #[derive(Clone, Debug, PartialEq)] |
| 77 | pub struct ToolCall { |
| 78 | pub id: String, |
| 79 | pub name: String, |
| 80 | /// 편집용 문자열. JSON이면 저장할 때 객체로 기록한다(`args_as_string`이 아닐 때). |
| 81 | pub arguments: String, |
| 82 | /// 원본이 문자열로 인코딩된 arguments였는지 (OpenAI 형식). |
| 83 | pub args_as_string: bool, |
| 84 | pub extra: Map<String, Value>, |
| 85 | } |
| 86 | |
| 87 | impl Default for ToolCall { |
| 88 | fn default() -> Self { |
| 89 | ToolCall { |
| 90 | id: String::new(), |
| 91 | name: String::new(), |
| 92 | arguments: "{}".to_string(), |
| 93 | args_as_string: false, |
| 94 | extra: Map::new(), |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | #[derive(Clone, Debug, PartialEq)] |
| 100 | pub struct Message { |
| 101 | pub role: Role, |
| 102 | pub content: String, |
| 103 | /// content가 문자열이 아닌 JSON 값(배열/객체)이었는지. (예: tools 역할의 스키마 목록) |
| 104 | pub content_is_json: bool, |
| 105 | /// assistant 전용: 생각(추론) 내용. |
| 106 | pub thinking: String, |
| 107 | thinking_key: Option<String>, |
| 108 | /// assistant 전용: 도구 호출 목록. |
| 109 | pub tool_calls: Vec<ToolCall>, |
| 110 | /// tool 전용: 어떤 도구 호출에 대한 결과인지. |
| 111 | pub tool_call_id: String, |
| 112 | pub extra: Map<String, Value>, |
| 113 | } |
| 114 | |
| 115 | impl Message { |
| 116 | pub fn new(role: Role) -> Self { |
| 117 | Message { |
| 118 | role, |
| 119 | content: if role == Role::Tools { "[]".to_string() } else { String::new() }, |
| 120 | content_is_json: role == Role::Tools, |
| 121 | thinking: String::new(), |
| 122 | thinking_key: None, |
| 123 | tool_calls: Vec::new(), |
| 124 | tool_call_id: String::new(), |
| 125 | extra: Map::new(), |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | pub fn with_content(role: Role, content: impl Into<String>) -> Self { |
| 130 | let mut m = Message::new(role); |
| 131 | m.content = content.into(); |
| 132 | m |
| 133 | } |
| 134 | |
| 135 | /// 역할이 바뀌었을 때 content의 JSON 여부를 보정한다. |
| 136 | pub fn set_role(&mut self, role: Role) { |
| 137 | if self.role == role { |
| 138 | return; |
| 139 | } |
| 140 | let was_tools = self.role == Role::Tools; |
| 141 | self.role = role; |
| 142 | if was_tools { |
| 143 | // tools용 기본값([])은 다른 역할에서 의미가 없으므로 비우고, 일반 문자열로 저장한다. |
| 144 | if self.content.trim() == "[]" { |
| 145 | self.content.clear(); |
| 146 | } |
| 147 | self.content_is_json = false; |
| 148 | } |
| 149 | if role == Role::Tools { |
| 150 | self.content_is_json = true; |
| 151 | if self.content.trim().is_empty() { |
| 152 | self.content = "[]".to_string(); |
| 153 | } |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | pub fn from_value(v: &Value) -> Result<Message, String> { |
| 158 | let obj = v.as_object().ok_or("메시지가 JSON 객체가 아닙니다")?; |
| 159 | let role_str = obj.get("role").and_then(Value::as_str).ok_or("메시지에 role이 없습니다")?; |
| 160 | let role = Role::parse(role_str).ok_or_else(|| format!("알 수 없는 role: {role_str}"))?; |
| 161 | let mut msg = Message::new(role); |
| 162 | msg.content.clear(); |
| 163 | msg.content_is_json = false; |
| 164 | |
| 165 | for (k, val) in obj { |
| 166 | match k.as_str() { |
| 167 | "role" => {} |
| 168 | "content" => match val { |
| 169 | Value::String(s) => msg.content = s.clone(), |
| 170 | Value::Null => {} |
| 171 | other => { |
| 172 | msg.content = serde_json::to_string_pretty(other).unwrap_or_default(); |
| 173 | msg.content_is_json = true; |
| 174 | } |
| 175 | }, |
| 176 | key if role == Role::Assistant |
| 177 | && msg.thinking_key.is_none() |
| 178 | && THINKING_KEYS.contains(&key) |
| 179 | && (val.is_string() || val.is_null()) => |
| 180 | { |
| 181 | msg.thinking = val.as_str().unwrap_or_default().to_string(); |
| 182 | msg.thinking_key = Some(key.to_string()); |
| 183 | } |
| 184 | "tool_calls" if val.is_array() => { |
| 185 | for tc in val.as_array().unwrap() { |
| 186 | msg.tool_calls.push(parse_tool_call(tc)?); |
| 187 | } |
| 188 | } |
| 189 | "tool_call_id" if val.is_string() => { |
| 190 | msg.tool_call_id = val.as_str().unwrap().to_string(); |
| 191 | } |
| 192 | _ => { |
| 193 | msg.extra.insert(k.clone(), val.clone()); |
| 194 | } |
| 195 | } |
| 196 | } |
| 197 | Ok(msg) |
| 198 | } |
| 199 | |
| 200 | pub fn to_value(&self) -> Value { |
| 201 | let mut m = Map::new(); |
| 202 | m.insert("role".into(), Value::String(self.role.as_str().into())); |
| 203 | if self.role == Role::Assistant && (!self.thinking.is_empty() || self.thinking_key.is_some()) { |
| 204 | let key = self.thinking_key.as_deref().unwrap_or(DEFAULT_THINKING_KEY); |
| 205 | m.insert(key.into(), Value::String(self.thinking.clone())); |
| 206 | } |
| 207 | let content = if self.content_is_json { |
| 208 | serde_json::from_str::<Value>(&self.content) |
| 209 | .unwrap_or_else(|_| Value::String(self.content.clone())) |
| 210 | } else { |
| 211 | Value::String(self.content.clone()) |
| 212 | }; |
| 213 | m.insert("content".into(), content); |
| 214 | if !self.tool_calls.is_empty() { |
| 215 | let calls = self.tool_calls.iter().map(tool_call_to_value).collect(); |
| 216 | m.insert("tool_calls".into(), Value::Array(calls)); |
| 217 | } |
| 218 | if !self.tool_call_id.is_empty() { |
| 219 | m.insert("tool_call_id".into(), Value::String(self.tool_call_id.clone())); |
| 220 | } |
| 221 | for (k, v) in &self.extra { |
| 222 | m.insert(k.clone(), v.clone()); |
| 223 | } |
| 224 | Value::Object(m) |
| 225 | } |
| 226 | |
| 227 | /// 사이드바/목록에 보여줄 한 줄 요약. |
| 228 | pub fn summary(&self) -> String { |
| 229 | let src = if !self.content.trim().is_empty() { |
| 230 | self.content.as_str() |
| 231 | } else if !self.tool_calls.is_empty() { |
| 232 | return format!("[도구 호출 {}개]", self.tool_calls.len()); |
| 233 | } else { |
| 234 | self.thinking.as_str() |
| 235 | }; |
| 236 | one_line(src, 120) |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | fn parse_tool_call(v: &Value) -> Result<ToolCall, String> { |
| 241 | let obj = v.as_object().ok_or("tool_calls 항목이 객체가 아닙니다")?; |
| 242 | let mut tc = ToolCall { arguments: String::new(), ..Default::default() }; |
| 243 | // OpenAI 형식({"function": {...}})과 평평한 형식({"name", "arguments"}) 모두 허용. |
| 244 | let (func, nested) = match obj.get("function").and_then(Value::as_object) { |
| 245 | Some(f) => (f, true), |
| 246 | None => (obj, false), |
| 247 | }; |
| 248 | tc.name = func.get("name").and_then(Value::as_str).unwrap_or_default().to_string(); |
| 249 | match func.get("arguments") { |
| 250 | Some(Value::String(s)) => { |
| 251 | tc.args_as_string = true; |
| 252 | // 보기 좋게 펼쳐서 편집하도록 한다. |
| 253 | tc.arguments = match serde_json::from_str::<Value>(s) { |
| 254 | Ok(v) => serde_json::to_string_pretty(&v).unwrap_or_else(|_| s.clone()), |
| 255 | Err(_) => s.clone(), |
| 256 | }; |
| 257 | } |
| 258 | Some(other) => tc.arguments = serde_json::to_string_pretty(other).unwrap_or_default(), |
| 259 | None => tc.arguments = "{}".into(), |
| 260 | } |
| 261 | for (k, val) in obj { |
| 262 | let skip = match k.as_str() { |
| 263 | "id" => { |
| 264 | tc.id = val.as_str().unwrap_or_default().to_string(); |
| 265 | true |
| 266 | } |
| 267 | "function" => nested, |
| 268 | "type" => nested && val == "function", |
| 269 | "name" | "arguments" => !nested, |
| 270 | _ => false, |
| 271 | }; |
| 272 | if !skip { |
| 273 | tc.extra.insert(k.clone(), val.clone()); |
| 274 | } |
| 275 | } |
| 276 | Ok(tc) |
| 277 | } |
| 278 | |
| 279 | fn tool_call_to_value(tc: &ToolCall) -> Value { |
| 280 | let args = match serde_json::from_str::<Value>(&tc.arguments) { |
| 281 | Ok(v) if tc.args_as_string => Value::String(serde_json::to_string(&v).unwrap_or_default()), |
| 282 | Ok(v) => v, |
| 283 | Err(_) => Value::String(tc.arguments.clone()), |
| 284 | }; |
| 285 | let mut func = Map::new(); |
| 286 | func.insert("name".into(), Value::String(tc.name.clone())); |
| 287 | func.insert("arguments".into(), args); |
| 288 | let mut m = Map::new(); |
| 289 | if !tc.id.is_empty() { |
| 290 | m.insert("id".into(), Value::String(tc.id.clone())); |
| 291 | } |
| 292 | m.insert("type".into(), Value::String("function".into())); |
| 293 | m.insert("function".into(), Value::Object(func)); |
| 294 | for (k, v) in &tc.extra { |
| 295 | m.insert(k.clone(), v.clone()); |
| 296 | } |
| 297 | Value::Object(m) |
| 298 | } |
| 299 | |
| 300 | #[derive(Clone, Debug, Default, PartialEq)] |
| 301 | pub struct Conversation { |
| 302 | pub messages: Vec<Message>, |
| 303 | pub extra: Map<String, Value>, |
| 304 | } |
| 305 | |
| 306 | impl Conversation { |
| 307 | pub fn parse_line(line: &str) -> Result<Conversation, String> { |
| 308 | let v: Value = serde_json::from_str(line).map_err(|e| format!("JSON 오류: {e}"))?; |
| 309 | let obj = v.as_object().ok_or("줄이 JSON 객체가 아닙니다")?; |
| 310 | let mut conv = Conversation::default(); |
| 311 | for (k, val) in obj { |
| 312 | if k == "messages" { |
| 313 | let arr = val.as_array().ok_or("messages가 배열이 아닙니다")?; |
| 314 | for (i, m) in arr.iter().enumerate() { |
| 315 | conv.messages.push(Message::from_value(m).map_err(|e| format!("메시지 #{}: {e}", i + 1))?); |
| 316 | } |
| 317 | } else { |
| 318 | conv.extra.insert(k.clone(), val.clone()); |
| 319 | } |
| 320 | } |
| 321 | Ok(conv) |
| 322 | } |
| 323 | |
| 324 | pub fn to_line(&self) -> String { |
| 325 | let mut m = Map::new(); |
| 326 | m.insert("messages".into(), Value::Array(self.messages.iter().map(Message::to_value).collect())); |
| 327 | for (k, v) in &self.extra { |
| 328 | m.insert(k.clone(), v.clone()); |
| 329 | } |
| 330 | serde_json::to_string(&Value::Object(m)).unwrap_or_default() |
| 331 | } |
| 332 | |
| 333 | pub fn preview(&self) -> String { |
| 334 | let first = self |
| 335 | .messages |
| 336 | .iter() |
| 337 | .find(|m| m.role == Role::User) |
| 338 | .or_else(|| self.messages.first()); |
| 339 | match first { |
| 340 | Some(m) => format!("({}) {}", self.messages.len(), m.summary()), |
| 341 | None => "(빈 대화)".to_string(), |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | /// `pos` 위치에 새 메시지를 넣을 때(Ctrl+A)의 기본 역할. |
| 346 | /// - 도구를 호출한 assistant 다음 → tool |
| 347 | /// - tool 다음: 직전 assistant의 호출 중 결과가 아직 없는 것이 남았으면 tool, 아니면 assistant |
| 348 | /// - 나머지는 `Role::default_after` (system → tools, assistant → user …) |
| 349 | pub fn default_role_at(&self, pos: usize) -> Role { |
| 350 | let before = &self.messages[..pos.min(self.messages.len())]; |
| 351 | let Some(prev) = before.last() else { return Role::System }; |
| 352 | match prev.role { |
| 353 | Role::Assistant if !prev.tool_calls.is_empty() => Role::Tool, |
| 354 | Role::Tool => { |
| 355 | let pending = before.iter().rposition(|m| m.role == Role::Assistant).is_some_and(|ai| { |
| 356 | let results = before[ai + 1..].iter().filter(|m| m.role == Role::Tool).count(); |
| 357 | results < before[ai].tool_calls.len() |
| 358 | }); |
| 359 | if pending { Role::Tool } else { Role::Assistant } |
| 360 | } |
| 361 | r => Role::default_after(Some(r)), |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | // ---- 메시지 단위 편집. 모두 새 선택 영역(인덱스 목록)을 돌려준다. ---- |
| 366 | |
| 367 | /// 선택한 메시지들을 복제해 마지막 선택 메시지 바로 뒤에 넣는다. 복제본이 선택된다. |
| 368 | pub fn duplicate(&mut self, sel: &[usize]) -> Vec<usize> { |
| 369 | let mut sel: Vec<usize> = sel.iter().copied().filter(|&i| i < self.messages.len()).collect(); |
| 370 | sel.sort_unstable(); |
| 371 | sel.dedup(); |
| 372 | let Some(&last) = sel.last() else { return Vec::new() }; |
| 373 | let copies: Vec<Message> = sel.iter().map(|&i| self.messages[i].clone()).collect(); |
| 374 | let n = copies.len(); |
| 375 | self.messages.splice(last + 1..last + 1, copies); |
| 376 | (last + 1..last + 1 + n).collect() |
| 377 | } |
| 378 | |
| 379 | pub fn delete(&mut self, sel: &[usize]) { |
| 380 | let mut sel: Vec<usize> = sel.to_vec(); |
| 381 | sel.sort_unstable(); |
| 382 | sel.dedup(); |
| 383 | for &i in sel.iter().rev() { |
| 384 | if i < self.messages.len() { |
| 385 | self.messages.remove(i); |
| 386 | } |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | /// 선택한 메시지들을 한 칸 위로. 맨 위에 붙은 묶음은 움직이지 않는다. |
| 391 | pub fn move_up(&mut self, sel: &[usize]) -> Vec<usize> { |
| 392 | let n = self.messages.len(); |
| 393 | let mut flags = vec![false; n]; |
| 394 | for &i in sel { |
| 395 | if i < n { |
| 396 | flags[i] = true; |
| 397 | } |
| 398 | } |
| 399 | for i in 1..n { |
| 400 | if flags[i] && !flags[i - 1] { |
| 401 | self.messages.swap(i, i - 1); |
| 402 | flags.swap(i, i - 1); |
| 403 | } |
| 404 | } |
| 405 | (0..n).filter(|&i| flags[i]).collect() |
| 406 | } |
| 407 | |
| 408 | /// 선택한 메시지들을 한 칸 아래로. 맨 아래에 붙은 묶음은 움직이지 않는다. |
| 409 | pub fn move_down(&mut self, sel: &[usize]) -> Vec<usize> { |
| 410 | let n = self.messages.len(); |
| 411 | let mut flags = vec![false; n]; |
| 412 | for &i in sel { |
| 413 | if i < n { |
| 414 | flags[i] = true; |
| 415 | } |
| 416 | } |
| 417 | for i in (0..n.saturating_sub(1)).rev() { |
| 418 | if flags[i] && !flags[i + 1] { |
| 419 | self.messages.swap(i, i + 1); |
| 420 | flags.swap(i, i + 1); |
| 421 | } |
| 422 | } |
| 423 | (0..n).filter(|&i| flags[i]).collect() |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | pub fn one_line(s: &str, max_chars: usize) -> String { |
| 428 | let mut out = String::new(); |
| 429 | let mut count = 0; |
| 430 | let mut last_space = false; |
| 431 | for ch in s.trim().chars() { |
| 432 | let ch = if ch.is_whitespace() { ' ' } else { ch }; |
| 433 | if ch == ' ' && last_space { |
| 434 | continue; |
| 435 | } |
| 436 | last_space = ch == ' '; |
| 437 | if count >= max_chars { |
| 438 | out.push('…'); |
| 439 | break; |
| 440 | } |
| 441 | out.push(ch); |
| 442 | count += 1; |
| 443 | } |
| 444 | out |
| 445 | } |
| 446 | |
| 447 | /// 데이터셋의 한 줄. 지연 파싱: 화면에 필요할 때만 파싱하고, |
| 448 | /// 수정되지 않은 줄은 원문(raw)을 그대로 저장한다. |
| 449 | #[derive(Clone, Debug)] |
| 450 | pub struct Entry { |
| 451 | raw: Option<String>, |
| 452 | conv: Option<Conversation>, |
| 453 | error: Option<String>, |
| 454 | preview: OnceCell<String>, |
| 455 | } |
| 456 | |
| 457 | impl Entry { |
| 458 | pub fn from_raw(raw: String) -> Self { |
| 459 | Entry { raw: Some(raw), conv: None, error: None, preview: OnceCell::new() } |
| 460 | } |
| 461 | |
| 462 | pub fn from_conv(conv: Conversation) -> Self { |
| 463 | Entry { raw: None, conv: Some(conv), error: None, preview: OnceCell::new() } |
| 464 | } |
| 465 | |
| 466 | /// 파싱해서 대화를 돌려준다. 실패하면 오류 메시지. |
| 467 | pub fn conversation(&mut self) -> Result<&Conversation, String> { |
| 468 | if self.conv.is_none() && self.error.is_none() { |
| 469 | match Conversation::parse_line(self.raw.as_deref().unwrap_or_default()) { |
| 470 | Ok(c) => self.conv = Some(c), |
| 471 | Err(e) => self.error = Some(e), |
| 472 | } |
| 473 | } |
| 474 | match (&self.conv, &self.error) { |
| 475 | (Some(c), _) => Ok(c), |
| 476 | (None, Some(e)) => Err(e.clone()), |
| 477 | (None, None) => unreachable!(), |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | pub fn parsed(&self) -> Option<&Conversation> { |
| 482 | self.conv.as_ref() |
| 483 | } |
| 484 | |
| 485 | pub fn raw(&self) -> Option<&str> { |
| 486 | self.raw.as_deref() |
| 487 | } |
| 488 | |
| 489 | pub fn has_error(&self) -> bool { |
| 490 | self.error.is_some() |
| 491 | } |
| 492 | |
| 493 | pub fn preview(&self) -> &str { |
| 494 | self.preview.get_or_init(|| { |
| 495 | if let Some(c) = &self.conv { |
| 496 | return c.preview(); |
| 497 | } |
| 498 | match Conversation::parse_line(self.raw.as_deref().unwrap_or_default()) { |
| 499 | Ok(c) => c.preview(), |
| 500 | Err(e) => format!("⚠ {}", one_line(&e, 80)), |
| 501 | } |
| 502 | }) |
| 503 | } |
| 504 | |
| 505 | pub fn to_line(&self) -> String { |
| 506 | match (&self.raw, &self.conv) { |
| 507 | (Some(raw), _) => raw.clone(), |
| 508 | (None, Some(c)) => c.to_line(), |
| 509 | (None, None) => String::new(), |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | /// 메모리를 아끼기 위해 수정되지 않은(원문이 있는) 파싱 결과를 버린다. |
| 514 | pub fn drop_parsed_cache(&mut self) { |
| 515 | if self.raw.is_some() { |
| 516 | self.conv = None; |
| 517 | self.error = None; |
| 518 | } |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | pub fn load_entries(path: &Path) -> std::io::Result<Vec<Entry>> { |
| 523 | let text = std::fs::read_to_string(path)?; |
| 524 | let text = text.strip_prefix('\u{feff}').unwrap_or(&text); |
| 525 | Ok(text |
| 526 | .lines() |
| 527 | .map(|l| l.trim_end_matches('\r')) |
| 528 | .filter(|l| !l.trim().is_empty()) |
| 529 | .map(|l| Entry::from_raw(l.to_string())) |
| 530 | .collect()) |
| 531 | } |
| 532 | |
| 533 | /// 임시 파일에 쓴 뒤 rename 하여, 저장 도중 문제가 생겨도 원본이 깨지지 않게 한다. |
| 534 | pub fn save_entries(path: &Path, entries: &[Entry]) -> std::io::Result<()> { |
| 535 | let file_name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); |
| 536 | let tmp = path.with_file_name(format!(".{file_name}.tmp")); |
| 537 | { |
| 538 | let f = std::fs::File::create(&tmp)?; |
| 539 | let mut w = std::io::BufWriter::new(f); |
| 540 | for e in entries { |
| 541 | w.write_all(e.to_line().as_bytes())?; |
| 542 | w.write_all(b"\n")?; |
| 543 | } |
| 544 | w.flush()?; |
| 545 | w.get_ref().sync_all()?; |
| 546 | } |
| 547 | std::fs::rename(&tmp, path) |
| 548 | } |