1import os
2import shutil
3import subprocess
4from pathlib import Path
5from typing import List, Optional
6
7from xdg import BaseDirectory # type: ignore
8
9from qpm import profiles
10from qpm.profiles import Profile
11from qpm.utils import error, user_data_dir
12
13
14def from_session(
15 session: str,
16 profile_name: Optional[str] = None,
17 profile_dir: Optional[Path] = None,
18 desktop_file: bool = True,
19) -> Optional[Profile]:
20 if session.endswith(".yml"):
21 session_file = Path(session).expanduser()
22 session_name = session_file.stem
23 else:
24 session_name = session
25 session_file = user_data_dir() / "sessions" / (session_name + ".yml")
26 if not session_file.is_file():
27 error(f"{session_file} is not a file")
28 return None
29
30 profile = Profile(profile_name or session_name, profile_dir)
31 if not profiles.new_profile(profile, desktop_file=desktop_file):
32 return None
33
34 session_dir = profile.root / "data" / "sessions"
35 session_dir.mkdir(parents=True)
36 shutil.copy(session_file, session_dir / "_autosave.yml")
37
38 return profile
39
40
41def launch(
42 profile: Profile, strict: bool, foreground: bool, qb_args: List[str]
43) -> bool:
44 if not profiles.ensure_profile_exists(profile, not strict):
45 return False
46
47 args = profile.cmdline() + qb_args
48 if foreground:
49 os.execlp("qutebrowser", *args)
50 else:
51 p = subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
52 try:
53 # give qb a chance to validate input before returning to shell
54 stdout, stderr = p.communicate(timeout=0.1)
55 print(stderr.decode(errors="ignore"), end="")
56 except subprocess.TimeoutExpired:
57 pass
58
59 return True
60
61
62def desktop(profile: Profile):
63 if profile.exists():
64 profiles.create_desktop_file(profile)
65 else:
66 error(f"profile {profile.name} not found at {profile.root}")
67
68
69DEFAULT_PROFILE_DIR = Path(BaseDirectory.xdg_data_home) / "qutebrowser-profiles"
70
71
72def list_() -> None:
73 for profile in sorted(DEFAULT_PROFILE_DIR.iterdir()):
74 print(profile.name)
75
76
77def edit(profile: Profile):
78 if not profile.exists():
79 error(f"profile {profile.name} not found at {profile.root}")
80 return
81 editor = os.environ.get("VISUAL") or os.environ.get("EDITOR") or "vim"
82 os.execlp(editor, editor, str(profile.root / "config" / "config.py"))