bdgtr-cli 0.2 → 0.3

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.
Files changed (87) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +1 -1
  3. data/bin/bdgtr +26 -5
  4. data/lib/bdgtr/cli/config.rb +188 -0
  5. data/lib/bdgtr/cli/config.sample.yml +15 -0
  6. data/lib/bdgtr/cli/help.rb +168 -0
  7. data/lib/bdgtr/cli/ledger_sync.rb +102 -0
  8. data/lib/bdgtr/cli/prompt.rb +47 -0
  9. data/lib/bdgtr/cli/psd2.rb +530 -0
  10. data/lib/bdgtr/cli/rows.rb +38 -0
  11. data/lib/bdgtr/cli/runtime.rb +88 -0
  12. data/lib/bdgtr/cli/table.rb +458 -0
  13. data/lib/bdgtr/cli.rb +126 -0
  14. data/lib/bdgtr/core/binder.rb +79 -0
  15. data/lib/bdgtr/core/exchange.rb +66 -0
  16. data/lib/bdgtr/core/models/account.rb +177 -0
  17. data/lib/bdgtr/core/models/account_requisition.rb +12 -0
  18. data/lib/bdgtr/core/models/account_sync.rb +12 -0
  19. data/lib/bdgtr/core/models/import.rb +12 -0
  20. data/lib/bdgtr/core/models/ledger.rb +10 -0
  21. data/lib/bdgtr/core/models/requisition.rb +27 -0
  22. data/lib/bdgtr/core/models/transaction.rb +98 -0
  23. data/lib/bdgtr/core/models/transaction_category.rb +12 -0
  24. data/lib/bdgtr/core/record.rb +11 -0
  25. data/lib/bdgtr/core/schema.rb +290 -0
  26. data/lib/bdgtr/core/session.rb +76 -0
  27. data/lib/bdgtr/core/syncable.rb +272 -0
  28. data/lib/bdgtr/core/transfer.rb +90 -0
  29. data/lib/bdgtr/core.rb +18 -0
  30. data/lib/bdgtr/portfolio/Rakefile +20 -0
  31. data/lib/bdgtr/portfolio/cli/LICENSE +21 -0
  32. data/lib/bdgtr/portfolio/cli/lib/portfolio_performance_api/cli/app.rb +77 -0
  33. data/lib/bdgtr/portfolio/cli/lib/portfolio_performance_api/cli/import.rb +30 -0
  34. data/lib/bdgtr/portfolio/cli/lib/portfolio_performance_api/cli/spreadsheet.rb +25 -0
  35. data/lib/bdgtr/portfolio/cli/lib/portfolio_performance_api/cli.rb +52 -0
  36. data/lib/bdgtr/portfolio/exe/bdgtr +7 -0
  37. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/accounts_csv.rb +67 -0
  38. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/app.rb +104 -0
  39. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/auth.rb +52 -0
  40. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/balances.rb +157 -0
  41. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/cache.rb +46 -0
  42. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/checkbox_menu.rb +90 -0
  43. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/checkbox_selection.rb +68 -0
  44. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/config.rb +138 -0
  45. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/decryptor.rb +70 -0
  46. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/drive_client.rb +182 -0
  47. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/errors.rb +10 -0
  48. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/file_reader.rb +80 -0
  49. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/fineco_import.rb +609 -0
  50. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/fineco_xls.rb +235 -0
  51. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/import/fineco.rb +243 -0
  52. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/import.rb +85 -0
  53. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/parser.rb +254 -0
  54. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/portfolio_source.rb +30 -0
  55. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/portfolio_store.rb +124 -0
  56. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/preview_window.rb +98 -0
  57. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/proto/client_pb.rb +29 -0
  58. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/row_preview.rb +174 -0
  59. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/sheets_client.rb +272 -0
  60. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/snapshot.rb +27 -0
  61. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/sync.rb +247 -0
  62. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/sync_preview.rb +63 -0
  63. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/transaction_identity.rb +49 -0
  64. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/transaction_sync.rb +948 -0
  65. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/transaction_types.rb +142 -0
  66. data/lib/bdgtr/portfolio/lib/portfolio_performance_api/version.rb +5 -0
  67. data/lib/bdgtr/portfolio/lib/portfolio_performance_api.rb +42 -0
  68. data/lib/bdgtr/portfolio/proto/client.proto +114 -0
  69. data/lib/bdgtr/psd2/account.rb +24 -0
  70. data/lib/bdgtr/psd2/account_snapshot.rb +96 -0
  71. data/lib/bdgtr/psd2/callback.rb +49 -0
  72. data/lib/bdgtr/psd2/connect.rb +75 -0
  73. data/lib/bdgtr/psd2/enable_banking.rb +250 -0
  74. data/lib/bdgtr/psd2/go_cardless.rb +133 -0
  75. data/lib/bdgtr/psd2/institution.rb +17 -0
  76. data/lib/bdgtr/psd2/platform.rb +37 -0
  77. data/lib/bdgtr/psd2/requisition.rb +21 -0
  78. data/lib/bdgtr/psd2/transaction.rb +29 -0
  79. data/lib/bdgtr/psd2.rb +25 -0
  80. data/lib/bdgtr/sync/importer.rb +125 -0
  81. data/lib/bdgtr/sync/library.rb +18 -0
  82. data/lib/bdgtr/sync/portfolio.rb +14 -0
  83. data/lib/bdgtr/sync/projection.rb +38 -0
  84. data/lib/bdgtr/sync/spreadsheet.rb +23 -0
  85. data/lib/bdgtr/sync.rb +25 -0
  86. data/lib/bdgtr/version.rb +1 -1
  87. metadata +353 -30
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e3b14aafd13b319d5d6ebd1f0f2d2b33006913d90280a681b35d43ede253ba54
4
- data.tar.gz: 6e28475797d841adb890ca7d7b603191f7c7e44337add49291fb5d57210da016
3
+ metadata.gz: 7ab4ad5485ba359d8356f42d92f870d298fb80a2df3525ab095fabfbbdf74f8f
4
+ data.tar.gz: c64a007baf404cf399b80a5c918337165e6ca047fc3976dc291b302d6933f5c1
5
5
  SHA512:
