upsert-plan 1.0.0

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 (6) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +22 -0
  3. data/README.md +49 -0
  4. data/bin/upsert-plan +24 -0
  5. data/lib/upsert_plan.rb +168 -0
  6. metadata +62 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 20a58d9faba048963d75e93f88d3811f2cc586d6b40b7f46bb70bcd43642571c
4
+ data.tar.gz: 09e11cc882522d991a7beb3025f0a73f7e26bd62140139f03fb74eb4dd52c96c
5
+ SHA512:
6
+ metadata.gz: 57f11ef7f3c30fd9e7fc5295c4b3f661dc7a77f3c0f29de2fbfc0c7c3b136e492c59e1f3e4e186545b4bf80b71af1431e78ddbb1b5d03be6edcb2e97df6b7f9d
7
+ data.tar.gz: 867374f668a6c63c6bba77086d78a42b6626cd8813f5ae9e286ccf913af973de1455bba0172868ca7d32837fadd7cf9a2e07e330fde16b0a41302acb92312cba
data/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 OneGTMLab
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.
22
+
data/README.md ADDED
@@ -0,0 +1,49 @@
1
+ # upsert-plan
2
+
3
+ Ruby command line tool and library. Give it an existing CSV and an incoming CSV and the column (or columns) that identify a row. It plans an upsert without calling anything: each incoming row is an insert, an update (with every changed column as column: old -> new) or unchanged, and it counts the existing rows that are not in the incoming file. Nothing is deleted and nothing is sent anywhere.
4
+
5
+ Part of the [OneGTMLab](https://www.onegtmlab.dev) free GTM tools. Background on the idea: [Freshsales](https://www.onegtmlab.dev/tool-directory/crm/freshsales).
6
+
7
+ ## Install
8
+
9
+ ```
10
+ gem install upsert-plan
11
+ ```
12
+
13
+ ## Use
14
+
15
+ Two CSV files with a header row, and --key with one column name or a comma list of names (a composite key: the parts are trimmed, lower-cased and joined with a bar). It is a diff of two files you give it: it knows no CRM, calls no API and deletes nothing. --ignore takes a comma list of columns to leave out of the comparison (default none). The compared columns are the columns present in both files, minus the key columns, minus the ignored ones; columns only in the incoming file are listed once as not compared. Values are compared trimmed and case-sensitive; keys are trimmed and case-insensitive. --empty keep|overwrite (default keep, set by you): with keep an empty incoming cell is never a change; with overwrite an empty incoming cell that differs from a filled existing cell is a change, shown as old -> (empty). Existing keys that are absent from the incoming file are only counted. --out FILE writes a CSV of the incoming rows that are an insert or an update, with an extra first column called action. Headers are matched trimmed and ignoring upper and lower case, extra columns are fine, and a UTF-8 BOM and CRLF line endings are accepted. A key column missing in either file (the file is named), an empty key value (the file and row are named), a duplicate key inside one file (the key is named), a bad option, a missing file or an incoming file with no data rows stops the run with an error and a non-zero exit code.
16
+
17
+ ```
18
+ $ ruby bin/upsert-plan existing.csv incoming.csv --key email
19
+ existing rows: 5
20
+ incoming rows: 6
21
+ key: email
22
+ compared columns: name, company, plan, phone
23
+ not compared (not in existing): source
24
+ empty incoming cells: keep (an empty cell is not a change)
25
+
26
+ insert: 2
27
+ update: 2
28
+ unchanged: 2
29
+ not in incoming (nothing is deleted): 1
30
+
31
+ updates (2)
32
+ beta@example.com
33
+ plan: Pro -> Basic
34
+ gamma@example.com
35
+ company: Example Com -> Example Org
36
+ phone: (empty) -> 555-0103
37
+
38
+ inserts (2)
39
+ zeta@example.com
40
+ eta@example.com
41
+ ```
42
+
43
+ ## Test
44
+
45
+ ```
46
+ ruby test/run.rb
47
+ ```
48
+
49
+ Offline, no network calls, no dependencies beyond the language runtime. MIT licensed.
data/bin/upsert-plan ADDED
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require_relative '../lib/upsert_plan'
5
+
6
+ if ARGV.empty? || ARGV.include?('-h') || ARGV.include?('--help')
7
+ warn "usage: upsert-plan existing.csv incoming.csv --key COLUMN[,COLUMN] [--ignore COLUMNS] [--empty keep|overwrite] [--out FILE]\n" \
8
+ "More: https://www.onegtmlab.dev/tool-directory/crm/freshsales"
9
+ exit 2
10
+ end
11
+
12
+ begin
13
+ o = UpsertPlan.parse_args(ARGV)
14
+ result = UpsertPlan.plan(File.read(o[:existing], encoding: 'bom|utf-8'), File.read(o[:incoming], encoding: 'bom|utf-8'),
15
+ key: o[:key], ignore: o[:ignore], empty: o[:empty],
16
+ existing_name: File.basename(o[:existing]), incoming_name: File.basename(o[:incoming]))
17
+ print UpsertPlan.render(result)
18
+ if o[:out]
19
+ File.write(o[:out], UpsertPlan.plan_csv(result))
20
+ puts "\nwrote #{result[:plan_rows].size} rows to #{o[:out]}"
21
+ end
22
+ rescue ArgumentError, SystemCallError, CSV::MalformedCSVError => e
23
+ abort "error: #{e.message}"
24
+ end
@@ -0,0 +1,168 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'csv'
4
+
5
+ # Plan an upsert of one CSV into another by a unique key, without calling anything and without deleting anything.
6
+ # It is a diff of two files you give it: it knows no CRM and calls no API.
7
+ module UpsertPlan
8
+ Table = Struct.new(:name, :headers, :display, :rows, keyword_init: true)
9
+
10
+ EMPTY_MODES = %w[keep overwrite].freeze
11
+
12
+ # Reads CSV text. Headers are matched trimmed and case-insensitive; a UTF-8 BOM and CRLF line endings are handled.
13
+ # rows keep the raw cells (padded to the header width); values are trimmed only when compared.
14
+ def self.read_table(text, name)
15
+ rows = CSV.parse(text.sub(/\A/, ''), skip_blanks: true)
16
+ raise ArgumentError, "#{name}: no header row" if rows.empty?
17
+
18
+ display = rows.shift.map { |h| h.to_s.strip }
19
+ headers = display.map(&:downcase)
20
+ data = rows.map { |r| Array.new(headers.size) { |i| r[i].to_s } }
21
+ Table.new(name: name, headers: headers, display: display, rows: data)
22
+ end
23
+
24
+ def self.key_columns(raw)
25
+ cols = raw.to_s.split(',').map { |c| c.strip.downcase }
26
+ raise ArgumentError, '--key needs at least one column name' if cols.empty? || cols.any?(&:empty?)
27
+
28
+ cols.uniq
29
+ end
30
+
31
+ # Returns [normalised key, display key] for every row; raises on an empty key part or a duplicate key.
32
+ def self.keys_for(table, key_cols)
33
+ idx = key_cols.map { |c| table.headers.index(c) }
34
+ seen = {}
35
+ table.rows.each_with_index.map do |row, i|
36
+ parts = idx.map { |j| row[j].strip }
37
+ if parts.any?(&:empty?)
38
+ raise ArgumentError, "#{table.name} row #{i + 2}: empty key value in column #{key_cols[parts.index(&:empty?)]}"
39
+ end
40
+
41
+ norm = parts.map(&:downcase).join('|')
42
+ raise ArgumentError, "duplicate key #{parts.join('|').inspect} in #{table.name} (rows #{seen[norm]} and #{i + 2})" if seen.key?(norm)
43
+
44
+ seen[norm] = i + 2
45
+ [norm, parts.join('|')]
46
+ end
47
+ end
48
+
49
+ # existing_text / incoming_text: CSV text. key: array of column names (see key_columns). ignore: columns left out of the
50
+ # comparison. empty: 'keep' (an empty incoming cell is not a change) or 'overwrite' (it is, when it differs).
51
+ def self.plan(existing_text, incoming_text, key:, ignore: [], empty: 'keep', existing_name: 'existing file',
52
+ incoming_name: 'incoming file')
53
+ raise ArgumentError, "--empty must be keep or overwrite, got #{empty.inspect}" unless EMPTY_MODES.include?(empty)
54
+
55
+ ex = read_table(existing_text, existing_name)
56
+ inc = read_table(incoming_text, incoming_name)
57
+ key_cols = key.map { |c| c.strip.downcase }
58
+ [ex, inc].each do |t|
59
+ missing = key_cols - t.headers
60
+ raise ArgumentError, "key column(s) #{missing.join(', ')} not found in #{t.name}" unless missing.empty?
61
+ end
62
+ raise ArgumentError, "no data rows in #{inc.name}" if inc.rows.empty?
63
+
64
+ ex_keys = keys_for(ex, key_cols)
65
+ inc_keys = keys_for(inc, key_cols)
66
+ ignore_cols = ignore.map { |c| c.strip.downcase }
67
+ compared = (ex.headers & inc.headers).uniq - key_cols - ignore_cols
68
+ not_compared = (inc.headers - ex.headers).uniq - ignore_cols
69
+ ex_index = {}
70
+ ex_keys.each_with_index { |(norm, _), i| ex_index[norm] = ex.rows[i] }
71
+
72
+ result = { existing_rows: ex.rows.size, incoming_rows: inc.rows.size, key: key_cols, compared: compared,
73
+ not_compared: not_compared, ignored: ignore_cols, empty: empty, inserts: [], updates: [], unchanged: 0,
74
+ incoming_headers: inc.display, plan_rows: [] }
75
+ inc.rows.each_with_index do |row, i|
76
+ norm, shown = inc_keys[i]
77
+ old = ex_index[norm]
78
+ if old.nil?
79
+ result[:inserts] << shown
80
+ result[:plan_rows] << ['insert', row]
81
+ next
82
+ end
83
+ changes = compared.filter_map do |c|
84
+ o = old[ex.headers.index(c)].strip
85
+ n = row[inc.headers.index(c)].strip
86
+ next if o == n
87
+ next if n.empty? && empty == 'keep'
88
+
89
+ [inc.display[inc.headers.index(c)], o, n]
90
+ end
91
+ if changes.empty?
92
+ result[:unchanged] += 1
93
+ else
94
+ result[:updates] << { key: shown, changes: changes }
95
+ result[:plan_rows] << ['update', row]
96
+ end
97
+ end
98
+ inc_set = inc_keys.to_h { |norm, _| [norm, true] }
99
+ result[:not_in_incoming] = ex_keys.count { |norm, _| !inc_set.key?(norm) }
100
+ result
101
+ end
102
+
103
+ def self.shown(value)
104
+ value.empty? ? '(empty)' : value
105
+ end
106
+
107
+ def self.render(r)
108
+ out = +"existing rows: #{r[:existing_rows]}\nincoming rows: #{r[:incoming_rows]}\n"
109
+ out << "key: #{r[:key].join(', ')}\n"
110
+ out << "compared columns: #{r[:compared].empty? ? '(none)' : r[:compared].join(', ')}\n"
111
+ out << "not compared (not in existing): #{r[:not_compared].join(', ')}\n" unless r[:not_compared].empty?
112
+ out << "left out with --ignore: #{r[:ignored].join(', ')}\n" unless r[:ignored].empty?
113
+ out << "empty incoming cells: #{r[:empty] == 'keep' ? 'keep (an empty cell is not a change)' : 'overwrite (an empty cell that differs is a change)'}\n"
114
+ out << "\ninsert: #{r[:inserts].size}\nupdate: #{r[:updates].size}\nunchanged: #{r[:unchanged]}\n"
115
+ out << "not in incoming (nothing is deleted): #{r[:not_in_incoming]}\n"
116
+ out << "\nupdates (#{r[:updates].size})\n"
117
+ r[:updates].each do |u|
118
+ out << " #{u[:key]}\n"
119
+ u[:changes].each { |c, o, n| out << " #{c}: #{shown(o)} -> #{shown(n)}\n" }
120
+ end
121
+ out << "\ninserts (#{r[:inserts].size})\n"
122
+ r[:inserts].each { |k| out << " #{k}\n" }
123
+ out
124
+ end
125
+
126
+ # CSV of the incoming rows that are insert or update, with the action as the first column.
127
+ def self.plan_csv(r)
128
+ CSV.generate do |csv|
129
+ csv << (['action'] + r[:incoming_headers])
130
+ r[:plan_rows].each { |action, row| csv << ([action] + row) }
131
+ end
132
+ end
133
+
134
+ # Returns { existing:, incoming:, key:, ignore:, empty:, out: }; raises ArgumentError on bad input.
135
+ def self.parse_args(argv)
136
+ args = argv.dup
137
+ opts = { key: nil, ignore: [], empty: 'keep', out: nil }
138
+ files = []
139
+ until args.empty?
140
+ arg = args.shift
141
+ name, inline = arg.start_with?('--') && arg.include?('=') ? arg.split('=', 2) : [arg, nil]
142
+ case name
143
+ when '--key', '--ignore', '--empty', '--out'
144
+ value = inline
145
+ if value.nil?
146
+ raise ArgumentError, "#{name} needs a value" if args.empty?
147
+
148
+ value = args.shift
149
+ end
150
+ case name
151
+ when '--key' then opts[:key] = key_columns(value)
152
+ when '--ignore' then opts[:ignore] = value.split(',').map { |c| c.strip.downcase }.reject(&:empty?)
153
+ when '--empty'
154
+ raise ArgumentError, "--empty must be keep or overwrite, got #{value.inspect}" unless EMPTY_MODES.include?(value)
155
+
156
+ opts[:empty] = value
157
+ when '--out' then opts[:out] = value
158
+ end
159
+ when /\A-/ then raise ArgumentError, "unknown option #{name}"
160
+ else files << arg
161
+ end
162
+ end
163
+ raise ArgumentError, 'two CSV files are needed: existing.csv incoming.csv' unless files.size == 2
164
+ raise ArgumentError, '--key is required (one column name or a comma list)' unless opts[:key]
165
+
166
+ opts.merge(existing: files[0], incoming: files[1])
167
+ end
168
+ end
metadata ADDED
@@ -0,0 +1,62 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: upsert-plan
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - OneGTMLab
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: csv
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ -
17
+ - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: "0"
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ -
25
+ - ">="
26
+ - !ruby/object:Gem::Version
27
+ version: "0"
28
+ description: "Ruby CLI and library: compare an existing CSV with an incoming CSV by a key (one column or several), list the inserts, the updates with column: old -> new, the unchanged rows and the existing keys missing from the incoming file. It calls no API and deletes nothing. Offline."
29
+ executables:
30
+ - upsert-plan
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - LICENSE
35
+ - README.md
36
+ - bin/upsert-plan
37
+ - lib/upsert_plan.rb
38
+ homepage: "https://www.onegtmlab.dev/tool-directory/crm/freshsales"
39
+ licenses:
40
+ - MIT
41
+ metadata:
42
+ source_code_uri: "https://github.com/jaizendra-netizen/upsert-plan"
43
+ rdoc_options: []
44
+ require_paths:
45
+ - lib
46
+ required_ruby_version: !ruby/object:Gem::Requirement
47
+ requirements:
48
+ -
49
+ - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: "2.7"
52
+ required_rubygems_version: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ -
55
+ - ">="
56
+ - !ruby/object:Gem::Version
57
+ version: "0"
58
+ requirements: []
59
+ rubygems_version: 4.1.0
60
+ specification_version: 4
61
+ summary: "Plan an upsert by a unique key: which rows of one CSV are inserts, updates or unchanged against another CSV"
62
+ test_files: []