]> git.r.bdr.sh - rbdr/lyricli/blame - Sources/lyricli/lyricli_command.swift
add distribution to gitignore
[rbdr/lyricli] / Sources / lyricli / lyricli_command.swift
CommitLineData
c53df649
RBR
1import Darwin
2import ArgumentParser
fdafe0d4 3
c53df649
RBR
4@main
5struct LyricliCommand: ParsableCommand {
6
7 // Positional Arguments
8 @Argument var artist: String?
9 @Argument var trackName: String?
fdafe0d4
BB
10
11 // Flags
c53df649
RBR
12 @Flag(name: .shortAndLong, help: "Prints the version.")
13 var version = false
14
15 @Flag(name: [.long, .customShort("t")], help: "Shows title of track if true")
16 var showTitle = false
17
18 @Flag(name: .shortAndLong, help: "Lists all sources")
19 var listSources = false
fdafe0d4
BB
20
21 // Named Arguments
c53df649
RBR
22 @Option(name: .shortAndLong, help: ArgumentHelp("Enables a source", valueName: "source"))
23 var enableSource: String?
fdafe0d4 24
c53df649
RBR
25 @Option(name: .shortAndLong, help: ArgumentHelp("Disables a source", valueName: "source"))
26 var disableSource: String?
27
28 @Option(name: .shortAndLong, help: ArgumentHelp("Resets a source", valueName: "source"))
29 var resetSource: String?
30
31 mutating func run() throws {
32
33 // Handle the version flag
34 if version {
35 print(Lyricli.version)
36 Darwin.exit(0)
37 }
38
39 // Handle the list sources flag
40 if listSources {
41 Lyricli.printSources()
42 Darwin.exit(0)
43 }
44
45 // Handle the enable source option
46 if let source = enableSource {
47 do {
48 try Lyricli.enableSource(source)
49 } catch let error {
50 handleErrorAndQuit(error)
51 }
52 Darwin.exit(0)
53 }
54
55 // Handle the disable source option
56 if let source = disableSource {
57 do {
58 try Lyricli.disableSource(source)
59 } catch let error {
60 handleErrorAndQuit(error)
61 }
62 Darwin.exit(0)
63 }
64
65 // Handle the reset source flag
66 if let source = resetSource {
67 do {
68 try Lyricli.resetSource(source)
69 } catch let error {
70 handleErrorAndQuit(error)
71 }
72 Darwin.exit(0)
73 }
74
75 Lyricli.showTitle = showTitle
76
77 if let artist {
78 let currentTrack: Track
79 if let trackName {
80 currentTrack = Track(withName: trackName, andArtist: artist)
81 } else {
82 currentTrack = Track(withName: "", andArtist: artist)
83 }
84 Lyricli.printLyrics(currentTrack)
85 Darwin.exit(0)
86 }
87
88 Lyricli.printLyrics()
89 }
90
91 private func handleErrorAndQuit(_ error: Error) {
92 fputs(error.localizedDescription, stderr)
93 Darwin.exit(1)
fdafe0d4
BB
94 }
95}