6
- metadata.gz: d0a52dea168f388ac5871b77d4cf50db548a428fadb25cd629088784c6df67e0c6bf0e2bd44ca22c2a8c4bcab447d3e1601b68d2829ac3690371a77b605f9bb6
7
- data.tar.gz: '0878e0509c2823a9bfef330428a44e4f5b7b96f4ae5142c710c8a5bacfa104ead4f7cd36b41a50288fa9a83a717c7c62d763eb00705ee8737b73a1007f8f2480'
6
+ metadata.gz: 8cce1ed3535b26425d42928c0e13b00c32ff2f565d7366d0ce68e2c7342e5132264b69d7b3c82ce2c9229ddd09ff6f9e9b4561eb6a37130d350787052605ff59
7
+ data.tar.gz: 3ca9d93f58a7d2541ce8f3a02ae40a140d4348185a5f988b5aa927a948afde861454d215c8a6590bbf16cee3a70d894caedc4adebf430d9403042c0d499cd010
data/README.md CHANGED
@@ -2,6 +2,6 @@
2
2
 
3
3
  Command line for bdgtr. Installing the gem creates `~/.bdgtr/config.yml` and `~/.bdgtr/bdgtr.sqlite` when they are missing, and leaves an existing ledger file in place.
4
4
 
5
- `bdgtr version` prints the gem version. `bdgtr ledger:reset` replaces `~/.bdgtr/bdgtr.sqlite` with the empty ledger after you type `yes`.
5
+ `bdgtr` lists the commands. `bdgtr version` prints the gem version. Account and transaction commands load ActiveRecord and the SQLite ledger. They do not boot the Rails app. `bdgtr ledger:reset` replaces `~/.bdgtr/bdgtr.sqlite` with the empty ledger after you type `yes`.
6
6
 
7
7
  Release from the app root: `bin/release-cli`
data/bin/bdgtr CHANGED
@@ -5,6 +5,12 @@ require "bdgtr_cli"
5
5
 
6
6
  Bdgtr::Cli::GemHome.install!
7
7
 
8
+ begin
9
+ require "bdgtr/cli/runtime"
10
+ rescue LoadError
11
+ require File.expand_path("../../lib/bdgtr/cli/runtime", __dir__)
12
+ end
13
+
8
14
  command = ARGV[0].to_s
9
15
 
10
16
  if %w[--version -v version].include?(command)
