-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
838 lines (714 loc) · 24.2 KB
/
Copy pathmain.go
File metadata and controls
838 lines (714 loc) · 24.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
package main
import (
"bytes"
"context"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"runtime"
"syscall"
"time"
"github.com/clobrano/wui/internal/api"
"github.com/clobrano/wui/internal/calendar"
"github.com/clobrano/wui/internal/config"
"github.com/clobrano/wui/internal/gui"
"github.com/clobrano/wui/internal/taskwarrior"
"github.com/clobrano/wui/internal/tui"
"github.com/clobrano/wui/internal/version"
"github.com/clobrano/wui/internal/youtube"
"github.com/spf13/cobra"
)
var (
// CLI flags
configPath string
taskrcPath string
taskBinPath string
logLevel string
logFormat string
searchFilter string
)
var rootCmd = &cobra.Command{
Use: "wui",
Short: "Warrior UI - A modern TUI for Taskwarrior",
Long: `wui (Warrior UI) is a Terminal User Interface for Taskwarrior built with Go and bubbletea.
It provides an intuitive, keyboard-driven interface for managing your tasks.`,
Run: func(cmd *cobra.Command, args []string) {
if err := runTUI(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
},
}
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version number of wui",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("wui version %s\n", version.GetVersion())
},
}
var (
syncCalendarName string
syncTaskFilter string
)
var serveAddr string
var serveTLSCert string
var serveTLSKey string
var (
guiPort int
guiAPIPort int
)
var guiCmd = &cobra.Command{
Use: "gui",
Short: "Start the web GUI",
Long: `Start the wui web-based GUI.
The GUI launches a local HTTP server and opens your default browser. It requires
wui serve (the REST API) to be reachable; if it is not already running, wui gui
starts it automatically as a child process.
Ports:
--port GUI HTTP server port (default 7008)
--api-port wui serve API port (default 7007)
Examples:
wui gui # GUI on :7008, API on :7007
wui gui --port 8080 # GUI on :8080
wui gui --api-port 9000 # Connect to API on :9000`,
Run: func(cmd *cobra.Command, args []string) {
if err := runGUI(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
},
}
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Start the REST API server",
Long: `Start the wui REST/JSON API server.
The server exposes the Taskwarrior backend over HTTP so that alternative UIs
(Flutter, web, CLI scripts) can drive the same business logic as the TUI.
API base: http://<addr>/api/v1
Endpoints:
GET /api/v1/tasks list tasks (optional ?filter= query param)
POST /api/v1/tasks create a task {"description":"..."}
PUT /api/v1/tasks/{uuid} modify a task {"modifications":"priority:H"}
DELETE /api/v1/tasks/{uuid} delete a task
POST /api/v1/tasks/{uuid}/done mark done
POST /api/v1/tasks/{uuid}/start start
POST /api/v1/tasks/{uuid}/stop stop
POST /api/v1/tasks/{uuid}/annotate add annotation {"text":"..."}
POST /api/v1/undo undo last operation
GET /api/v1/projects list project summaries
Examples:
wui serve # Listen on localhost:7007
wui serve --addr :7007 # Listen on all interfaces`,
Run: func(cmd *cobra.Command, args []string) {
if err := runServe(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
},
}
var youtubeCmd = &cobra.Command{
Use: "youtube",
Short: "Sync YouTube playlists to Taskwarrior (one-shot)",
Long: `Fetch all configured YouTube playlists via yt-dlp and create a Taskwarrior
task for each video not yet seen. Useful for testing your youtube_sync config
before relying on the background poller in wui serve.
Examples:
wui youtube # run sync for all enabled playlists`,
Run: func(cmd *cobra.Command, args []string) {
if err := runYoutube(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
},
}
var syncCmd = &cobra.Command{
Use: "sync",
Short: "Sync Taskwarrior tasks to Google Calendar",
Long: `Synchronize Taskwarrior tasks to Google Calendar.
This command syncs tasks from Taskwarrior to a specified Google Calendar using
settings from your config file (~/.config/wui/config.yaml). You can override
these settings with command-line flags.
Before syncing, you need to:
1. Create a Google Cloud project and enable the Google Calendar API
2. Download the credentials.json file from Google Cloud Console
3. Place it in ~/.config/wui/credentials.json
4. Configure calendar_name and task_filter in config.yaml
On first run, you'll be prompted to authorize the app in your browser.
Examples:
wui sync # Use config.yaml settings
wui sync --calendar "Work" # Override calendar
wui sync --filter "+urgent" # Override filter
wui sync --calendar "Tasks" --filter "due:today" # Override both`,
Run: func(cmd *cobra.Command, args []string) {
if err := runSync(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
},
}
func init() {
// Add subcommands
rootCmd.AddCommand(versionCmd)
rootCmd.AddCommand(youtubeCmd)
rootCmd.AddCommand(syncCmd)
rootCmd.AddCommand(serveCmd)
rootCmd.AddCommand(guiCmd)
// GUI command flags
guiCmd.Flags().IntVar(&guiPort, "port", 7008, "port for the GUI HTTP server")
guiCmd.Flags().IntVar(&guiAPIPort, "api-port", 0, "port of the wui serve API (0 = use config or default 7007)")
// Serve command flags
serveCmd.Flags().StringVar(&serveAddr, "addr", "localhost:7007", "address to listen on (host:port)")
serveCmd.Flags().StringVar(&serveTLSCert, "tls-cert", "", "path to TLS certificate file (enables HTTPS)")
serveCmd.Flags().StringVar(&serveTLSKey, "tls-key", "", "path to TLS private key file (enables HTTPS)")
// Sync command flags (optional - override config file values)
syncCmd.Flags().StringVar(&syncCalendarName, "calendar", "", "Google Calendar name (overrides config)")
syncCmd.Flags().StringVar(&syncTaskFilter, "filter", "", "Taskwarrior filter for tasks to sync (overrides config)")
// Persistent flags available to all commands
rootCmd.PersistentFlags().StringVar(&configPath, "config", "", "config file path (default: ~/.config/wui/config.yaml)")
rootCmd.PersistentFlags().StringVar(&taskrcPath, "taskrc", "", "taskrc file path (default: ~/.taskrc)")
rootCmd.PersistentFlags().StringVar(&taskBinPath, "task-bin", "", "task binary path (default: /usr/local/bin/task)")
rootCmd.PersistentFlags().StringVar(&logLevel, "log-level", "error", "log level (debug, info, warn, error)")
rootCmd.PersistentFlags().StringVar(&logFormat, "log-format", "text", "log format (text, json)")
rootCmd.PersistentFlags().StringVar(&searchFilter, "search", "", "open in Search tab with the specified filter")
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
// runTUI initializes and runs the TUI application
func runTUI() error {
// Resolve config path
cfgPath := config.ResolveConfigPath(configPath)
// If the user explicitly passed --config, the file must exist
if err := config.ValidateExplicitConfigPath(configPath, cfgPath); err != nil {
return err
}
// Load configuration
cfg, err := config.LoadConfig(cfgPath)
if err != nil {
// Use basic logging before config is loaded
initLogging(nil)
slog.Error("Failed to load config", "error", err, "path", cfgPath)
return fmt.Errorf("failed to load config: %w", err)
}
// Initialize logging with config (priority: flag > env > config)
initLogging(cfg)
slog.Info("Starting wui", "version", version.GetVersion())
slog.Debug("Using config path", "path", cfgPath)
// Override with CLI flags if provided
if taskBinPath != "" {
slog.Debug("Overriding task binary path", "path", taskBinPath)
cfg.TaskBin = taskBinPath
}
if taskrcPath != "" {
slog.Debug("Overriding taskrc path", "path", taskrcPath)
cfg.TaskrcPath = taskrcPath
}
if searchFilter != "" {
slog.Debug("Setting initial search filter", "filter", searchFilter)
cfg.InitialSearchFilter = searchFilter
}
slog.Info("Configuration loaded",
"task_bin", cfg.TaskBin,
"taskrc_path", cfg.TaskrcPath)
// Check if task binary exists and is executable
if err := checkTaskBinary(cfg.TaskBin); err != nil {
slog.Error("Task binary not found or not executable", "error", err, "path", cfg.TaskBin)
return err
}
// Check if taskrc file exists
if err := config.ValidateTaskrcPath(cfg.TaskrcPath); err != nil {
slog.Error("Taskrc file not found", "error", err, "path", cfg.TaskrcPath)
return err
}
// Create Taskwarrior client
client, err := taskwarrior.NewClient(cfg.TaskBin, cfg.TaskrcPath)
if err != nil {
slog.Error("Failed to create taskwarrior client", "error", err)
return fmt.Errorf("failed to create taskwarrior client: %w", err)
}
slog.Debug("Taskwarrior client created successfully")
// Run the TUI
return tui.Run(client, cfg)
}
// initLogging initializes the logging system with priority: flag > env > config
func initLogging(cfg *config.Config) {
// Determine log level with priority: CLI flag > env variable > config file
effectiveLogLevel := "error" // fallback default
// Start with config value if available
if cfg != nil && cfg.LogLevel != "" {
effectiveLogLevel = cfg.LogLevel
}
// Override with environment variable if set
if envLogLevel := os.Getenv("WUI_LOG_LEVEL"); envLogLevel != "" {
effectiveLogLevel = envLogLevel
}
// Override with CLI flag if provided (non-default)
// Note: We check if it's different from the default value
if logLevel != "" {
effectiveLogLevel = logLevel
}
// Parse log level
var level slog.Level
switch effectiveLogLevel {
case "debug":
level = slog.LevelDebug
case "info":
level = slog.LevelInfo
case "warn":
level = slog.LevelWarn
case "error":
level = slog.LevelError
default:
level = slog.LevelInfo
}
// For TUI mode, log to file instead of stderr to avoid interfering with display
logFile := os.Getenv("WUI_LOG_FILE")
if logFile == "" {
// Default to temp file
logFile = "/tmp/wui.log"
}
f, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
// Fallback to discarding logs if file can't be opened
f = nil
}
// Create handler based on format
var handler slog.Handler
opts := &slog.HandlerOptions{Level: level}
output := os.Stderr
if f != nil {
output = f
}
if logFormat == "json" {
handler = slog.NewJSONHandler(output, opts)
} else {
handler = slog.NewTextHandler(output, opts)
}
// Set default logger
slog.SetDefault(slog.New(handler))
}
// checkTaskBinary verifies that the task binary exists and is executable
func checkTaskBinary(taskBin string) error {
// Use exec.LookPath to check if the binary is in PATH or at the specified location
path, err := exec.LookPath(taskBin)
if err != nil {
return fmt.Errorf(`task binary not found: %w
Taskwarrior is required to run wui. Please install it:
• Ubuntu/Debian: sudo apt install taskwarrior
• Fedora/RHEL: sudo dnf install task
• macOS (Homebrew): brew install task
• Arch Linux: sudo pacman -S task
Or specify a custom path with: wui --task-bin /path/to/task
Visit https://taskwarrior.org for more information.`, err)
}
slog.Debug("Task binary found", "path", path)
return nil
}
// runServe starts the REST API server backed by the local Taskwarrior installation.
func runServe() error {
cfgPath := config.ResolveConfigPath(configPath)
if err := config.ValidateExplicitConfigPath(configPath, cfgPath); err != nil {
return err
}
cfg, err := config.LoadConfig(cfgPath)
if err != nil {
initLogging(nil)
slog.Error("Failed to load config", "error", err, "path", cfgPath)
return fmt.Errorf("failed to load config: %w", err)
}
initLogging(cfg)
slog.Info("Starting wui API server", "version", version.GetVersion())
if taskBinPath != "" {
cfg.TaskBin = taskBinPath
}
if taskrcPath != "" {
cfg.TaskrcPath = taskrcPath
}
if err := checkTaskBinary(cfg.TaskBin); err != nil {
return err
}
if err := config.ValidateTaskrcPath(cfg.TaskrcPath); err != nil {
return err
}
client, err := taskwarrior.NewClient(cfg.TaskBin, cfg.TaskrcPath)
if err != nil {
return fmt.Errorf("failed to create taskwarrior client: %w", err)
}
client.SetWuiConfigPath(cfgPath)
// Background context cancelled on shutdown to stop any pollers.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Start one YouTube playlist poller per enabled entry.
if yt := cfg.YoutubeSync; yt != nil && len(yt.Playlists) > 0 {
if _, err := exec.LookPath(yt.YtDlpBin); err != nil {
return fmt.Errorf("yt-dlp binary %q not found: %w", yt.YtDlpBin, err)
}
for i := range yt.Playlists {
pl := &yt.Playlists[i]
if !pl.Enabled {
continue
}
if pl.PlaylistURL == "" {
slog.Warn("YouTube playlist entry has no playlist_url — skipping")
continue
}
interval, err := time.ParseDuration(pl.PollInterval)
if err != nil {
slog.Warn("Invalid poll_interval for playlist, using 30m", "playlist", pl.PlaylistURL, "value", pl.PollInterval)
interval = 30 * time.Minute
}
syncer := youtube.NewSyncer(pl, yt.YtDlpBin, client)
youtube.StartPoller(ctx, syncer, interval)
slog.Info("YouTube playlist poller started", "playlist", pl.PlaylistURL, "interval", interval)
}
}
srv := api.NewServer(client, serveAddr, serveTLSCert, serveTLSKey)
// Graceful shutdown on SIGINT / SIGTERM
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
errCh := make(chan error, 1)
go func() { errCh <- srv.Start() }()
select {
case err := <-errCh:
return err
case <-stop:
cancel() // stop the YouTube poller
fmt.Println("\nShutting down...")
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer shutdownCancel()
return srv.Shutdown(shutdownCtx)
}
}
// resolveAPIPort implements the --api-port fallback: flag (non-zero) → config.Serve.Port → 7007.
func resolveAPIPort(flag int, cfg *config.Config) int {
if flag != 0 {
return flag
}
if cfg.Serve != nil && cfg.Serve.Port > 0 {
return cfg.Serve.Port
}
return 7007
}
// portInUse returns true when something is already listening on localhost:<port>.
func portInUse(port int) bool {
conn, err := net.DialTimeout("tcp", fmt.Sprintf("localhost:%d", port), time.Second)
if err != nil {
return false
}
conn.Close()
return true
}
// apiReachable returns true when GET /api/v1/version on localhost:<port> responds with 2xx.
func apiReachable(port int) bool {
url := fmt.Sprintf("http://localhost:%d/api/v1/version", port)
resp, err := http.Get(url) //nolint:gosec // localhost only
if err != nil {
return false
}
resp.Body.Close()
return resp.StatusCode < 300
}
// waitForAPI polls GET /api/v1/version every 200 ms for up to 10 s.
func waitForAPI(port int) error {
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
if apiReachable(port) {
return nil
}
time.Sleep(200 * time.Millisecond)
}
return fmt.Errorf("wui serve on :%d did not become ready within 10 s", port)
}
// openBrowser opens the default browser on the given URL (cross-platform).
func openBrowser(url string) {
var cmd *exec.Cmd
switch runtime.GOOS {
case "darwin":
cmd = exec.Command("open", url)
case "windows":
cmd = exec.Command("cmd", "/c", "start", url)
default:
cmd = exec.Command("xdg-open", url)
}
// Best-effort; ignore errors (missing browser is not fatal).
_ = cmd.Start()
}
// runGUI starts the web GUI server and manages the wui serve child process.
func runGUI() error {
cfgPath := config.ResolveConfigPath(configPath)
if err := config.ValidateExplicitConfigPath(configPath, cfgPath); err != nil {
return err
}
cfg, err := config.LoadConfig(cfgPath)
if err != nil {
initLogging(nil)
return fmt.Errorf("failed to load config: %w", err)
}
initLogging(cfg)
apiPort := resolveAPIPort(guiAPIPort, cfg)
// Bind on all interfaces so the GUI is reachable over the LAN (e.g. from
// other devices on the same WiFi). The browser is still opened via localhost.
guiAddr := fmt.Sprintf(":%d", guiPort)
// Task 1.3: fail fast if the GUI port is already occupied.
if portInUse(guiPort) {
return fmt.Errorf("port %d is already in use; choose another with --port", guiPort)
}
// Task 1.4: start wui serve as a child process if the API is not already up.
var child *exec.Cmd
if !apiReachable(apiPort) {
args := []string{"serve", "--addr", fmt.Sprintf("localhost:%d", apiPort)}
if configPath != "" {
args = append(args, "--config", cfgPath)
}
if taskrcPath != "" {
args = append(args, "--taskrc", taskrcPath)
}
if taskBinPath != "" {
args = append(args, "--task-bin", taskBinPath)
}
child = exec.Command(os.Args[0], args...)
// Task 1.7: relay child output with a [wui serve] prefix.
child.Stdout = &prefixWriter{w: os.Stderr, prefix: "[wui serve] "}
child.Stderr = &prefixWriter{w: os.Stderr, prefix: "[wui serve] "}
if err := child.Start(); err != nil {
return fmt.Errorf("failed to start wui serve: %w", err)
}
slog.Info("Started wui serve child process", "pid", child.Process.Pid, "api-port", apiPort)
} else {
slog.Info("wui serve already running", "api-port", apiPort)
}
// Task 1.5: wait for the API to become reachable.
if err := waitForAPI(apiPort); err != nil {
if child != nil {
_ = child.Process.Kill()
}
return err
}
// Build the GUI server.
apiClient := gui.NewAPIClient(fmt.Sprintf("http://localhost:%d/api/v1", apiPort))
filterHistory := gui.NewFilterHistory(config.ConfigDir())
guiServer := gui.NewServer(apiClient, cfg, filterHistory, fmt.Sprintf("http://localhost:%d", apiPort))
guiURL := fmt.Sprintf("http://localhost:%d", guiPort)
// Task 1.8: graceful shutdown on SIGINT / SIGTERM.
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
errCh := make(chan error, 1)
go func() { errCh <- guiServer.Start(guiAddr) }()
// Wait until the GUI port is actually bound before opening the browser.
// This avoids a race where the browser connects before ListenAndServe is ready.
for i := 0; i < 50; i++ {
select {
case err := <-errCh:
return fmt.Errorf("GUI server failed to start: %w", err)
default:
}
if portInUse(guiPort) {
break
}
time.Sleep(50 * time.Millisecond)
}
// Task 1.6: open the browser.
fmt.Fprintf(os.Stderr, "wui GUI listening on %s\n", guiURL)
openBrowser(guiURL)
select {
case err := <-errCh:
return err
case <-stop:
fmt.Println("\nShutting down wui GUI...")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = guiServer.Shutdown(ctx)
if child != nil {
slog.Info("Stopping wui serve child process")
_ = child.Process.Signal(syscall.SIGTERM)
done := make(chan struct{})
go func() { _ = child.Wait(); close(done) }()
select {
case <-done:
case <-time.After(5 * time.Second):
_ = child.Process.Kill()
}
}
}
return nil
}
// prefixWriter prefixes each line written to it before forwarding to w.
type prefixWriter struct {
w io.Writer
prefix string
buf []byte
}
func (pw *prefixWriter) Write(p []byte) (n int, err error) {
pw.buf = append(pw.buf, p...)
for {
idx := bytes.IndexByte(pw.buf, '\n')
if idx < 0 {
break
}
line := pw.buf[:idx+1]
if _, err := fmt.Fprintf(pw.w, "%s%s", pw.prefix, line); err != nil {
return 0, err
}
pw.buf = pw.buf[idx+1:]
}
return len(p), nil
}
// runYoutube performs a one-shot YouTube playlist sync and prints results to stdout.
func runYoutube() error {
cfgPath := config.ResolveConfigPath(configPath)
if err := config.ValidateExplicitConfigPath(configPath, cfgPath); err != nil {
return err
}
cfg, err := config.LoadConfig(cfgPath)
if err != nil {
initLogging(nil)
return fmt.Errorf("failed to load config: %w", err)
}
initLogging(cfg)
if taskBinPath != "" {
cfg.TaskBin = taskBinPath
}
if taskrcPath != "" {
cfg.TaskrcPath = taskrcPath
}
if err := checkTaskBinary(cfg.TaskBin); err != nil {
return err
}
if err := config.ValidateTaskrcPath(cfg.TaskrcPath); err != nil {
return err
}
yt := cfg.YoutubeSync
if yt == nil || len(yt.Playlists) == 0 {
fmt.Println("No playlists configured under youtube_sync.")
return nil
}
if _, err := exec.LookPath(yt.YtDlpBin); err != nil {
return fmt.Errorf("yt-dlp binary %q not found: %w", yt.YtDlpBin, err)
}
client, err := taskwarrior.NewClient(cfg.TaskBin, cfg.TaskrcPath)
if err != nil {
return fmt.Errorf("failed to create taskwarrior client: %w", err)
}
anyEnabled := false
for i := range yt.Playlists {
pl := &yt.Playlists[i]
if !pl.Enabled {
continue
}
anyEnabled = true
if pl.PlaylistURL == "" {
fmt.Fprintf(os.Stderr, "playlist entry %d: no playlist_url — skipping\n", i+1)
continue
}
fmt.Printf("syncing %s … ", pl.PlaylistURL)
result, err := youtube.NewSyncer(pl, yt.YtDlpBin, client).Sync()
if err != nil {
fmt.Printf("error: %v\n", err)
continue
}
fmt.Printf("%d added, %d skipped\n", result.Added, result.Skipped)
}
if !anyEnabled {
fmt.Println("No enabled playlists found. Set enabled: true in youtube_sync.playlists.")
}
return nil
}
// runSync performs the Google Calendar sync operation
func runSync() error {
// Resolve config path
cfgPath := config.ResolveConfigPath(configPath)
// If the user explicitly passed --config, the file must exist
if err := config.ValidateExplicitConfigPath(configPath, cfgPath); err != nil {
return err
}
// Load configuration
cfg, err := config.LoadConfig(cfgPath)
if err != nil {
// Use basic logging before config is loaded
initLogging(nil)
slog.Error("Failed to load config", "error", err, "path", cfgPath)
return fmt.Errorf("failed to load config: %w", err)
}
// Initialize logging with config (priority: flag > env > config)
initLogging(cfg)
slog.Info("Starting Google Calendar sync", "version", version.GetVersion())
slog.Debug("Using config path", "path", cfgPath)
// Override with CLI flags if provided
if taskBinPath != "" {
cfg.TaskBin = taskBinPath
}
if taskrcPath != "" {
cfg.TaskrcPath = taskrcPath
}
// Get calendar name and filter from config, allow flags to override
calendarName := cfg.CalendarSync.CalendarName
taskFilter := cfg.CalendarSync.TaskFilter
if syncCalendarName != "" {
calendarName = syncCalendarName
}
if syncTaskFilter != "" {
taskFilter = syncTaskFilter
}
// Validate required fields
if calendarName == "" {
return fmt.Errorf("calendar name is required (set in config.yaml or use --calendar flag)")
}
if taskFilter == "" {
return fmt.Errorf("task filter is required (set in config.yaml or use --filter flag)")
}
slog.Info("Sync configuration",
"calendar", calendarName,
"filter", taskFilter,
"task_bin", cfg.TaskBin,
"taskrc_path", cfg.TaskrcPath)
// Check if task binary exists
if err := checkTaskBinary(cfg.TaskBin); err != nil {
return err
}
// Check if taskrc file exists
if err := config.ValidateTaskrcPath(cfg.TaskrcPath); err != nil {
slog.Error("Taskrc file not found", "error", err, "path", cfg.TaskrcPath)
return err
}
// Create Taskwarrior client
taskClient, err := taskwarrior.NewClient(cfg.TaskBin, cfg.TaskrcPath)
if err != nil {
slog.Error("Failed to create taskwarrior client", "error", err)
return fmt.Errorf("failed to create taskwarrior client: %w", err)
}
// Get credentials and token paths from config
credentialsPath := cfg.CalendarSync.CredentialsPath
tokenPath := cfg.CalendarSync.TokenPath
slog.Info("Using credentials", "path", credentialsPath, "token_path", tokenPath)
// Create sync client
ctx := context.Background()
syncClient, err := calendar.NewSyncClient(ctx, taskClient, credentialsPath, tokenPath, calendarName, taskFilter)
if err != nil {
slog.Error("Failed to create sync client", "error", err)
return fmt.Errorf("failed to create sync client: %w", err)
}
// Perform sync
result, err := syncClient.Sync(ctx)
if err != nil {
slog.Error("Sync failed", "error", err)
return fmt.Errorf("sync failed: %w", err)
}
slog.Info("Sync completed successfully", "created", result.Created, "updated", result.Updated)
// Print warnings if any (for TUI mode when output might be lost)
if len(result.Warnings) > 0 {
fmt.Println("\n========================================")
for _, warning := range result.Warnings {
fmt.Printf("⚠️ WARNING: %s\n", warning)
}
fmt.Println("========================================")
}
return nil
}