visualmode-tracker 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
py_vmt/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ import importlib.metadata
2
+
3
+ __version__ = importlib.metadata.version("visualmode-tracker")
py_vmt/cli.py ADDED
@@ -0,0 +1,628 @@
1
+ import collections
2
+ import json
3
+ import sqlite3
4
+ from datetime import UTC, date, datetime, timedelta
5
+ from pathlib import Path
6
+ from sqlite3 import Connection
7
+ from typing import Protocol
8
+
9
+ import click
10
+ from platformdirs import user_config_dir, user_data_dir
11
+
12
+ from py_vmt import db, time_helpers
13
+ from py_vmt.file_utils import atomic_write
14
+ from py_vmt.session import Session
15
+
16
+ type DateToSessionDict = collections.defaultdict[date, list[Session]]
17
+
18
+
19
+ class SessionRepository(Protocol):
20
+ def active_session(self) -> Session | None: ...
21
+ def write_active_session(self, session) -> None: ...
22
+ def all_sessions(self) -> list[Session]: ...
23
+ def clear_active_session(self) -> None: ...
24
+ def complete_active_session(self, session) -> None: ...
25
+
26
+
27
+ class SqliteRepository:
28
+ def __init__(self, *, data_dir: Path) -> None:
29
+ self.db_file: Path = data_dir / "sessions.db"
30
+ self.conn: Connection = sqlite3.connect(self.db_file)
31
+
32
+ # Enable Row Factory for the result set
33
+ # https://docs.python.org/3/library/sqlite3.html#how-to-create-and-use-row-factories
34
+ self.conn.row_factory = sqlite3.Row
35
+
36
+ # always migrate the DB as part of initialization, this will mostly be a no-op
37
+ db.migrate(self.conn)
38
+
39
+ def active_session(self) -> Session | None:
40
+ fetch_active_session_sql = """
41
+ select
42
+ sessions.id as session_id,
43
+ sessions.active,
44
+ projects.name as project_name,
45
+ sessions.start_time,
46
+ sessions.end_time
47
+ from sessions
48
+ join projects on sessions.project_id = projects.id
49
+ where sessions.active = 1;
50
+ """
51
+
52
+ result = self.conn.execute(fetch_active_session_sql)
53
+ raw_active_session = result.fetchone()
54
+
55
+ if raw_active_session is not None:
56
+ fetch_tags_for_active_session_sql = """
57
+ select tags.name
58
+ from tags
59
+ join session_tags on session_tags.tag_id = tags.id
60
+ where session_tags.session_id = ?;
61
+ """
62
+ result = self.conn.execute(
63
+ fetch_tags_for_active_session_sql, [raw_active_session["session_id"]]
64
+ )
65
+ tag_names = [row[0] for row in result.fetchall()]
66
+
67
+ data = {
68
+ "project_name": raw_active_session["project_name"],
69
+ "start_time": raw_active_session["start_time"],
70
+ "tags": tag_names,
71
+ "end_time": raw_active_session["end_time"],
72
+ }
73
+ return Session.hydrate(data)
74
+
75
+ def write_active_session(self, session: Session) -> None:
76
+ self.write_session_with_project(session, active=True)
77
+
78
+ def all_sessions(self) -> list[Session]:
79
+ fetch_all_sessions_sql = """
80
+ select
81
+ sessions.id as session_id,
82
+ sessions.active,
83
+ projects.name as project_name,
84
+ sessions.start_time,
85
+ sessions.end_time
86
+ from sessions
87
+ join projects on sessions.project_id = projects.id;
88
+ """
89
+ result = self.conn.execute(fetch_all_sessions_sql)
90
+ raw_sessions = result.fetchall()
91
+
92
+ sessions = []
93
+ for raw_session in raw_sessions:
94
+ # TODO: this is an N+1, acceptable for now, but refactor later
95
+ fetch_tags_for_active_session_sql = """
96
+ select tags.name
97
+ from tags
98
+ join session_tags on session_tags.tag_id = tags.id
99
+ where session_tags.session_id = ?;
100
+ """
101
+ result = self.conn.execute(
102
+ fetch_tags_for_active_session_sql, [raw_session["session_id"]]
103
+ )
104
+ tag_names = [row[0] for row in result.fetchall()]
105
+
106
+ data = {
107
+ "project_name": raw_session["project_name"],
108
+ "start_time": raw_session["start_time"],
109
+ "tags": tag_names,
110
+ "end_time": raw_session["end_time"],
111
+ }
112
+ sessions.append(Session.hydrate(data))
113
+
114
+ return sessions
115
+
116
+ def complete_active_session(self, session: Session) -> None:
117
+ # Do we want some kind of assertion that `sessions` matches the currently active session?
118
+
119
+ with self.conn:
120
+ self.conn.execute(
121
+ """
122
+ update sessions set active = :active, end_time = :end_time where active = 1;
123
+ """,
124
+ {"active": 0, "end_time": session.end_time},
125
+ )
126
+
127
+ def clear_active_session(self) -> None:
128
+ # Delete the current active session if there is one
129
+ with self.conn:
130
+ self.conn.execute("""
131
+ delete from sessions where active = 1;
132
+ """)
133
+
134
+ def write_session_with_project(self, session, *, active=False) -> None:
135
+ with self.conn:
136
+ if active:
137
+ # Delete the current active session if there is one
138
+ self.conn.execute("""
139
+ delete from sessions where active = 1;
140
+ """)
141
+
142
+ # Upsert tags if there are any
143
+ tag_ids = []
144
+ if session.tags:
145
+ # build the upsert query with the right number of slots
146
+ placeholders = ", ".join(["(?)"] * len(session.tags))
147
+ upsert_tags_sql = f"""
148
+ insert into tags (name) values {placeholders}
149
+ on conflict (name) do update set name = excluded.name
150
+ returning id;
151
+ """
152
+ cursor = self.conn.execute(upsert_tags_sql, session.tags)
153
+ tag_ids = [row[0] for row in cursor.fetchall()]
154
+
155
+ # Upsert (find or create) the project based on `session.project_name`
156
+ cursor = self.conn.execute(
157
+ """
158
+ insert into projects (name) values (:project_name)
159
+ on conflict (name) do update set name = excluded.name
160
+ returning id;
161
+ """,
162
+ {"project_name": session.project_name},
163
+ )
164
+ project_id = cursor.fetchone()[0]
165
+
166
+ # Prepare `sessions` insert payload
167
+ session_data = {
168
+ "active": 1 if active else 0,
169
+ "project_id": project_id,
170
+ "start_time": datetime.isoformat(session.start_time),
171
+ "end_time": None,
172
+ }
173
+
174
+ if session.end_time:
175
+ session_data["end_time"] = datetime.isoformat(session.end_time)
176
+
177
+ # Insert the new active session
178
+ cursor = self.conn.execute(
179
+ """
180
+ insert into sessions (active, project_id, start_time, end_time)
181
+ values (:active, :project_id, :start_time, :end_time)
182
+ returning id;
183
+ """,
184
+ session_data,
185
+ )
186
+ session_id = cursor.fetchone()[0]
187
+
188
+ if tag_ids:
189
+ # Apply tags to this session
190
+ placeholder = ", ".join(["(?, ?)"] * len(tag_ids))
191
+ # TODO: Figure out why the `on conflict do nothing` was needed, we shouldn't be inserting any duplicates
192
+ session_to_tags_sql = f"""
193
+ insert into session_tags (session_id, tag_id) values {placeholder} on conflict do nothing;
194
+ """
195
+ # this is a list of tuples
196
+ # session_tag_pairs = [(session_id, tag_id) for tag_id in tag_ids]
197
+ #
198
+ # this is a flat list
199
+ sql_params = [
200
+ param for tag_id in tag_ids for param in (session_id, tag_id)
201
+ ]
202
+ self.conn.execute(session_to_tags_sql, sql_params)
203
+
204
+
205
+ class JsonRepository:
206
+ def __init__(self, *, data_dir: Path) -> None:
207
+ self.active_session_file: Path = data_dir / "active_session.json"
208
+ self.session_log_file: Path = data_dir / "session_log.json"
209
+
210
+ def active_session(self) -> Session | None:
211
+ if self.active_session_file.exists():
212
+ # TODO: good place to use Pydantic eventually
213
+ session_data = json.loads(self.active_session_file.read_text()) or {}
214
+ if "project_name" in session_data:
215
+ return Session.hydrate(session_data)
216
+
217
+ return None
218
+
219
+ def write_active_session(self, session: Session) -> None:
220
+ with atomic_write(self.active_session_file) as file:
221
+ json.dump(session.marshal(), file)
222
+
223
+ def complete_active_session(self, session: Session) -> None:
224
+ existing_sessions = self.load_raw_session_log()
225
+
226
+ writeable_session = session.marshal()
227
+ existing_sessions.append(writeable_session)
228
+
229
+ with atomic_write(self.session_log_file) as file:
230
+ json.dump(existing_sessions, file)
231
+
232
+ self.clear_active_session()
233
+
234
+ def load_raw_session_log(self) -> list[dict]:
235
+ if self.session_log_file.exists():
236
+ return json.loads(self.session_log_file.read_text())
237
+
238
+ return []
239
+
240
+ def all_sessions(self) -> list[Session]:
241
+ return [Session.hydrate(raw_sesh) for raw_sesh in self.load_raw_session_log()]
242
+
243
+ def clear_active_session(self) -> None:
244
+ with atomic_write(self.active_session_file) as file:
245
+ json.dump({}, file)
246
+
247
+
248
+ class CliContext:
249
+ def __init__(self, *, verbose: bool) -> None:
250
+ self.verbose: bool = verbose
251
+ self.data_dir: Path = CliContext.get_data_dir()
252
+ self.config = self.read_config()
253
+ self.active_session: Session | None = None
254
+ self.repo = self._initialize_configured_repo(data_dir=self.data_dir)
255
+ self.active_session = self.repo.active_session()
256
+
257
+ def start_active_session(
258
+ self, project_name: str, tags: list[str], start_time: datetime
259
+ ) -> None:
260
+ new_session = Session(start_time, project_name, tags=tags)
261
+ self.repo.write_active_session(new_session)
262
+
263
+ def stop_active_session(self, at: datetime, round: bool = False) -> Session:
264
+ assert self.active_session, (
265
+ "An active session is required in order to stop an active session"
266
+ )
267
+
268
+ session = self.active_session
269
+ session.stop(at, round)
270
+
271
+ self.repo.complete_active_session(session)
272
+
273
+ # clear active session state
274
+ self.active_session = None
275
+
276
+ return session
277
+
278
+ def cancel_active_session(self) -> Session:
279
+ assert self.active_session, (
280
+ "An active session is required in order to cancel an active session"
281
+ )
282
+
283
+ session = self.active_session
284
+ session.stop()
285
+
286
+ # clear out active session file
287
+ self.repo.clear_active_session()
288
+
289
+ # clear active session state
290
+ self.active_session = None
291
+
292
+ return session
293
+
294
+ def load_latest_sessions(self) -> DateToSessionDict:
295
+ existing_sessions = self.repo.all_sessions()
296
+
297
+ days_ago_list = [timedelta(days=neg_index) for neg_index in range(0, -7, -1)]
298
+ last_seven_days = [
299
+ (datetime.now() + days_ago).date() for days_ago in days_ago_list
300
+ ]
301
+ sessions_grouped_by_day: DateToSessionDict = collections.defaultdict(list)
302
+
303
+ for previous_date in last_seven_days:
304
+ sessions_for_date = [
305
+ sesh
306
+ for sesh in existing_sessions
307
+ if sesh.start_time.date() == previous_date
308
+ ]
309
+
310
+ if sessions_for_date:
311
+ sessions_for_date.sort()
312
+ sessions_grouped_by_day[previous_date] = sessions_for_date
313
+
314
+ return sessions_grouped_by_day
315
+ # TODO: determine if there is anything to preserve from the following
316
+ # comment, otherwise delete it.
317
+ #
318
+ # find all sessions in the last 7 days
319
+ #
320
+ # Note: we care about local time, not UTC
321
+ #
322
+ # If we are aggregating the sessions by day, where does a session that
323
+ # spans two days go?
324
+ # Probably it goes in the day it started in.
325
+ # If I have a session that starts at 11pm and goes until 2am.
326
+ # I suppose that is a late night session, so it should be attributed to
327
+ # that day.
328
+ # And then anything after midnight we can treat as part of the next day.
329
+ # for sesh in existing_sessions:
330
+ # sesh["start_time"]
331
+
332
+ def load_most_recent_session(self) -> Session | None:
333
+ sessions_by_date = self.load_latest_sessions()
334
+
335
+ if not sessions_by_date:
336
+ return None
337
+
338
+ latest_date = next(iter(sessions_by_date))
339
+ if latest_date:
340
+ sessions = sessions_by_date[latest_date]
341
+
342
+ if sessions:
343
+ return sessions[-1]
344
+
345
+ return None
346
+
347
+ @staticmethod
348
+ def get_data_dir() -> Path:
349
+ path = Path(user_data_dir("vmt"))
350
+ path.mkdir(parents=True, exist_ok=True)
351
+ return path
352
+
353
+ @staticmethod
354
+ def get_config_dir() -> Path:
355
+ path = Path(user_config_dir("vmt"))
356
+ path.mkdir(parents=True, exist_ok=True)
357
+ return path
358
+
359
+ @staticmethod
360
+ def read_config() -> dict:
361
+ config_dir: Path = CliContext.get_config_dir()
362
+ config_file: Path = config_dir / "config.json"
363
+
364
+ if config_file.exists():
365
+ return json.loads(config_file.read_text())
366
+
367
+ return {}
368
+
369
+ _REPOS: dict[str, type[SessionRepository]] = {
370
+ "json": JsonRepository,
371
+ "sqlite": SqliteRepository,
372
+ }
373
+
374
+ def _initialize_configured_repo(self, **config) -> SessionRepository:
375
+ default_format = "sqlite"
376
+ format = self.config.get("storage_format", default_format)
377
+ try:
378
+ return self._REPOS[format](**config)
379
+ except KeyError:
380
+ raise ValueError(f"Unknown storage_format: {format!r}")
381
+
382
+
383
+ # This decorator allows for passing the `CliContext` object
384
+ # directly to each command handler
385
+ pass_cli = click.make_pass_decorator(CliContext)
386
+
387
+
388
+ # define top-level CLI group
389
+ @click.group(name="vmt")
390
+ @click.option(
391
+ "--verbose",
392
+ "-v",
393
+ help="See extra output when running commands",
394
+ is_flag=True,
395
+ )
396
+ @click.pass_context
397
+ @click.version_option(prog_name="vmt")
398
+ def cli(ctx: click.Context, verbose: bool):
399
+ ctx.ensure_object(dict)
400
+ ctx.obj = CliContext(verbose=verbose)
401
+
402
+ if ctx.obj.verbose:
403
+ click.echo("[ running `vmt` in verbose mode ]")
404
+
405
+
406
+ def validate_start_at(_ctx, _param, value: str | None) -> datetime:
407
+ now = datetime.now(UTC)
408
+
409
+ if value is None:
410
+ return now
411
+
412
+ past_time = time_helpers.parse_to_datetime(value)
413
+
414
+ if past_time is None or past_time > now:
415
+ raise click.BadParameter("must be a relative time in the past")
416
+
417
+ return past_time
418
+
419
+
420
+ class AcceptsTagsCommand(click.Command):
421
+ @staticmethod
422
+ def tag_shaped(arg: str) -> bool:
423
+ return len(arg) > 1 and arg.startswith("+")
424
+
425
+ def parse_args(self, ctx, args):
426
+ # remove `+` prefix and collect tags
427
+ tags = tuple(tag_arg[1:] for tag_arg in args if self.tag_shaped(tag_arg))
428
+ other_args = [arg for arg in args if not self.tag_shaped(arg)]
429
+
430
+ # process all other args first to let `ctx` settle
431
+ parsed_args = super().parse_args(ctx, other_args)
432
+
433
+ ctx.params["tags"] = tags
434
+
435
+ return parsed_args
436
+
437
+ # Add tags to usage line because Click won't automatically pick it since it
438
+ # is not using the option decorator syntax.
439
+ # e.g. `Usage: vmt start [OPTIONS] PROJECT_NAME [+TAG]...`
440
+ def collect_usage_pieces(self, ctx):
441
+ pieces = super().collect_usage_pieces(ctx)
442
+ pieces.append("[+TAG]...")
443
+ return pieces
444
+
445
+ # Similarly, include a `Tags` section below options that explains the `+TAG` option.
446
+ # e.g.
447
+ # Tags:
448
+ # +TAG Attach one or more tags, e.g. +meeting +engineering
449
+ def format_options(self, ctx, formatter):
450
+ super().format_options(ctx, formatter)
451
+ with formatter.section("Tags"):
452
+ formatter.write_dl(
453
+ [("+TAG", "Attach one or more tags, e.g. +meeting +engineering")]
454
+ )
455
+
456
+
457
+ # define `start` subcommand
458
+ @cli.command(cls=AcceptsTagsCommand)
459
+ @click.argument("project-name")
460
+ @click.option(
461
+ "--at",
462
+ help='Relative time in past to start the time, e.g. "2 hours ago", "33 minutes ago"',
463
+ callback=validate_start_at,
464
+ )
465
+ @pass_cli
466
+ def start(
467
+ cli_ctx: CliContext, project_name: str, at: datetime, tags: list[str]
468
+ ) -> None:
469
+ if cli_ctx.active_session:
470
+ msg = f"Error: already tracking '{cli_ctx.active_session.project_name}'. Stop the current session first."
471
+ click.echo(msg)
472
+ click.get_current_context().abort()
473
+
474
+ formatted_start_time = time_helpers.format_timestamp(at)
475
+
476
+ cli_ctx.start_active_session(
477
+ project_name,
478
+ tags,
479
+ at,
480
+ )
481
+
482
+ temp_sesh = Session(at, project_name, tags=tags)
483
+ # • Started tracking 'visual-mode-tracking' [cli] at 11:11 AM
484
+ click.echo(
485
+ f"• Started tracking {temp_sesh.description()} at {formatted_start_time}"
486
+ )
487
+
488
+
489
+ # define `status` subcommand
490
+ @cli.command()
491
+ @pass_cli
492
+ def status(cli_ctx: CliContext) -> None:
493
+ sesh = cli_ctx.active_session
494
+ if sesh:
495
+ curr_time = datetime.now(UTC)
496
+ time_diff = curr_time - sesh.start_time
497
+ elapsed_time = time_helpers.format_time_delta(time_diff)
498
+ started_at = time_helpers.format_timestamp(sesh.start_time)
499
+
500
+ msg = f"• Tracking {sesh.description()} for {elapsed_time} (since {started_at})"
501
+ click.echo(msg)
502
+ else:
503
+ # read in most recent session
504
+ latest_sesh = cli_ctx.load_most_recent_session()
505
+
506
+ # • Not tracking
507
+ # Last: 'my-project' (1h30m) at 8:37AM
508
+ click.echo("• Not tracking")
509
+ if latest_sesh:
510
+ elapsed_time = time_helpers.format_time_delta(latest_sesh.duration())
511
+ started_at = time_helpers.format_timestamp(latest_sesh.start_time)
512
+
513
+ click.echo(
514
+ f"Last: {latest_sesh.description()} ({elapsed_time}) at {started_at}"
515
+ )
516
+
517
+
518
+ def validate_stop_at(ctx, _param, value: str | None) -> datetime:
519
+ now = datetime.now(UTC)
520
+
521
+ if value is None:
522
+ return now
523
+
524
+ past_time = time_helpers.parse_to_datetime(value)
525
+
526
+ if past_time is None or past_time > now:
527
+ raise click.BadParameter("must be a relative time in the past")
528
+
529
+ if past_time < ctx.obj.active_session.start_time:
530
+ raise click.BadParameter("stop time must be after start time")
531
+
532
+ return past_time
533
+
534
+
535
+ class RequireActiveSessionCommand(click.Command):
536
+ def parse_args(self, ctx, args):
537
+ if ctx.obj.active_session is None:
538
+ raise click.UsageError(
539
+ "No active session being tracked. Start a session first."
540
+ )
541
+
542
+ return super().parse_args(ctx, args)
543
+
544
+
545
+ # define `stop` subcommand
546
+ @cli.command(cls=RequireActiveSessionCommand)
547
+ @click.option(
548
+ "--at",
549
+ help='Hours previous to end the timer, e.g. "2 hours ago"',
550
+ callback=validate_stop_at,
551
+ )
552
+ @click.option(
553
+ "--round",
554
+ help="Round the stop time to the nearest 15 minute interval",
555
+ is_flag=True,
556
+ )
557
+ @pass_cli
558
+ def stop(cli_ctx: CliContext, at: datetime, round: bool) -> None:
559
+ stopped_at = at
560
+ latest_sesh = cli_ctx.stop_active_session(stopped_at, round)
561
+
562
+ assert latest_sesh.end_time, "Expected this session to have an 'end_time' set"
563
+
564
+ elapsed_time = time_helpers.format_time_delta(latest_sesh.duration())
565
+
566
+ click.echo(f"• Stopped tracking {latest_sesh.description()} ({elapsed_time})")
567
+
568
+
569
+ # define `cancel` subcommand
570
+ @cli.command(cls=RequireActiveSessionCommand)
571
+ @pass_cli
572
+ def cancel(cli_ctx: CliContext):
573
+ cancelled_sesh = cli_ctx.cancel_active_session()
574
+
575
+ assert cancelled_sesh.end_time, "Expected this session to have an 'end_time' set"
576
+
577
+ elapsed_time = time_helpers.format_time_delta(cancelled_sesh.duration())
578
+
579
+ click.echo(
580
+ f"• Cancelled session for {cancelled_sesh.description()} ({elapsed_time})"
581
+ )
582
+
583
+
584
+ # define `log` subcommand
585
+ @cli.command()
586
+ @pass_cli
587
+ def log(cli_ctx: CliContext):
588
+ # read in the session log file if it exists
589
+ sessions = cli_ctx.load_latest_sessions()
590
+
591
+ # make sure to also display the active session if there is one
592
+ active_session = cli_ctx.active_session
593
+
594
+ click.echo("Session Log")
595
+
596
+ if active_session:
597
+ # Assume, for now, that an active session is always 'today'
598
+ # Later I'll have to account for a session that started the
599
+ # previous day.
600
+ start_time = time_helpers.format_timestamp(active_session.start_time)
601
+
602
+ duration = time_helpers.format_time_delta(active_session.duration())
603
+
604
+ click.echo(
605
+ f" {start_time} - ...\t\t{duration}\t\t{active_session.description()}"
606
+ )
607
+
608
+ yesterday = (datetime.now() - timedelta(days=1)).date()
609
+ for session_date, sessions_for_day in sessions.items():
610
+ date_display = session_date.strftime("%A, %B %d")
611
+ if session_date == yesterday:
612
+ date_display = "Yesterday"
613
+
614
+ click.echo(f"{date_display}")
615
+ for session in sessions_for_day:
616
+ if session.end_time is None:
617
+ continue
618
+
619
+ start_time = time_helpers.format_timestamp(session.start_time)
620
+ end_time = time_helpers.format_timestamp(session.end_time)
621
+
622
+ elapsed_time = time_helpers.format_time_delta(session.duration())
623
+
624
+ click.echo(
625
+ f" {start_time} - {end_time}\t\t{elapsed_time}\t\t{session.description()}"
626
+ )
627
+
628
+ click.echo("")
py_vmt/db.py ADDED
@@ -0,0 +1,51 @@
1
+ from sqlite3 import Connection
2
+
3
+ MIGRATIONS = [
4
+ # v1
5
+ """
6
+ create table tags (
7
+ id integer primary key,
8
+ name text not null unique,
9
+ created_at text not null default (datetime('now')),
10
+ updated_at text not null default (datetime('now'))
11
+ );
12
+
13
+ create table projects (
14
+ id integer primary key,
15
+ name text not null unique,
16
+ created_at text not null default (datetime('now')),
17
+ updated_at text not null default (datetime('now'))
18
+ );
19
+
20
+ create table sessions (
21
+ id integer primary key,
22
+ active integer not null check (active in (0, 1)),
23
+ project_id integer not null references projects(id) on delete cascade,
24
+ start_time text not null,
25
+ end_time text,
26
+ created_at text not null default (datetime('now')),
27
+ updated_at text not null default (datetime('now'))
28
+ );
29
+ create unique index idx_sessions_single_active
30
+ on sessions(active)
31
+ where active = 1;
32
+
33
+ create table session_tags (
34
+ session_id integer not null references sessions(id) on delete cascade,
35
+ tag_id integer not null references tags(id) on delete cascade,
36
+ primary key (session_id, tag_id)
37
+ );
38
+ create index idx_session_tags_tag on session_tags(tag_id);
39
+ """
40
+ ]
41
+
42
+
43
+ # Using the `user_version` pragma in SQLite, this checks if there are any
44
+ # sets of statements in `MIGRATIONS` that have not been run yet. It then
45
+ # executes those and updates `user_version`.
46
+ def migrate(conn: Connection):
47
+ version = conn.execute("pragma user_version").fetchone()[0]
48
+ for i, statement in enumerate(MIGRATIONS[version:], start=version):
49
+ conn.executescript(statement)
50
+ conn.execute(f"pragma user_version = {i + 1}")
51
+ conn.commit()
py_vmt/file_utils.py ADDED
@@ -0,0 +1,17 @@
1
+ import os
2
+ import tempfile
3
+ from contextlib import contextmanager
4
+ from pathlib import Path
5
+
6
+
7
+ @contextmanager
8
+ def atomic_write(path: Path):
9
+ # write to a tmp file in the same directory, then atomically swap it
10
+ fd, temp_file_path = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
11
+ try:
12
+ with os.fdopen(fd, "w") as file:
13
+ yield file
14
+ os.replace(temp_file_path, path)
15
+ except BaseException:
16
+ os.unlink(temp_file_path)
17
+ raise
py_vmt/session.py ADDED
@@ -0,0 +1,72 @@
1
+ from dataclasses import dataclass, field
2
+ from datetime import UTC, datetime, timedelta
3
+
4
+ from py_vmt.time_helpers import find_nearest_timestamp_interval
5
+
6
+
7
+ @dataclass
8
+ class Session:
9
+ start_time: datetime
10
+ project_name: str
11
+ tags: list[str] = field(default_factory=list, kw_only=True)
12
+ end_time: datetime | None = field(default=None, kw_only=True)
13
+
14
+ def __lt__(self, other):
15
+ if not isinstance(other, Session):
16
+ return NotImplemented
17
+ return self.start_time < other.start_time
18
+
19
+ # TODO: Use or remove because nothing is calling this right now
20
+ @staticmethod
21
+ def start(project_name: str) -> "Session":
22
+ return Session(datetime.now(UTC), project_name)
23
+
24
+ def round_end_time(
25
+ self, exact_end_time: datetime, interval: timedelta = timedelta(minutes=15)
26
+ ) -> datetime:
27
+ return find_nearest_timestamp_interval(
28
+ self.start_time, exact_end_time, interval
29
+ )
30
+
31
+ def stop(self, at: datetime | None = None, round: bool = False):
32
+ exact_end_time = at or datetime.now(UTC)
33
+ if round:
34
+ # difference between `self.start_time` and
35
+ rounded_end_time = self.round_end_time(exact_end_time)
36
+ self.end_time = rounded_end_time
37
+ else:
38
+ self.end_time = exact_end_time
39
+
40
+ def duration(self) -> timedelta:
41
+ lhs_time = self.end_time or datetime.now(UTC)
42
+
43
+ return lhs_time - self.start_time
44
+
45
+ def description(self) -> str:
46
+ tag_display = f" [{' '.join(self.tags)}]" if self.tags else ""
47
+ return f"'{self.project_name}'{tag_display}"
48
+
49
+ @staticmethod
50
+ def hydrate(data: dict) -> "Session":
51
+ start_time = datetime.fromisoformat(data["start_time"])
52
+ end_time = None
53
+ if "end_time" in data and data["end_time"] is not None:
54
+ end_time = datetime.fromisoformat(data["end_time"])
55
+
56
+ return Session(
57
+ start_time,
58
+ data["project_name"],
59
+ tags=data.get("tags", []),
60
+ end_time=end_time,
61
+ )
62
+
63
+ def marshal(self) -> dict:
64
+ marshalled_data = {"project_name": self.project_name, "tags": self.tags}
65
+
66
+ if self.start_time:
67
+ marshalled_data["start_time"] = datetime.isoformat(self.start_time)
68
+
69
+ if self.end_time:
70
+ marshalled_data["end_time"] = datetime.isoformat(self.end_time)
71
+
72
+ return marshalled_data
py_vmt/time_helpers.py ADDED
@@ -0,0 +1,63 @@
1
+ from datetime import datetime, timedelta
2
+
3
+ import dateparser
4
+
5
+
6
+ def parse_to_datetime(at: str) -> datetime | None:
7
+ settings = {"TO_TIMEZONE": "UTC", "RETURN_AS_TIMEZONE_AWARE": True}
8
+ return dateparser.parse(at, settings=settings)
9
+
10
+
11
+ def find_nearest_timestamp_interval(
12
+ start_time: datetime, end_time: datetime, interval: timedelta
13
+ ) -> datetime:
14
+ diff = end_time - start_time
15
+ rounding_point = interval.seconds // 2
16
+ intervals, remainder = divmod(diff.seconds, interval.seconds)
17
+
18
+ if remainder == 0:
19
+ return end_time
20
+
21
+ if remainder <= rounding_point:
22
+ return start_time + (intervals * interval)
23
+ else:
24
+ return start_time + ((intervals + 1) * interval)
25
+
26
+
27
+ def format_time_delta(diff: timedelta) -> str:
28
+ total_seconds = int(diff.total_seconds())
29
+
30
+ hours, remainder = divmod(total_seconds, 3600)
31
+ minutes, remainder = divmod(remainder, 60)
32
+ seconds = remainder
33
+
34
+ hour_str = _format_amount_with_suffix(hours, "h")
35
+ min_str = _format_amount_with_suffix(minutes, "m")
36
+ sec_str = _format_amount_with_suffix(seconds, "s")
37
+
38
+ if hour_str:
39
+ return f"{hour_str}{min_str}"
40
+ else:
41
+ return f"{min_str}{sec_str}"
42
+
43
+
44
+ def _format_amount_with_suffix(amount, suffix):
45
+ str = ""
46
+ if amount > 0:
47
+ str = f"{amount}{suffix}"
48
+
49
+ return str
50
+
51
+
52
+ def format_timestamp(utc_datetime: datetime) -> str:
53
+ # H:MM[AM|PM], e.g. 6:32PM
54
+ format = "%-I:%M%p"
55
+
56
+ check = utc_datetime.tzinfo is not None and utc_datetime.utcoffset() == timedelta(0)
57
+ msg = f"The given datetime must have tzinfo ({utc_datetime.tzinfo}) with offset of 0 ({utc_datetime.utcoffset()})"
58
+ assert check, msg
59
+
60
+ # Make sure to convert to local time (with `astimezone()`) before formatting
61
+ # the string.
62
+ local_datetime = utc_datetime.astimezone()
63
+ return local_datetime.strftime(format)
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: visualmode-tracker
3
+ Version: 0.1.0
4
+ Summary: A command-line time tracker for your project and work sessions
5
+ Project-URL: Homepage, https://github.com/jbranchaud/py-vmt
6
+ Project-URL: Repository, https://github.com/jbranchaud/py-vmt
7
+ Project-URL: Issues, https://github.com/jbranchaud/py-vmt/issues
8
+ Author-email: Josh Branchaud <jbranchaud@gmail.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: cli,productivity,time-tracking,timer,tracker
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Utilities
20
+ Requires-Python: >=3.12
21
+ Requires-Dist: click>=8.3.1
22
+ Requires-Dist: dateparser>=1.3.0
23
+ Requires-Dist: platformdirs>=4.9.4
24
+ Description-Content-Type: text/markdown
25
+
26
+ # VisualMode Tracker, built with Python
27
+
28
+ > A command-line time tracker for your project and work sessions
29
+
30
+ ## Usage
31
+
32
+ Standard usage of `vmt` is to `start` a session by name (e.g. `py-vmt`) with
33
+ zero or more tags (e.g. `+python`) while you work. You can always check the
34
+ `status`. When you are done with a session, you can `stop` it. Check the `log`
35
+ to see what sessions you have tracked over the last 7 days.
36
+
37
+ ```bash
38
+ ❯ vmt start py-vmt +python --at "14 minutes ago"
39
+ • Started tracking 'py-vmt' [python] at 12:00PM
40
+
41
+ ❯ vmt status
42
+ • Tracking 'py-vmt' [python] for 27m20s (since 12:00PM)
43
+
44
+ ❯ vmt stop --round
45
+ • Stopped tracking 'py-vmt' [python] (30m)
46
+
47
+ ❯ vmt log
48
+ Session Log
49
+ Sunday, August 02
50
+ 12:00PM - 12:30PM 30m 'py-vmt' [python]
51
+
52
+ ❯ vmt status
53
+ • Not tracking
54
+ Last: 'py-vmt' [python] (30m) at 12:00PM
55
+ ```
56
+
57
+ ## Installation
58
+
59
+ `vmt` (`visualmode-tracker`) can be installed via `uv` and `pipx`:
60
+
61
+ ```bash
62
+ ❯ uv tool install visualmode-tracker
63
+ ```
64
+
65
+ ```bash
66
+ ❯ pipx install visualmode-tracker
67
+ ```
68
+
69
+ Note: that while the package name on PyPI is `visualmode-tracker`, the
70
+ executable binary is called via `vmt`.
71
+
72
+ ## Development
73
+
74
+ Run the CLI in development with `uv`:
75
+
76
+ ```bash
77
+ ❯ uv run vmt start taco --at "1 hour ago"
78
+ • Started tracking 'taco' at 12:56PM
79
+ with flag --at of '1 hour ago'
80
+
81
+ ❯ uv run vmt status
82
+ • Tracking 'taco' for 3m
83
+
84
+ ❯ uv run vmt start burrito
85
+ Error: already tracking 'taco'. Stop the current session first.
86
+ Aborted!
87
+ ```
88
+
89
+ ## Testing
90
+
91
+ The test suite uses `pytest` and `click`'s `CliRunner` to verify the behavior of
92
+ the `vmt` CLI.
93
+
94
+ Run the tests like so:
95
+
96
+ ```bash
97
+ ❯ uv run pytest
98
+ ```
@@ -0,0 +1,11 @@
1
+ py_vmt/__init__.py,sha256=ExOOIXLXNQgir8z_BI74amPH8o5c_Qhu_7q-iP6CO8Q,90
2
+ py_vmt/cli.py,sha256=aXUve9h3BEwDorK9T4l7nm7GSsb006z_JC-DiEOudY4,21475
3
+ py_vmt/db.py,sha256=S3RPEgzvgmNnQXnow7K4yyInaniPGz8rLxGlPVeKXto,1765
4
+ py_vmt/file_utils.py,sha256=xcKnpY2jl3EcFXT51hV7eUy8k6gq9rovO6P3Y72cRJE,472
5
+ py_vmt/session.py,sha256=d50_AFVu7DwyPXVJHWBZX_CIBAb4qeKqFQZtFZ_5fUE,2396
6
+ py_vmt/time_helpers.py,sha256=qU1NNBazbe-oPQcyrJYyMlVaocqnNnRphUN0LXnSo_k,1850
7
+ visualmode_tracker-0.1.0.dist-info/METADATA,sha256=1Hj1wII0iRCyce63gaIJdv-pX0klHmrZ4wHQVRTLZms,2609
8
+ visualmode_tracker-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
9
+ visualmode_tracker-0.1.0.dist-info/entry_points.txt,sha256=exkHcaEX_oBQyZtOTI30XZOj4Y1E191iySibPUu3KjM,39
10
+ visualmode_tracker-0.1.0.dist-info/licenses/LICENSE,sha256=961Eipw_GBeKS0vCjXZkU5MUwkt4ZYukFsAMTxvXMSs,1071
11
+ visualmode_tracker-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ vmt = py_vmt.cli:cli
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Josh Branchaud
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.