@@ -12,11 +18,26 @@ if %w[--version -v version].include?(command)
12
18
  exit 0
13
19
  end
14
20
 
15
- if command == "ledger:reset"
16
- Bdgtr::Cli::GemHome.reset_with_confirmation!
21
+ if ARGV.empty? || %w[help --help -h].include?(command)
22
+ Bdgtr::Cli::Runtime.boot!(models: false)
23
+ if ARGV.length <= 1
24
+ Bdgtr::Cli::Help.print_index
25
+ else
26
+ Bdgtr::Cli::Help.print_command(ARGV[1])
27
+ end
17
28
  exit 0
18
29
  end
19
30
 
20
- warn "unknown command #{command}" unless command.empty? || %w[help --help -h].include?(command)
21
- warn "bdgtr-cli #{Bdgtr::Version::VERSION}"
22
- exit command.empty? || %w[help --help -h].include?(command) ? 0 : 1
31
+ if %w[ledger:export ledger:import ledger:project].include?(command)
32
+ environment = File.expand_path("../../config/environment.rb", __dir__)
33
+ environment = File.expand_path("../../../config/environment.rb", __dir__) unless File.exist?(environment)
34
+ unless File.exist?(environment)
35
+ warn "ledger:export, ledger:import, and ledger:project copy rows with the app database. Run them from the bdgtr app."
36
+ exit 1
37
+ end
38
+ require environment
39
+ else
40
+ Bdgtr::Cli::Runtime.boot!(models: command.start_with?("account:", "transaction:"))
41
+ end
42
+
43
+ Bdgtr::Cli.start(ARGV)
@@ -0,0 +1,188 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "yaml"
5
+
6
+ module Bdgtr
7
+ class Cli
8
+ # ~/.bdgtr/config.yml. Created the first time bdgtr runs.
9
+ class Config
10
+ MASK = "********"
11
+
12
+ def self.path
13
+ configured = ENV["BDGTR_CONFIG"].to_s.strip
14
+ return configured unless configured.empty?
15
+
16
+ File.join(Dir.home, ".bdgtr", "config.yml")
17
+ end
18
+
19
+ def self.sample_path
20
+ File.expand_path("config.sample.yml", __dir__)
21
+ end
22
+
23
+ def self.ensure!
24
+ unless File.exist?(path)
25
+ FileUtils.mkdir_p(File.dirname(path))
26
+ FileUtils.cp(sample_path, path)
27
+ end
28
+ rename_enablebanking_key!
29
+ end
30
+
31
+ def self.rename_enablebanking_key!
32
+ return unless File.exist?(path)
33
+
34
+ text = File.read(path)
35
+ updated = text.sub(/^([ \t]*)enable_banking:/, "\\1enablebanking:")
36
+ File.write(path, updated) if updated != text
37
+ end
38
+
39
+ def self.workspace_id
40
+ value = data.dig("bdgtr", "workspace_id")
41
+ return if value.nil?
42
+ return if value.is_a?(String) && value.strip.empty?
43
+
44
+ value
45
+ end
46
+
47
+ def self.workspace_id=(id)
48
+ ensure!
49
+ number = Integer(id)
50
+ text = File.read(path)
51
+ updated = text.sub(/^([ \t]*)workspace_id:[ \t]*.*$/, "\\1workspace_id: #{number}")
52
+ raise "workspace_id is missing from #{path}" if updated == text
53
+
54
+ File.write(path, updated)
55
+ end
56
+
57
+ def self.remote_url
58
+ text = data.dig("bdgtr", "url").to_s.strip
59
+ text.empty? ? nil : text
60
+ end
61
+
62
+ def self.token
63
+ text = data.dig("bdgtr", "token").to_s.strip
64
+ text.empty? ? nil : text
65
+ end
66
+
67
+ # SQLite ledger used by the CLI. A relative path starts at the config directory.
68
+ def self.ledger
69
+ text = data.dig("bdgtr", "ledger").to_s.strip
70
+ text = "bdgtr.sqlite" if text.empty?
71
+ expand_path(text)
72
+ end
73
+
74
+ def self.during_ledger
75
+ previous = Thread.current[:bdgtr_cli_ledger]
76
+ Thread.current[:bdgtr_cli_ledger] = ledger
77
+ yield
78
+ ensure
79
+ Thread.current[:bdgtr_cli_ledger] = previous
80
+ end
81
+
82
+ def self.active_ledger
83
+ Thread.current[:bdgtr_cli_ledger]
84
+ end
85
+
86
+ # The CLI ledger when that file is present, otherwise the workspace path.
87
+ def self.ledger_for(workspace)
88
+ configured = active_ledger
89
+ return configured if configured && File.exist?(configured)
90
+
91
+ stored = workspace.respond_to?(:ledger_path) ? workspace.ledger_path : nil
92
+ text = stored.to_s.strip
93
+ text.empty? ? nil : text
94
+ end
95
+
96
+ def self.expand_path(value)
97
+ text = value.to_s.strip
98
+ return if text.empty?
99
+ return File.expand_path(text) if text.start_with?("~") || File.absolute_path?(text)
100
+
101
+ File.expand_path(text, directory)
102
+ end
103
+
104
+ def self.directory
105
+ File.dirname(path)
106
+ end
107
+ private_class_method :directory
108
+
109
+ def self.api(group, key)
110
+ group_value = data.dig("api", group.to_s)
111
+ return unless group_value.is_a?(Hash)
112
+
113
+ value = group_value[key.to_s]
114
+ text = value.to_s.strip
115
+ text.empty? ? nil : text
116
+ end
117
+
118
+ # A group may be a nested map or a single value, such as a path to a .pem file.
119
+ def self.api_scalar(group)
120
+ value = data.dig("api", group.to_s)
121
+ return unless value.is_a?(String)
122
+
123
+ text = value.strip
124
+ text.empty? ? nil : text
125
+ end
126
+
127
+ def self.data
128
+ return {} unless File.exist?(path)
129
+
130
+ YAML.safe_load_file(path, aliases: false) || {}
131
+ end
132
+
133
+ def self.contents
134
+ ensure!
135
+ File.read(path)
136
+ end
137
+
138
+ def self.display
139
+ redact(contents)
140
+ end
141
+
142
+ def self.redact(text)
143
+ inside_api = false
144
+ block_indent = nil
145
+ text.each_line.map do |line|
146
+ if block_indent
147
+ if line.strip.empty? || line[/\A[ \t]*/].size > block_indent
148
+ next line if line.strip.empty?
149
+
150
+ next "#{line[/\A[ \t]*/]}#{MASK}\n"
151
+ end
152
+ block_indent = nil
153
+ end
154
+
155
+ if line.match?(/\A[ \t]*token:[ \t]+\S/)
156
+ next masked_value(line)
157
+ end
158
+
159
+ if (key = line[/\A([A-Za-z0-9_][\w-]*):/, 1])
160
+ inside_api = key == "api"
161
+ next line
162
+ end
163
+
164
+ next line unless inside_api
165
+
166
+ if line.match?(/\A[ \t]+[\w][\w-]*:[ \t]*[|>][+-]?[0-9]*[ \t]*(?:#.*)?$/)
167
+ block_indent = line[/\A[ \t]*/].size
168
+ next line
169
+ end
170
+
171
+ if line.match?(/\A[ \t]+[\w][\w-]*:[ \t]+\S/)
172
+ next masked_value(line)
173
+ end
174
+
175
+ line
176
+ end.join
177
+ end
178
+
179
+ def self.masked_value(line)
180
+ parts = line.match(/\A([ \t]*[\w][\w-]*:)([ \t]+)(.*)$/)
181
+ value, comment = parts[3].sub(/\n\z/, "").split(/[ \t]+#/, 2)
182
+ suffix = comment ? " ##{comment}" : ""
183
+ "#{parts[1]}#{parts[2]}#{MASK}#{suffix}\n"
184
+ end
185
+ private_class_method :masked_value
186
+ end
187
+ end
188
+ end
@@ -0,0 +1,15 @@
1
+ bdgtr:
2
+ workspace_id:
3
+ url: https://app.bdgtr.com
4
+ token:
5
+ ledger: bdgtr.sqlite
6
+
7
+ api:
8
+ nordigen:
9
+ secret_id:
10
+ secret_key:
11
+ # enablebanking: /path/to/private-key.pem
12
+ enablebanking:
13
+ app_id:
14
+ private_key:
15
+ redirect_url:
@@ -0,0 +1,168 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bdgtr
4
+ class Cli
5
+ # Command index and `bdgtr help COMMAND`. Loaded without Rails.
6
+ module Help
7
+ Command = Struct.new(:name, :usage, :description, :parameters, keyword_init: true)
8
+
9
+ COMMANDS = [
10
+ Command.new(
11
+ name: "workspace:set",
12
+ usage: "workspace:set WORKSPACE_ID",
13
+ description: "Store the workspace id used by the other commands.",
14
+ parameters: [ [ "WORKSPACE_ID", "Workspace id." ] ]
15
+ ),
16
+ Command.new(
17
+ name: "config",
18
+ usage: "config",
19
+ description: "Show ~/.bdgtr/config.yml and optionally edit it."
20
+ ),
21
+ Command.new(
22
+ name: "account:list",
23
+ usage: "account:list [WORKSPACE_ID]",
24
+ description: "List accounts in the configured workspace.",
25
+ parameters: [ [ "WORKSPACE_ID", "Workspace to read this once." ] ]
26
+ ),
27
+ Command.new(
28
+ name: "account:connect",
29
+ usage: "account:connect [--provider gocardless|enablebanking] [WORKSPACE_ID]",
30
+ description: "Connect a bank and choose which accounts to save.",
31
+ parameters: [
32
+ [ "--provider", "gocardless or enablebanking. Skips the provider question." ],
33
+ [ "WORKSPACE_ID", "Workspace to use this once." ]
34
+ ]
35
+ ),
36
+ Command.new(
37
+ name: "account:sync",
38
+ usage: "account:sync ACCOUNT_ID",
39
+ description: "Sync one account through its latest bank connection.",
40
+ parameters: [ [ "ACCOUNT_ID", "Account id." ] ]
41
+ ),
42
+ Command.new(
43
+ name: "account:sync:enable",
44
+ usage: "account:sync:enable ACCOUNT_ID",
45
+ description: "Turn automatic sync on for one account.",
46
+ parameters: [ [ "ACCOUNT_ID", "Account id." ] ]
47
+ ),
48
+ Command.new(
49
+ name: "account:sync:disable",
50
+ usage: "account:sync:disable ACCOUNT_ID",
51
+ description: "Turn automatic sync off for one account.",
52
+ parameters: [ [ "ACCOUNT_ID", "Account id." ] ]
53
+ ),
54
+ Command.new(
55
+ name: "account:delete",
56
+ usage: "account:delete ACCOUNT_ID",
57
+ description: "Delete one account and its transactions after confirmation.",
58
+ parameters: [ [ "ACCOUNT_ID", "Account id." ] ]
59
+ ),
60
+ Command.new(
61
+ name: "transaction:search",
62
+ usage: "transaction:search ACCOUNT_ID",
63
+ description: "List transactions. Enter opens a row and esc returns.",
64
+ parameters: [ [ "ACCOUNT_ID", "Account id." ] ]
65
+ ),
66
+ Command.new(
67
+ name: "ledger:export",
68
+ usage: "ledger:export [WORKSPACE_ID]",
69
+ description: "Copy the workspace ledger to bdgtr.ledger and remove those rows from Postgres.",
70
+ parameters: [ [ "WORKSPACE_ID", "Workspace id. Defaults to the configured workspace." ] ]
71
+ ),
72
+ Command.new(
73
+ name: "ledger:import",
74
+ usage: "ledger:import [WORKSPACE_ID]",
75
+ description: "Copy the ledger back onto Postgres, creating only missing rows.",
76
+ parameters: [ [ "WORKSPACE_ID", "Workspace id. Defaults to the configured workspace." ] ]
77
+ ),
78
+ Command.new(
79
+ name: "ledger:project",
80
+ usage: "ledger:project [WORKSPACE_ID]",
81
+ description: "Replace the Postgres rows from the ledger, keeping ids.",
82
+ parameters: [ [ "WORKSPACE_ID", "Workspace id. Defaults to the configured workspace." ] ]
83
+ ),
84
+ Command.new(
85
+ name: "ledger:push",
86
+ usage: "ledger:push",
87
+ description: "Upload the configured workspace ledger to bdgtr.url after confirmation."
88
+ ),
89
+ Command.new(
90
+ name: "ledger:pull",
91
+ usage: "ledger:pull",
92
+ description: "Download the online ledger and replace the local file after confirmation."
93
+ ),
94
+ Command.new(
95
+ name: "ledger:reset",
96
+ usage: "ledger:reset",
97
+ description: "Replace ~/.bdgtr/bdgtr.sqlite with the empty ledger after you type yes."
98
+ ),
99
+ Command.new(
100
+ name: "import:xls",
101
+ usage: "import:xls PROVIDER ACCOUNT [XLS]",
102
+ description: "Import an Excel export into the Drive .portfolio.",
103
+ parameters: [
104
+ [ "PROVIDER", "Provider name. fineco." ],
105
+ [ "ACCOUNT", "Account name in the portfolio." ],
106
+ [ "XLS", "Excel export path." ],
107
+ [ "--file", "Excel export path." ],
108
+ [ "--exclude", "Skip rows matching this regexp. Repeatable." ],
109
+ [ "--skip-lines", "Number of leading lines to skip." ],
110
+ [ "--match-security", "/REGEXP/VALUE" ],
111
+ [ "--match-offset-account", "/REGEXP/VALUE" ]
112
+ ]
113
+ ),
114
+ Command.new(
115
+ name: "spreadsheet:dump",
116
+ usage: "spreadsheet:dump",
117
+ description: "Align the Drive .portfolio with the Google spreadsheet."
118
+ ),
119
+ Command.new(
120
+ name: "spreadsheet:cleanup",
121
+ usage: "spreadsheet:cleanup",
122
+ description: "Clear spreadsheet tabs one at a time."
123
+ ),
124
+ Command.new(
125
+ name: "version",
126
+ usage: "version",
127
+ description: "Show the bdgtr version of the portfolio tools."
128
+ ),
129
+ Command.new(
130
+ name: "help",
131
+ usage: "help [COMMAND]",
132
+ description: "List commands, or describe one command.",
133
+ parameters: [ [ "COMMAND", "Command name." ] ]
134
+ )
135
+ ].freeze
136
+
137
+ def self.print_index
138
+ singles, namespaced = COMMANDS.partition { |command| !command.name.include?(":") }
139
+ singles.sort_by(&:name).each { |command| puts command.name }
140
+ puts unless singles.empty? || namespaced.empty?
141
+ namespaced.group_by { |command| command.name.split(":", 2).first }.sort.each_with_index do |(_prefix, commands), index|
142
+ puts if index.positive?
143
+ commands.each { |command| puts command.name }
144
+ end
145
+ end
146
+
147
+ def self.print_command(name)
148
+ command = COMMANDS.find { |entry| entry.name == name }
149
+ if command.nil?
150
+ warn "Unknown command #{name}"
151
+ exit 1
152
+ end
153
+
154
+ puts command.usage
155
+ puts command.description
156
+ parameters = Array(command.parameters)
157
+ return if parameters.empty?
158
+
159
+ puts
160
+ width = parameters.map { |parameter, _text| parameter.size }.max
161
+ parameters.each do |parameter, text|
162
+ puts "#{parameter.ljust(width)} #{text}"
163
+ end
164
+ end
165
+
166
+ end
167
+ end
168
+ end
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "stringio"
5
+ require "uri"
6
+
7
+ module Bdgtr
8
+ class Cli
9
+ # Uploads and downloads the workspace SQLite ledger through the online app.
10
+ class LedgerSync
11
+ def self.push
12
+ remote!
13
+ path = ledger_file
14
+ confirmed!("Push the ledger of workspace #{Config.workspace_id} to #{Config.remote_url}?")
15
+ bytes = File.binread(Core::Exchange.checkpoint!(path))
16
+ post_ledger(bytes)
17
+ puts "pushed ledger of workspace #{Config.workspace_id}"
18
+ rescue SQLite3::BusyException
19
+ warn "ledger is open"
20
+ exit 1
21
+ end
22
+
23
+ def self.pull
24
+ remote!
25
+ confirmed!("Replace the local ledger of workspace #{Config.workspace_id} with #{Config.remote_url}?")
26
+ bytes = transmit(:get, "/api/ledger/pull")
27
+ path = Core::Exchange.install!(StringIO.new(bytes.to_s.b), Config.ledger)
28
+ puts "pulled ledger to #{path}"
29
+ rescue ArgumentError => error
30
+ warn error.message
31
+ exit 1
32
+ end
33
+
34
+ def self.transmit(verb, path, body = nil, content_type = nil)
35
+ uri = endpoint(path)
36
+ request = (verb == :post ? Net::HTTP::Post : Net::HTTP::Get).new(uri)
37
+ request["Authorization"] = "Bearer #{Config.token}"
38
+ request["Accept"] = "application/octet-stream, application/json"
39
+ if body
40
+ request["Content-Type"] = content_type
41
+ request.body = body
42
+ end
43
+
44
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 15, read_timeout: 120) do |http|
45
+ response = http.request(request)
46
+ return response.body if response.is_a?(Net::HTTPSuccess)
47
+
48
+ warn "ledger request failed: #{response.code} #{response.body.to_s.byteslice(0, 500)}"
49
+ exit 1
50
+ end
51
+ end
52
+
53
+ def self.remote!
54
+ if Config.remote_url.nil? || Config.token.nil?
55
+ warn "Set bdgtr.url and bdgtr.token in #{Config.path}"
56
+ exit 1
57
+ end
58
+
59
+ uri = URI(Config.remote_url)
60
+ return if uri.is_a?(URI::HTTP) && uri.host
61
+
62
+ warn "bdgtr.url is not an http address"
63
+ exit 1
64
+ rescue URI::InvalidURIError
65
+ warn "bdgtr.url is not an http address"
66
+ exit 1
67
+ end
68
+
69
+ def self.ledger_file
70
+ path = Config.active_ledger.presence || Config.ledger
71
+ return path if path.present? && File.exist?(path)
72
+
73
+ warn "workspace #{Config.workspace_id} has no ledger file"
74
+ exit 1
75
+ end
76
+
77
+ def self.confirmed!(question)
78
+ return if Prompt.confirm(question) == :yes
79
+
80
+ warn "Aborted."
81
+ exit 1
82
+ end
83
+
84
+ def self.post_ledger(bytes)
85
+ boundary = "bdgtr#{SecureRandom.hex(12)}"
86
+ body = "".b
87
+ body << "--#{boundary}\r\n".b
88
+ body << "Content-Disposition: form-data; name=\"file\"; filename=\"ledger.sqlite\"\r\n".b
89
+ body << "Content-Type: application/octet-stream\r\n\r\n".b
90
+ body << bytes.b
91
+ body << "\r\n--#{boundary}--\r\n".b
92
+ transmit(:post, "/api/ledger/push", body, "multipart/form-data; boundary=#{boundary}")
93
+ end
94
+
95
+ def self.endpoint(path)
96
+ URI("#{Config.remote_url.sub(%r{/+\z}, "")}#{path}")
97
+ end
98
+
99
+ private_class_method :remote!, :ledger_file, :confirmed!, :post_ledger, :endpoint
100
+ end
101
+ end
102
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "io/console"
4
+
5
+ module Bdgtr
6
+ class Cli
7
+ # Confirmation. The default is yes: Enter and y continue, n declines.
8
+ # Pass default: :no to make Enter decline. Esc and Ctrl+C abort.
9
+ class Prompt
10
+ def self.confirm(question, default: :yes)
11
+ choice = default == :no ? "[y/N]" : "[Y/n]"
12
+ print "#{question} #{choice} "
13
+ $stdout.flush
14
+ decision(read_answer, default)
15
+ end
16
+
17
+ def self.decision(answer, default = :yes)
18
+ return :abort if answer.nil? || answer == :abort
19
+
20
+ text = answer.to_s
21
+ return :abort if text.include?("\u0003") || text == "\e" || text.strip == "\e"
22
+
23
+ stripped = text.strip
24
+ return default if stripped.empty?
25
+ return :yes if %w[y yes].include?(stripped.downcase)
26
+ return :no if %w[n no].include?(stripped.downcase)
27
+
28
+ :no
29
+ end
30
+
31
+ def self.read_answer
32
+ if $stdin.tty?
33
+ char = $stdin.getch
34
+ return :abort if char.nil? || char == "\e" || char == "\u0003"
35
+
36
+ puts(char == "\r" || char == "\n" ? "" : char)
37
+ char == "\r" || char == "\n" ? "" : char
38
+ else
39
+ $stdin.gets
40
+ end
41
+ rescue Interrupt
42
+ :abort
43
+ end
44
+ private_class_method :read_answer
45
+ end
46
+ end
47
+ end