dev_archive 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 78b46d3e90671b1c9c27286b7dc9fa2368606dedddbea6fe4cdfe943199e84b2
4
+ data.tar.gz: 85d514e0d3a76cf6101143e12d087b6cdb70f62f147520e72fdd9f339860dc92
5
+ SHA512:
6
+ metadata.gz: 17b2a150829b1bebb45937203e3221b477bea958c27da9e404e85beec808d5c295b6190c4151282766d4ab68f1d25f282867f94281581d6177f15cda99629496
7
+ data.tar.gz: 9b3d0536aaf77cc561e9c1dbcaa55e70f3e32d956d51eb2cc68e3086bdeaf2d80036a828152fecec9ded5fc20e34e97e55ba699da7ce6d031a1110643f64b920
data/.gitignore ADDED
@@ -0,0 +1,8 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.4
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 2.7.5
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at pete.kinnecom@appfolio.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in dev_archive.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+ gem "rubocop", "~> 1.7"
data/Gemfile.lock ADDED
@@ -0,0 +1,45 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ dev_archive (0.1.0)
5
+ commander (~> 4.5)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ ast (2.4.2)
11
+ commander (4.6.0)
12
+ highline (~> 2.0.0)
13
+ highline (2.0.3)
14
+ parallel (1.22.1)
15
+ parser (3.1.1.0)
16
+ ast (~> 2.4.1)
17
+ rainbow (3.1.1)
18
+ rake (13.0.6)
19
+ regexp_parser (2.3.0)
20
+ rexml (3.2.5)
21
+ rubocop (1.27.0)
22
+ parallel (~> 1.10)
23
+ parser (>= 3.1.0.0)
24
+ rainbow (>= 2.2.2, < 4.0)
25
+ regexp_parser (>= 1.8, < 3.0)
26
+ rexml
27
+ rubocop-ast (>= 1.16.0, < 2.0)
28
+ ruby-progressbar (~> 1.7)
29
+ unicode-display_width (>= 1.4.0, < 3.0)
30
+ rubocop-ast (1.16.0)
31
+ parser (>= 3.1.1.0)
32
+ ruby-progressbar (1.11.0)
33
+ unicode-display_width (2.1.0)
34
+
35
+ PLATFORMS
36
+ x86_64-darwin-19
37
+ x86_64-darwin-20
38
+
39
+ DEPENDENCIES
40
+ dev_archive!
41
+ rake (~> 13.0)
42
+ rubocop (~> 1.7)
43
+
44
+ BUNDLED WITH
45
+ 2.2.17
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Pete Kinnecom
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
13
+ all 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
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # DevArchive
2
+
3
+ Save and restore snapshots of stateful services to a central archive. Have a
4
+ development database that you want to restore to a prior state? Just take a
5
+ snapshot and restore it later!
6
+
7
+ ## Backup
8
+
9
+ ```bash
10
+ # Uses your EDITOR to add details for the snapshot.
11
+ # Uses the default configured "stores" for creating the snapshot
12
+ dev_archive backup
13
+
14
+ # Add a message from the command line:
15
+ dev_archive backup --message "Add message from command line"
16
+ dev_archive backup -m "Add message from command line"
17
+
18
+ # Override which stores are used for the snapshot
19
+ dev_archive --store custom_store_1,custom_store_2
20
+ ```
21
+
22
+ See the "Configure" section for how add a custom store.
23
+
24
+ ## Show
25
+
26
+ ```bash
27
+ # Show the full details for a given snapshot
28
+ dev_archive show {id}
29
+ ```
30
+
31
+
32
+ ## Restore
33
+
34
+ ```bash
35
+ # Restore the given snapshot
36
+ dev_archive restore {id}
37
+ ```
38
+
39
+ ## List
40
+
41
+ ```bash
42
+ # list all snapshots (pipe to `less` if you like)
43
+ dev_archive list
44
+ ```
45
+
46
+ ## Delete
47
+
48
+ ```bash
49
+ # Delete the given snapshot
50
+ dev_archive rm {id}
51
+ ```
52
+
53
+ ## Configure
54
+
55
+ A custom configuration can be written at the location `$HOME/.config/dev_archive.rb`. It is written in ruby. Here is an example config:
56
+
57
+ ```ruby
58
+
59
+ DevArchive.configure do |config|
60
+
61
+ # Configure where the snapshots are stored. Defaults to `$HOME/.dev_archive`
62
+ config.storage_path = "/path/to/snapshot_dir"
63
+
64
+ # Configure which stores are active by default (can be overridden with --store
65
+ # option on command line). The default store is "mysql_rails" which saves a
66
+ # snapshot of all databases for the Rails app found in the CWD.
67
+ config.active_stores = ["store_1", "store_2"]
68
+
69
+ # Creating a custom store:
70
+ #
71
+ # Stores must implement two methods:
72
+ #
73
+ # backup: accepts a directory for data and returns a JSON hash (with string
74
+ # keys) for use in restoring.
75
+ #
76
+ # restore: accepts the metadata JSON data created when making the backup. No
77
+ # return value.
78
+ #
79
+ # Stores can either be defined as objects/classes/modules or a builtin store
80
+ # builder can be used.
81
+
82
+ # Using an object:
83
+
84
+ class MyCustomStore
85
+ def backup(dir)
86
+ path = File.join(dir, "my_custom_store.txt")
87
+ File.write(path, "hello")
88
+
89
+ { "path" => path }
90
+ end
91
+
92
+ def restore(metadata)
93
+ puts(File.read(metadata.fetch("path")))
94
+ end
95
+ end
96
+
97
+ config.register_store("my_custom_store", MyCustomStore.new)
98
+
99
+
100
+ # Using the store builder:
101
+
102
+ config.register_store("my_customer_store") do |store|
103
+ store.backup do |dir|
104
+ path = File.join(dir, "my_custom_store.txt")
105
+ File.write(path, "hello")
106
+
107
+ { "path" => path }
108
+ end
109
+
110
+ store.restore do |metadata|
111
+ puts(File.read(metadata.fetch("path")))
112
+ end
113
+ end
114
+ end
115
+ ```
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rubocop/rake_task"
5
+
6
+ RuboCop::RakeTask.new
7
+
8
+ task default: :rubocop
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "dev_archive"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/dev_archive/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "dev_archive"
7
+ spec.version = DevArchive::VERSION
8
+ spec.authors = ["Pete Kinnecom"]
9
+ spec.email = ["git@k7u7.com"]
10
+
11
+ spec.summary = <<~TEXT.chomp
12
+ Save and restore snapshots of stateful services to a central archive. The
13
+ default action is to backup all databases for the current rails apps,
14
+ however, custom actions can easily be configured.
15
+ TEXT
16
+
17
+ spec.homepage = "https://github.com/petekinnecom/dev_archive"
18
+ spec.license = "WTFPL2"
19
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0")
20
+
21
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
22
+
23
+ spec.metadata["homepage_uri"] = spec.homepage
24
+ spec.metadata["source_code_uri"] = spec.homepage
25
+
26
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
27
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
28
+ end
29
+ spec.bindir = "exe"
30
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
31
+ spec.require_paths = ["lib"]
32
+
33
+ spec.add_dependency("commander", "~> 4.5")
34
+ end
data/exe/dev_archive ADDED
@@ -0,0 +1,112 @@
1
+ #! /usr/bin/env ruby
2
+
3
+ # frozen_string_literal: true
4
+
5
+ if $PROGRAM_NAME == __FILE__
6
+ require "bundler/setup"
7
+ end
8
+
9
+ require "commander"
10
+ require "dev_archive"
11
+
12
+ module DevArchive
13
+ class CommanderCli
14
+ include Commander::Methods
15
+
16
+ def run
17
+ DevArchive::Cfg.instance.load
18
+
19
+ program :name, "DevArchive"
20
+ program :version, DevArchive::VERSION
21
+ program(:description, DevArchive::DESCRIPTION)
22
+
23
+ command :backup do |c|
24
+ c.syntax = "dev_archive backup"
25
+ c.description = "Save a snapshot"
26
+
27
+ c.option "-m MESSAGE", "--message MESSAGE", String, "Description"
28
+
29
+ c.option(
30
+ "-s STORES",
31
+ "--stores STORES",
32
+ Array,
33
+ "Comma separated list of stores to activate,
34
+ defaults to mysql_rails"
35
+ )
36
+
37
+ c.action do |_args, options|
38
+ message = (
39
+ if options.message
40
+ options.message.strip
41
+ else
42
+ ask_editor(File.read(File.join(__dir__, "../lib/template.txt")))
43
+ .split("\n")
44
+ .reject { |l| l.match(/\A#|\A\n/) }
45
+ .join("\n")
46
+ .strip
47
+ end
48
+ )
49
+
50
+ if options.stores
51
+ DevArchive::Cfg.instance.active_stores = options.stores
52
+ end
53
+
54
+ DevArchive::Cli.backup(
55
+ msg: message
56
+ )
57
+ end
58
+ end
59
+
60
+ command :restore do |c|
61
+ c.syntax = "dev_archive restore ID"
62
+ c.description = "Restore the state of the databases."
63
+
64
+ c.action do |args, _options|
65
+ raise "exactly one ID required" unless args.count == 1
66
+
67
+ DevArchive::Cli.restore(
68
+ id: args.first
69
+ )
70
+ end
71
+ end
72
+
73
+ command :list do |c|
74
+ c.syntax = "dev_archive list"
75
+ c.description = "List available snapshots"
76
+
77
+ c.action do |_args, options|
78
+ DevArchive::Cli.list
79
+ end
80
+ end
81
+
82
+ command :show do |c|
83
+ c.syntax = "dev_archive show"
84
+ c.description = "Show full message for snapshot"
85
+
86
+ c.action do |args, options|
87
+ raise "exactly one id is required" unless args.length == 1
88
+
89
+ DevArchive::Cli.show(args.first)
90
+ end
91
+ end
92
+
93
+ command :rm do |c|
94
+ c.syntax = "dev_archive rm"
95
+ c.description = "Delete an snapshot"
96
+
97
+ c.action do |args, options|
98
+ raise "exactly one id is required" unless args.length == 1
99
+
100
+ DevArchive::Cli.delete(args.first)
101
+ end
102
+ end
103
+
104
+ default_command :list
105
+
106
+ run!
107
+ end
108
+ end
109
+ end
110
+
111
+
112
+ DevArchive::CommanderCli.new.run
@@ -0,0 +1,56 @@
1
+ module DevArchive
2
+ module Archives
3
+ class Builder
4
+ def self.call(dir:)
5
+ new(dir).call
6
+ end
7
+
8
+ attr_reader :dir
9
+ def initialize(dir)
10
+ @dir = dir
11
+ end
12
+
13
+ def call
14
+ stores_metadata = (
15
+ Cfg
16
+ .stores
17
+ .map { |name, store| store.backup(dir)&.merge(type: name) }
18
+ .compact
19
+ )
20
+
21
+ {
22
+ stores: stores_metadata
23
+ }
24
+ end
25
+ end
26
+
27
+ class Restore
28
+ def self.call(metadata)
29
+ new(metadata).call
30
+ end
31
+
32
+ attr_reader :metadata
33
+ def initialize(metadata)
34
+ @metadata = metadata
35
+ end
36
+
37
+ def call
38
+ metadata.fetch("stores").each do |store_metadata|
39
+ store = Cfg.instance.store(store_metadata.fetch("type"))
40
+ store.restore(store_metadata)
41
+ end
42
+ end
43
+ end
44
+
45
+ class Presenter
46
+ def self.call(metadata)
47
+ new(metadata).call
48
+ end
49
+
50
+ attr_reader :metadata
51
+ def initialize(metadata)
52
+ @metadata = metadata
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,104 @@
1
+ require "dev_archive/shell"
2
+ require "dev_archive/repositories"
3
+
4
+ module DevArchive
5
+ class StoreBuilder
6
+ class CustomStore
7
+ def initialize(backup:, restore:)
8
+ @backup = backup
9
+ @restore = restore
10
+ end
11
+
12
+ def backup(dir)
13
+ @backup.call(dir)
14
+ end
15
+
16
+ def restore(metadata)
17
+ @restore.call(metadata)
18
+ end
19
+ end
20
+
21
+ def backup(&block)
22
+ @backup = block
23
+ end
24
+
25
+ def restore(&block)
26
+ @restore = block
27
+ end
28
+
29
+ def to_store
30
+ CustomStore.new(backup: @backup, restore: @restore)
31
+ end
32
+ end
33
+
34
+ class Cfg
35
+ class << self
36
+ def instance
37
+ @instance ||= Cfg.new
38
+ end
39
+
40
+ [ :stores, :pwd, :repository, :shell ].each do |meth|
41
+ define_method(meth) do |*args|
42
+ instance.public_send(meth, *args)
43
+ end
44
+ end
45
+ end
46
+
47
+ attr_accessor :pwd, :storage_path, :active_stores
48
+ def initialize
49
+ self.active_stores = []
50
+ end
51
+
52
+ def load(path = ".config/dev_archive.rb")
53
+ config_path = File.join(ENV["HOME"], path)
54
+
55
+ require("dev_archive/default_configuration")
56
+ Kernel.load(config_path) if File.exist?(config_path)
57
+ end
58
+
59
+ def register_store(name, klass=nil, active_by_default: true, &block)
60
+ store = (
61
+ if klass
62
+ klass
63
+ else
64
+ builder = StoreBuilder.new
65
+ yield(builder)
66
+ builder.to_store
67
+ end
68
+ )
69
+
70
+ store_registry[name] = store
71
+ if active_by_default
72
+ active_stores << name
73
+ end
74
+ end
75
+
76
+ def repository
77
+ Repositories::FileSystem.new(path: storage_path)
78
+ end
79
+
80
+ def store(name)
81
+ store_registry.fetch(name)
82
+ end
83
+
84
+ def stores
85
+ unknown_keys = active_stores - store_registry.keys
86
+
87
+ if !unknown_keys.empty?
88
+ raise ArgumentError.new("invalid store(s): #{unknown_keys.join(",")}")
89
+ end
90
+
91
+ store_registry.slice(*active_stores)
92
+ end
93
+
94
+ def shell
95
+ @shell ||= Shell.new
96
+ end
97
+
98
+ private
99
+
100
+ def store_registry
101
+ @store_registry ||= {}
102
+ end
103
+ end
104
+ end
@@ -0,0 +1,38 @@
1
+ require "ostruct"
2
+ require "time"
3
+ require "json"
4
+ require "securerandom"
5
+
6
+ require "dev_archive/stores"
7
+ require "dev_archive/archives"
8
+ require "dev_archive/formatters"
9
+
10
+ module DevArchive
11
+ class Cli
12
+ class << self
13
+ def backup(msg:)
14
+ if msg.empty?
15
+ Cfg.shell.warn("aborting due to empty message")
16
+ else
17
+ Cfg.repository.add(msg)
18
+ end
19
+ end
20
+
21
+ def restore(id:)
22
+ Cfg.repository.restore(id)
23
+ end
24
+
25
+ def list
26
+ Cfg.repository.list
27
+ end
28
+
29
+ def show(id)
30
+ Cfg.repository.show(id)
31
+ end
32
+
33
+ def delete(id)
34
+ Cfg.repository.delete(id)
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,32 @@
1
+ DevArchive.configure do |config|
2
+ config.register_store("mysql_rails") do |store|
3
+ store.backup do |dir|
4
+ existing_databases = (
5
+ config
6
+ .shell
7
+ .run("mysql --execute 'show databases' --silent --skip-column-names")
8
+ )
9
+
10
+ db_names = (
11
+ config
12
+ .shell
13
+ .run("sh -c 'cd $(git rev-parse --show-toplevel) && git grep database:.*_development *database.yml || exit 0'")
14
+ .map { |line| line.match(/database:\s+(.*_development)\s*$/) }
15
+ .compact
16
+ .map { |match| match[1] }
17
+ .select { |db| existing_databases.include?(db) }
18
+ .reject { |db| db.match(/_tmp_/)}
19
+ )
20
+
21
+ next if db_names.empty?
22
+
23
+ DevArchive::Stores::Mysql.bind(db_names).backup(dir)
24
+ end
25
+
26
+ store.restore do |metadata|
27
+ DevArchive::Stores::Mysql.restore(metadata)
28
+ end
29
+ end
30
+
31
+ config.storage_path = File.join(ENV["HOME"], ".dev_archive")
32
+ end
@@ -0,0 +1,49 @@
1
+ module DevArchive
2
+ module Formatters
3
+ class List
4
+ def self.call(metadata)
5
+ new(metadata).call
6
+ end
7
+
8
+ attr_reader :metadata
9
+ def initialize(metadata)
10
+ @metadata = metadata
11
+ end
12
+
13
+ def call
14
+ id = metadata.fetch("id")
15
+ timestamp = Time.parse(metadata.fetch("timestamp")).strftime("%F %H:%M")
16
+ message = metadata.fetch("message")
17
+
18
+ short_message = message.split("\n").first
19
+ Cfg.shell.puts([id, timestamp, short_message].join(" : "))
20
+ end
21
+ end
22
+
23
+ class Show
24
+ def self.call(metadata)
25
+ new(metadata).call
26
+ end
27
+
28
+ attr_reader :metadata
29
+ def initialize(metadata)
30
+ @metadata = metadata
31
+ end
32
+
33
+ def call
34
+ id = metadata.fetch("id")
35
+ timestamp = Time.parse(metadata.fetch("timestamp")).strftime("%F %H:%M")
36
+ message = metadata.fetch("message")
37
+
38
+ Cfg.shell.puts(
39
+ [
40
+ "id: #{id}",
41
+ "time: #{timestamp}",
42
+ "----------------------",
43
+ message
44
+ ].join("\n")
45
+ )
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,78 @@
1
+ module DevArchive
2
+ module Repositories
3
+ class FileSystem
4
+ SCHEMA = "0"
5
+ attr_reader :path
6
+ def initialize(path:)
7
+ @path = path
8
+ end
9
+
10
+ def add(message)
11
+ id = SecureRandom.uuid
12
+ timestamp = Time.now
13
+ dir = mkdir(id)
14
+
15
+ archive_metadata = Archives::Builder.call(dir: dir)
16
+
17
+ if archive_metadata.fetch(:stores).empty?
18
+ Cfg.shell.puts("no data to save")
19
+ else
20
+ metadata = {
21
+ __schema__: SCHEMA,
22
+ id: id,
23
+ message: message,
24
+ timestamp: timestamp.utc.iso8601,
25
+ dir: dir,
26
+ archive: archive_metadata
27
+ }
28
+
29
+ Cfg.shell.puts("writing metadata: #{metadata.to_json}")
30
+ File.write(File.join(dir, "metadata.json"), JSON.pretty_generate(metadata))
31
+ end
32
+ end
33
+
34
+ def restore(id)
35
+ metadata = JSON.parse(File.read(File.join(path, id, "metadata.json")))
36
+
37
+ Archives::Restore.call(metadata.dig("archive"))
38
+ end
39
+
40
+ def list
41
+ Dir
42
+ .glob(File.join(path, "**/metadata.json"))
43
+ .map { |metadata| JSON.parse(File.read(metadata)) }
44
+ .sort_by { |metadata| metadata.fetch("timestamp") }
45
+ .reverse
46
+ .each do |metadata|
47
+ Formatters::List.call(metadata)
48
+ end
49
+ end
50
+
51
+ def show(id)
52
+ Formatters::Show.call(
53
+ JSON.parse(File.read(File.join(path, id, "metadata.json")))
54
+ )
55
+ end
56
+
57
+ def delete(id)
58
+ dir = File.join(path, id)
59
+
60
+ raise ArgumentError.new("unknown snapshot: #{id}") unless File.exist?(dir)
61
+
62
+ FileUtils.rm_rf(dir)
63
+ end
64
+
65
+ private
66
+
67
+ def timestamp
68
+ @timestamp ||= Time.now
69
+ end
70
+
71
+ def mkdir(id)
72
+ dir = File.join(path, id)
73
+ FileUtils.mkdir(dir)
74
+ dir
75
+ end
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,41 @@
1
+ module DevArchive
2
+ class Shell
3
+ CODES = {
4
+ red: 31,
5
+ green: 32,
6
+ yellow: 33,
7
+ pink: 35,
8
+ }.freeze
9
+
10
+ CommandFailureError = Class.new(StandardError)
11
+
12
+ def run(cmd)
13
+ puts(cmd)
14
+
15
+ `#{cmd}`
16
+ .split("\n")
17
+ .tap { raise CommandFailureError.new(cmd) unless $? == 0 }
18
+ end
19
+
20
+ def warn(msg)
21
+ print "#{colorize(msg, :red)}\n"
22
+ end
23
+
24
+ def notify(msg)
25
+ print "#{colorize(msg, :yellow)}\n"
26
+ end
27
+
28
+ def puts(msg)
29
+ print "#{msg}\n"
30
+ end
31
+
32
+ private
33
+
34
+ # colorization
35
+ def colorize(msg, color)
36
+ color_code = CODES.fetch(color)
37
+
38
+ "\e[#{color_code}m#{msg}\e[0m"
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,74 @@
1
+ module DevArchive
2
+ module Stores
3
+ module Mysql
4
+ class BoundStore
5
+ attr_reader :names
6
+ def initialize(names)
7
+ @names = names
8
+ end
9
+
10
+ def backup(dir)
11
+ Backup.call(names, dir)
12
+ end
13
+ end
14
+
15
+ class << self
16
+ def bind(names)
17
+ BoundStore.new(names)
18
+ end
19
+
20
+ def restore(metadata)
21
+ Restore.call(metadata)
22
+ end
23
+ end
24
+
25
+ class Backup
26
+ def self.call(names, dir)
27
+ new(names, dir).call
28
+ end
29
+
30
+ attr_reader :names, :dir
31
+ def initialize(names, dir)
32
+ @names = names
33
+ @dir = dir
34
+ end
35
+
36
+ def call
37
+ Cfg.shell.puts("backing up #{names} into #{dir}")
38
+
39
+ path = File.join(dir, "mysql.sql.gz")
40
+
41
+ Cfg.shell.run(<<~SH)
42
+ mysqldump \
43
+ --add-drop-database \
44
+ --databases #{names.join(" ")} \
45
+ | gzip > #{path}
46
+ SH
47
+
48
+ {
49
+ type: "mysql",
50
+ path: path,
51
+ databases: names
52
+ }
53
+ end
54
+ end
55
+
56
+ class Restore
57
+ def self.call(metadata)
58
+ new(metadata).call
59
+ end
60
+
61
+ attr_reader :metadata
62
+ def initialize(metadata)
63
+ @metadata = metadata
64
+ end
65
+
66
+ def call
67
+ dump_path = metadata.dig("path")
68
+ Cfg.shell.puts "restoring #{metadata.to_json}"
69
+ Cfg.shell.run("bash -ec 'zcat < #{dump_path} | mysql -uroot'")
70
+ end
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DevArchive
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "dev_archive/version"
4
+ require_relative "dev_archive/cfg"
5
+
6
+ module DevArchive
7
+ class Error < StandardError; end
8
+
9
+ DESCRIPTION = <<~TEXT.chomp
10
+ Save and restore snapshots of stateful services to a central archive. The
11
+ default action is to backup all databases for the current rails apps,
12
+ however, custom actions can easily be configured.
13
+
14
+ See https://github.com/petekinnecom/dev_archive for the full README.
15
+ TEXT
16
+
17
+ class << self
18
+ def configure
19
+ yield(Cfg.instance)
20
+ end
21
+ end
22
+ end
23
+
24
+ require_relative "dev_archive/cli"
data/lib/template.txt ADDED
@@ -0,0 +1,5 @@
1
+
2
+
3
+ # Follows same rules as a git commit message. First line is summary, followed by
4
+ # more detailed info. Set `export EDITOR="..."` to use a different editor for
5
+ # this message. (eg. `export EDITOR="code --wait"` to use VSCode)
data/script/install ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env bash
2
+
3
+ set -ex
4
+
5
+ gemname='dev_archive'
6
+
7
+ gem uninstall -Ix ${gemname}
8
+ gem build ${gemname}.gemspec
9
+ gemfile=${gemname}-"$(grep -oEi '\d+\.\d+\.\d+' lib/${gemname}/version.rb)".gem
10
+ gem install "${gemfile}"
11
+ rm "${gemfile}"
metadata ADDED
@@ -0,0 +1,88 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dev_archive
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Pete Kinnecom
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-04-08 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: commander
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '4.5'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '4.5'
27
+ description:
28
+ email:
29
+ - git@k7u7.com
30
+ executables:
31
+ - dev_archive
32
+ extensions: []
33
+ extra_rdoc_files: []
34
+ files:
35
+ - ".gitignore"
36
+ - ".rubocop.yml"
37
+ - ".ruby-version"
38
+ - CODE_OF_CONDUCT.md
39
+ - Gemfile
40
+ - Gemfile.lock
41
+ - LICENSE.txt
42
+ - README.md
43
+ - Rakefile
44
+ - bin/console
45
+ - bin/setup
46
+ - dev_archive.gemspec
47
+ - exe/dev_archive
48
+ - lib/dev_archive.rb
49
+ - lib/dev_archive/archives.rb
50
+ - lib/dev_archive/cfg.rb
51
+ - lib/dev_archive/cli.rb
52
+ - lib/dev_archive/default_configuration.rb
53
+ - lib/dev_archive/formatters.rb
54
+ - lib/dev_archive/repositories.rb
55
+ - lib/dev_archive/shell.rb
56
+ - lib/dev_archive/stores.rb
57
+ - lib/dev_archive/version.rb
58
+ - lib/template.txt
59
+ - script/install
60
+ homepage: https://github.com/petekinnecom/dev_archive
61
+ licenses:
62
+ - WTFPL2
63
+ metadata:
64
+ allowed_push_host: https://rubygems.org
65
+ homepage_uri: https://github.com/petekinnecom/dev_archive
66
+ source_code_uri: https://github.com/petekinnecom/dev_archive
67
+ post_install_message:
68
+ rdoc_options: []
69
+ require_paths:
70
+ - lib
71
+ required_ruby_version: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: 2.4.0
76
+ required_rubygems_version: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ version: '0'
81
+ requirements: []
82
+ rubygems_version: 3.3.4
83
+ signing_key:
84
+ specification_version: 4
85
+ summary: Save and restore snapshots of stateful services to a central archive. The
86
+ default action is to backup all databases for the current rails apps, however, custom
87
+ actions can easily be configured.
88
+ test_files: []