diff --git a/scripts/search.py b/scripts/search.py index 988f95d..442e7ae 100755 --- a/scripts/search.py +++ b/scripts/search.py @@ -2,18 +2,19 @@ """Fuzzy search artists in playlists.db and show their similar artists.""" import curses +import os import sqlite3 import sys from pathlib import Path def find_db(): - """Look for playlists.db in cwd, then script's parent dir.""" - for base in [Path.cwd(), Path(__file__).resolve().parent.parent]: - p = base / "playlists.db" - if p.exists(): - return str(p) - print("Could not find playlists.db", file=sys.stderr) + """Find playlists.db in XDG data dir.""" + data_home = os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share") + p = Path(data_home) / "playlists" / "playlists.db" + if p.exists(): + return str(p) + print(f"Could not find {p}", file=sys.stderr) sys.exit(1) diff --git a/src/db.rs b/src/db.rs index 7badf16..ac48415 100644 --- a/src/db.rs +++ b/src/db.rs @@ -2,7 +2,7 @@ use rusqlite::Connection; use crate::lastfm::{SimilarArtist, TopTrack}; -pub fn open(path: &str) -> Result { +pub fn open(path: &std::path::Path) -> Result { let conn = Connection::open(path)?; conn.execute_batch( "CREATE TABLE IF NOT EXISTS artists ( diff --git a/src/main.rs b/src/main.rs index 69586fe..42ff0d8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,11 +7,23 @@ mod tui; use std::collections::HashMap; use std::env; -use std::path::Path; +use std::path::{Path, PathBuf}; use rand::distr::weighted::WeightedIndex; use rand::prelude::*; +fn db_path() -> PathBuf { + let data_dir = env::var("XDG_DATA_HOME") + .map(PathBuf::from) + .unwrap_or_else(|_| { + let home = env::var("HOME").expect("HOME not set"); + PathBuf::from(home).join(".local/share") + }); + let dir = data_dir.join("playlists"); + std::fs::create_dir_all(&dir).expect("failed to create data directory"); + dir.join("playlists.db") +} + fn usage(program: &str) -> ! { eprintln!("Usage:"); eprintln!(" {program} index [-v] "); @@ -50,7 +62,7 @@ fn cmd_index(args: &[String]) { std::process::exit(1); } - let conn = db::open("playlists.db").expect("failed to open database"); + let conn = db::open(&db_path()).expect("failed to open database"); let lastfm = lastfm::LastfmClient::new(api_key); let dir = Path::new(rest[0].as_str()); @@ -166,7 +178,7 @@ fn cmd_build(args: &[String]) { } dotenvy::dotenv().ok(); - let conn = db::open("playlists.db").expect("failed to open database"); + let conn = db::open(&db_path()).expect("failed to open database"); let (artist_mbid, seed_name) = if let Some(file_arg) = rest.first() { let path = Path::new(file_arg.as_str());