├── .github ├── dependabot.yml ├── release-drafter.yml └── workflows │ ├── ci.yml │ └── release-drafter.yml.dist ├── .gitignore ├── .kodiak.toml ├── .overcommit.yml ├── .prettierignore ├── .rubocop.yml ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── Gemfile ├── LICENSE.txt ├── README.md ├── Rakefile ├── bin ├── console └── setup ├── example.gemspec ├── exe └── example ├── lib ├── example.rb └── example │ ├── cli.rb │ ├── thor_ext.rb │ └── version.rb ├── rename_template.rb └── test ├── example_test.rb ├── support └── rg.rb └── test_helper.rb /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: bundler 4 | directory: "/" 5 | schedule: 6 | interval: monthly 7 | time: "16:00" 8 | timezone: America/Los_Angeles 9 | open-pull-requests-limit: 10 10 | labels: 11 | - "🏠 Housekeeping" 12 | - package-ecosystem: github-actions 13 | directory: "/" 14 | schedule: 15 | interval: monthly 16 | time: "16:00" 17 | timezone: America/Los_Angeles 18 | open-pull-requests-limit: 10 19 | labels: 20 | - "🏠 Housekeeping" 21 | -------------------------------------------------------------------------------- /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name-template: "$RESOLVED_VERSION" 2 | tag-template: "v$RESOLVED_VERSION" 3 | categories: 4 | - title: "⚠️ Breaking Changes" 5 | label: "⚠️ Breaking" 6 | - title: "✨ New Features" 7 | label: "✨ Feature" 8 | - title: "🐛 Bug Fixes" 9 | label: "🐛 Bug Fix" 10 | - title: "📚 Documentation" 11 | label: "📚 Docs" 12 | - title: "🏠 Housekeeping" 13 | label: "🏠 Housekeeping" 14 | version-resolver: 15 | minor: 16 | labels: 17 | - "⚠️ Breaking" 18 | - "✨ Feature" 19 | default: patch 20 | change-template: "- $TITLE (#$NUMBER) @$AUTHOR" 21 | no-changes-template: "- No changes" 22 | template: | 23 | $CHANGES 24 | 25 | **Full Changelog:** https://github.com/$OWNER/$REPOSITORY/compare/$PREVIOUS_TAG...v$RESOLVED_VERSION 26 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | pull_request: 4 | push: 5 | branches: 6 | - main 7 | jobs: 8 | rubocop: 9 | name: "Rubocop" 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v4 13 | - uses: ruby/setup-ruby@v1 14 | with: 15 | ruby-version: "ruby" 16 | bundler-cache: true 17 | - run: bundle exec rubocop 18 | test: 19 | name: "Test / Ruby ${{ matrix.ruby }}" 20 | runs-on: ubuntu-latest 21 | strategy: 22 | matrix: 23 | ruby: ["3.1", "3.2", "3.3", "3.4", "head"] 24 | steps: 25 | - uses: actions/checkout@v4 26 | - uses: ruby/setup-ruby@v1 27 | with: 28 | ruby-version: ${{ matrix.ruby }} 29 | bundler-cache: true 30 | - run: bundle exec rake test 31 | -------------------------------------------------------------------------------- /.github/workflows/release-drafter.yml.dist: -------------------------------------------------------------------------------- 1 | name: Release Drafter 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | permissions: 9 | contents: write 10 | pull-requests: read 11 | 12 | jobs: 13 | update_release_draft: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: release-drafter/release-drafter@v6 17 | env: 18 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /_yardoc/ 4 | /coverage/ 5 | /doc/ 6 | /pkg/ 7 | /site/ 8 | /spec/reports/ 9 | /tmp/ 10 | /Gemfile.lock 11 | -------------------------------------------------------------------------------- /.kodiak.toml: -------------------------------------------------------------------------------- 1 | # .kodiak.toml 2 | # Minimal config. version is the only required field. 3 | version = 1 4 | 5 | [merge.automerge_dependencies] 6 | # auto merge all PRs opened by "dependabot" that are "minor" or "patch" version upgrades. "major" version upgrades will be ignored. 7 | versions = ["minor", "patch"] 8 | usernames = ["dependabot"] 9 | 10 | # if using `update.always`, add dependabot to `update.ignore_usernames` to allow 11 | # dependabot to update and close stale dependency upgrades. 12 | [update] 13 | ignored_usernames = ["dependabot"] 14 | -------------------------------------------------------------------------------- /.overcommit.yml: -------------------------------------------------------------------------------- 1 | # Overcommit hooks run automatically on certain git operations, like "git commit". 2 | # For a complete list of options that you can use to customize hooks, see: 3 | # https://github.com/sds/overcommit 4 | 5 | gemfile: false 6 | verify_signatures: false 7 | 8 | PreCommit: 9 | BundleCheck: 10 | enabled: true 11 | 12 | FixMe: 13 | enabled: true 14 | keywords: ["FIXME"] 15 | exclude: 16 | - .overcommit.yml 17 | 18 | LocalPathsInGemfile: 19 | enabled: true 20 | 21 | RuboCop: 22 | enabled: true 23 | required_executable: bundle 24 | command: ["bundle", "exec", "rubocop"] 25 | on_warn: fail 26 | 27 | YamlSyntax: 28 | enabled: true 29 | 30 | PostCheckout: 31 | ALL: 32 | quiet: true 33 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | /CODE_OF_CONDUCT.md 2 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | require: 2 | - rubocop-minitest 3 | - rubocop-packaging 4 | - rubocop-performance 5 | - rubocop-rake 6 | 7 | AllCops: 8 | DisplayCopNames: true 9 | DisplayStyleGuide: true 10 | NewCops: enable 11 | TargetRubyVersion: 3.1 12 | Exclude: 13 | - "tmp/**/*" 14 | - "vendor/**/*" 15 | 16 | Layout/FirstArrayElementIndentation: 17 | EnforcedStyle: consistent 18 | 19 | Layout/FirstArrayElementLineBreak: 20 | Enabled: true 21 | 22 | Layout/FirstHashElementLineBreak: 23 | Enabled: true 24 | 25 | Layout/FirstMethodArgumentLineBreak: 26 | Enabled: true 27 | 28 | Layout/HashAlignment: 29 | EnforcedColonStyle: 30 | - table 31 | - key 32 | EnforcedHashRocketStyle: 33 | - table 34 | - key 35 | 36 | Layout/MultilineArrayLineBreaks: 37 | Enabled: true 38 | 39 | Layout/MultilineHashKeyLineBreaks: 40 | Enabled: true 41 | 42 | Layout/MultilineMethodArgumentLineBreaks: 43 | Enabled: true 44 | 45 | Layout/MultilineMethodCallIndentation: 46 | EnforcedStyle: indented 47 | 48 | Layout/SpaceAroundEqualsInParameterDefault: 49 | EnforcedStyle: no_space 50 | 51 | Metrics/AbcSize: 52 | Max: 20 53 | Exclude: 54 | - "test/**/*" 55 | 56 | Metrics/BlockLength: 57 | Exclude: 58 | - "*.gemspec" 59 | - "Rakefile" 60 | 61 | Metrics/ClassLength: 62 | Exclude: 63 | - "test/**/*" 64 | 65 | Metrics/MethodLength: 66 | Max: 18 67 | Exclude: 68 | - "test/**/*" 69 | 70 | Metrics/ParameterLists: 71 | Max: 6 72 | 73 | Minitest/EmptyLineBeforeAssertionMethods: 74 | Enabled: false 75 | 76 | Naming/MemoizedInstanceVariableName: 77 | Enabled: false 78 | 79 | Naming/VariableNumber: 80 | Enabled: false 81 | 82 | Rake/Desc: 83 | Enabled: false 84 | 85 | Style/BarePercentLiterals: 86 | EnforcedStyle: percent_q 87 | 88 | Style/Documentation: 89 | Enabled: false 90 | 91 | Style/DoubleNegation: 92 | Enabled: false 93 | 94 | Style/EmptyMethod: 95 | Enabled: false 96 | 97 | Style/NumericPredicate: 98 | Enabled: false 99 | 100 | Style/StringLiterals: 101 | EnforcedStyle: double_quotes 102 | 103 | Style/TrivialAccessors: 104 | AllowPredicates: true 105 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Release notes for this project are kept here: https://github.com/mattbrictson/gem/releases 2 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 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 owner@example.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. 85 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | source "https://rubygems.org" 4 | gemspec 5 | 6 | gem "minitest", "~> 5.11" 7 | gem "minitest-rg", "~> 5.3" 8 | gem "rake", "~> 13.0" 9 | gem "rubocop", "1.75.8" 10 | gem "rubocop-minitest", "0.38.1" 11 | gem "rubocop-packaging", "0.6.0" 12 | gem "rubocop-performance", "1.25.0" 13 | gem "rubocop-rake", "0.7.1" 14 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2025 Example Owner 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. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gem template 2 | 3 | This is a GitHub template for creating Ruby gems. Press [**Use this template**](https://github.com/mattbrictson/gem/generate) to generate a project from this template. In the generated project, run this script to rename the gem to meet your needs: 4 | 5 | ``` 6 | ruby rename_template.rb 7 | ``` 8 | 9 | Note that to get the full benefits of the script, you will need the [gh](https://github.com/cli/cli) command installed. 10 | 11 | This template is based on `bundle gem` with some notable improvements: 12 | 13 | - GitHub Actions configuration 14 | - Minitest, with minitest-rg for nicely formatted test output 15 | - Rubocop with a good set of configuration 16 | - CLI scaffolding, built on top of Thor (optional; for more background, read [Fixing Thor’s CLI Quirks](https://mattbrictson.com/blog/fixing-thor-cli-behavior)) 17 | - [release-drafter](https://github.com/apps/release-drafter) GitHub Action for automating release notes 18 | - A `rake bump` task to keep your Ruby and Bundler dependencies up to date 19 | - A nice README with badges ready to go (see below) 20 | 21 | --- 22 | 23 | 24 | 25 | # example 26 | 27 | [![Gem Version](https://img.shields.io/gem/v/replace_with_gem_name)](https://rubygems.org/gems/replace_with_gem_name) 28 | [![Gem Downloads](https://img.shields.io/gem/dt/replace_with_gem_name)](https://www.ruby-toolbox.com/projects/replace_with_gem_name) 29 | [![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/mattbrictson/gem/ci.yml)](https://github.com/mattbrictson/gem/actions/workflows/ci.yml) 30 | [![Code Climate maintainability](https://img.shields.io/codeclimate/maintainability/mattbrictson/gem)](https://codeclimate.com/github/mattbrictson/gem) 31 | 32 | TODO: Description of this gem goes here. 33 | 34 | --- 35 | 36 | - [Quick start](#quick-start) 37 | - [Support](#support) 38 | - [License](#license) 39 | - [Code of conduct](#code-of-conduct) 40 | - [Contribution guide](#contribution-guide) 41 | 42 | ## Quick start 43 | 44 | ``` 45 | gem install example 46 | ``` 47 | 48 | ```ruby 49 | require "example" 50 | ``` 51 | 52 | ## Support 53 | 54 | If you want to report a bug, or have ideas, feedback or questions about the gem, [let me know via GitHub issues](https://github.com/mattbrictson/gem/issues/new) and I will do my best to provide a helpful answer. Happy hacking! 55 | 56 | ## License 57 | 58 | The gem is available as open source under the terms of the [MIT License](LICENSE.txt). 59 | 60 | ## Code of conduct 61 | 62 | Everyone interacting in this project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](CODE_OF_CONDUCT.md). 63 | 64 | ## Contribution guide 65 | 66 | Pull requests are welcome! 67 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "bundler/gem_tasks" 4 | require "rake/testtask" 5 | require "rubocop/rake_task" 6 | 7 | Rake::TestTask.new(:test) do |t| 8 | t.libs << "test" 9 | t.libs << "lib" 10 | t.test_files = FileList["test/**/*_test.rb"] 11 | end 12 | 13 | RuboCop::RakeTask.new 14 | 15 | task default: %i[test rubocop] 16 | 17 | # == "rake release" enhancements ============================================== 18 | 19 | Rake::Task["release"].enhance do 20 | puts "Don't forget to publish the release on GitHub!" 21 | system "open https://github.com/mattbrictson/gem/releases" 22 | end 23 | 24 | task :disable_overcommit do 25 | ENV["OVERCOMMIT_DISABLE"] = "1" 26 | end 27 | 28 | Rake::Task[:build].enhance [:disable_overcommit] 29 | 30 | task :verify_gemspec_files do 31 | git_files = `git ls-files -z`.split("\x0") 32 | gemspec_files = Gem::Specification.load("example.gemspec").files.sort 33 | ignored_by_git = gemspec_files - git_files 34 | next if ignored_by_git.empty? 35 | 36 | raise <<~ERROR 37 | 38 | The `spec.files` specified in example.gemspec include the following files 39 | that are being ignored by git. Did you forget to add them to the repo? If 40 | not, you may need to delete these files or modify the gemspec to ensure 41 | that they are not included in the gem by mistake: 42 | 43 | #{ignored_by_git.join("\n").gsub(/^/, ' ')} 44 | 45 | ERROR 46 | end 47 | 48 | Rake::Task[:build].enhance [:verify_gemspec_files] 49 | 50 | # == "rake bump" tasks ======================================================== 51 | 52 | task bump: %w[bump:bundler bump:ruby bump:year] 53 | 54 | namespace :bump do 55 | task :bundler do 56 | sh "bundle update --bundler" 57 | end 58 | 59 | task :ruby do 60 | replace_in_file "example.gemspec", /ruby_version = .*">= (.*)"/ => RubyVersions.lowest 61 | replace_in_file ".rubocop.yml", /TargetRubyVersion: (.*)/ => RubyVersions.lowest 62 | replace_in_file ".github/workflows/ci.yml", /ruby: (\[.+\])/ => RubyVersions.all.inspect 63 | end 64 | 65 | task :year do 66 | replace_in_file "LICENSE.txt", /\(c\) (\d+)/ => Date.today.year.to_s 67 | end 68 | end 69 | 70 | require "date" 71 | require "open-uri" 72 | require "yaml" 73 | 74 | def replace_in_file(path, replacements) 75 | contents = File.read(path) 76 | orig_contents = contents.dup 77 | replacements.each do |regexp, text| 78 | raise "Can't find #{regexp} in #{path}" unless regexp.match?(contents) 79 | 80 | contents.gsub!(regexp) do |match| 81 | match[regexp, 1] = text 82 | match 83 | end 84 | end 85 | File.write(path, contents) if contents != orig_contents 86 | end 87 | 88 | module RubyVersions 89 | class << self 90 | def lowest 91 | all.first 92 | end 93 | 94 | def all 95 | patches = versions.values_at(:stable, :security_maintenance).compact.flatten 96 | sorted_minor_versions = patches.map { |p| p[/\d+\.\d+/] }.sort_by(&:to_f) 97 | [*sorted_minor_versions, "head"] 98 | end 99 | 100 | private 101 | 102 | def versions 103 | @_versions ||= begin 104 | yaml = URI.open("https://raw.githubusercontent.com/ruby/www.ruby-lang.org/HEAD/_data/downloads.yml") 105 | YAML.safe_load(yaml, symbolize_names: true) 106 | end 107 | end 108 | end 109 | end 110 | -------------------------------------------------------------------------------- /bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | require "bundler/setup" 5 | require "example" 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__) 16 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | IFS=$'\n\t' 4 | set -vx 5 | 6 | which overcommit > /dev/null 2>&1 && overcommit --install 7 | bundle install 8 | 9 | # Do any other automated setup that you need to do here 10 | -------------------------------------------------------------------------------- /example.gemspec: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative "lib/example/version" 4 | 5 | Gem::Specification.new do |spec| 6 | spec.name = "example" 7 | spec.version = Example::VERSION 8 | spec.authors = ["Example Owner"] 9 | spec.email = ["owner@example.com"] 10 | 11 | spec.summary = "" 12 | spec.homepage = "https://github.com/mattbrictson/gem" 13 | spec.license = "MIT" 14 | spec.required_ruby_version = ">= 3.1" 15 | 16 | spec.metadata = { 17 | "bug_tracker_uri" => "https://github.com/mattbrictson/gem/issues", 18 | "changelog_uri" => "https://github.com/mattbrictson/gem/releases", 19 | "source_code_uri" => "https://github.com/mattbrictson/gem", 20 | "homepage_uri" => spec.homepage, 21 | "rubygems_mfa_required" => "true" 22 | } 23 | 24 | # Specify which files should be added to the gem when it is released. 25 | spec.files = Dir.glob(%w[LICENSE.txt README.md {exe,lib}/**/*]).reject { |f| File.directory?(f) } 26 | spec.bindir = "exe" 27 | spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } 28 | spec.require_paths = ["lib"] 29 | 30 | # Runtime dependencies 31 | spec.add_dependency "thor", "~> 1.2" 32 | end 33 | -------------------------------------------------------------------------------- /exe/example: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | require "example" 5 | Example::CLI.start(ARGV) 6 | -------------------------------------------------------------------------------- /lib/example.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Example 4 | autoload :CLI, "example/cli" 5 | autoload :VERSION, "example/version" 6 | autoload :ThorExt, "example/thor_ext" 7 | end 8 | -------------------------------------------------------------------------------- /lib/example/cli.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "thor" 4 | 5 | module Example 6 | class CLI < Thor 7 | extend ThorExt::Start 8 | 9 | map %w[-v --version] => "version" 10 | 11 | desc "version", "Display example version", hide: true 12 | def version 13 | say "example/#{VERSION} #{RUBY_DESCRIPTION}" 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /lib/example/thor_ext.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Example 4 | module ThorExt 5 | # Configures Thor to behave more like a typical CLI, with better help and error handling. 6 | # 7 | # - Passing -h or --help to a command will show help for that command. 8 | # - Unrecognized options will be treated as errors (instead of being silently ignored). 9 | # - Error messages will be printed in red to stderr, without stack trace. 10 | # - Full stack traces can be enabled by setting the VERBOSE environment variable. 11 | # - Errors will cause Thor to exit with a non-zero status. 12 | # 13 | # To take advantage of this behavior, your CLI should subclass Thor and extend this module. 14 | # 15 | # class CLI < Thor 16 | # extend ThorExt::Start 17 | # end 18 | # 19 | # Start your CLI with: 20 | # 21 | # CLI.start 22 | # 23 | # In tests, prevent Kernel.exit from being called when an error occurs, like this: 24 | # 25 | # CLI.start(args, exit_on_failure: false) 26 | # 27 | module Start 28 | def self.extended(base) 29 | super 30 | base.check_unknown_options! 31 | end 32 | 33 | def start(given_args=ARGV, config={}) 34 | config[:shell] ||= Thor::Base.shell.new 35 | handle_help_switches(given_args) do |args| 36 | dispatch(nil, args, nil, config) 37 | end 38 | rescue StandardError => e 39 | handle_exception_on_start(e, config) 40 | end 41 | 42 | private 43 | 44 | def handle_help_switches(given_args) 45 | yield(given_args.dup) 46 | rescue Thor::UnknownArgumentError => e 47 | retry_with_args = [] 48 | 49 | if given_args.first == "help" 50 | retry_with_args = ["help"] if given_args.length > 1 51 | elsif e.unknown.intersect?(%w[-h --help]) 52 | retry_with_args = ["help", (given_args - e.unknown).first] 53 | end 54 | raise unless retry_with_args.any? 55 | 56 | yield(retry_with_args) 57 | end 58 | 59 | def handle_exception_on_start(error, config) 60 | return if error.is_a?(Errno::EPIPE) 61 | raise if ENV["VERBOSE"] || !config.fetch(:exit_on_failure, true) 62 | 63 | message = error.message.to_s 64 | message.prepend("[#{error.class}] ") if message.empty? || !error.is_a?(Thor::Error) 65 | 66 | config[:shell]&.say_error(message, :red) 67 | exit(false) 68 | end 69 | end 70 | end 71 | end 72 | -------------------------------------------------------------------------------- /lib/example/version.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module Example 4 | VERSION = "0.1.0" 5 | end 6 | -------------------------------------------------------------------------------- /rename_template.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | require "bundler/inline" 5 | require "fileutils" 6 | require "io/console" 7 | require "open3" 8 | require "shellwords" 9 | 10 | def main # rubocop:disable Metrics/AbcSize, Metrics/MethodLength 11 | assert_git_repo! 12 | git_meta = read_git_data 13 | 14 | gem_name = ask("Gem name?", default: git_meta[:origin_repo_name]) 15 | gem_summary = ask("Gem summary (< 60 chars)?", default: "") 16 | author_email = ask("Author email?", default: git_meta[:user_email]) 17 | author_name = ask("Author name?", default: git_meta[:user_name]) 18 | github_repo = ask("GitHub repository?", default: git_meta[:origin_repo_path]) 19 | exe = ask_yes_or_no("Include an executable (CLI) in this gem?", default: "N") 20 | 21 | created_labels = 22 | if gh_present? 23 | puts 24 | puts "I would like to use the `gh` executable to create labels in your repo." 25 | puts "These labels will be used to generate nice-looking release notes." 26 | puts 27 | if ask_yes_or_no("Create GitHub labels using `gh`?", default: "Y") 28 | create_labels(github_repo) 29 | true 30 | end 31 | end 32 | 33 | replace_in_file(".github/dependabot.yml", /\s+labels:\n\s+-.*$/ => "") unless created_labels 34 | 35 | git "mv", ".github/workflows/release-drafter.yml.dist", ".github/workflows/release-drafter.yml" 36 | 37 | FileUtils.mkdir_p "lib/#{as_path(gem_name)}" 38 | FileUtils.mkdir_p "test/#{as_path(gem_name)}" 39 | 40 | ensure_executable "bin/console" 41 | ensure_executable "bin/setup" 42 | 43 | if exe 44 | replace_in_file "exe/example", 45 | "example" => as_path(gem_name), 46 | "Example" => as_module(gem_name) 47 | 48 | git "mv", "exe/example", "exe/#{gem_name}" 49 | ensure_executable "exe/#{gem_name}" 50 | 51 | replace_in_file "lib/example/cli.rb", 52 | "example" => as_path(gem_name), 53 | "Example" => as_module(gem_name) 54 | 55 | git "mv", "lib/example/cli.rb", "lib/#{as_path(gem_name)}/cli.rb" 56 | reindent_module "lib/#{as_path(gem_name)}/cli.rb" 57 | 58 | replace_in_file "lib/example/thor_ext.rb", "Example" => as_module(gem_name) 59 | git "mv", "lib/example/thor_ext.rb", "lib/#{as_path(gem_name)}/thor_ext.rb" 60 | reindent_module "lib/#{as_path(gem_name)}/thor_ext.rb" 61 | else 62 | git "rm", "exe/example", "lib/example/cli.rb", "lib/example/thor_ext.rb" 63 | replace_in_file "example.gemspec", 'spec.add_dependency "thor"' => '# spec.add_dependency "thor"' 64 | remove_line "lib/example.rb", /autoload :ThorExt/ 65 | remove_line "lib/example.rb", /autoload :CLI/ 66 | end 67 | 68 | replace_in_file "LICENSE.txt", 69 | "Example Owner" => author_name 70 | 71 | replace_in_file "Rakefile", 72 | "example.gemspec" => "#{gem_name}.gemspec", 73 | "mattbrictson/gem" => github_repo 74 | 75 | replace_in_file "README.md", 76 | "mattbrictson/gem" => github_repo, 77 | 'require "example"' => %Q(require "#{as_path(gem_name)}"), 78 | "example" => gem_name, 79 | "replace_with_gem_name" => gem_name, 80 | /\A.*\n+/m => "" 81 | 82 | replace_in_file "CHANGELOG.md", 83 | "mattbrictson/gem" => github_repo 84 | 85 | replace_in_file "CODE_OF_CONDUCT.md", 86 | "owner@example.com" => author_email 87 | 88 | replace_in_file "bin/console", 89 | 'require "example"' => %Q(require "#{as_path(gem_name)}") 90 | 91 | replace_in_file "example.gemspec", 92 | "mattbrictson/gem" => github_repo, 93 | '"Example Owner"' => author_name.inspect, 94 | '"owner@example.com"' => author_email.inspect, 95 | '"example"' => gem_name.inspect, 96 | "example/version" => "#{as_path(gem_name)}/version", 97 | "Example::VERSION" => "#{as_module(gem_name)}::VERSION", 98 | /summary\s*=\s*("")/ => gem_summary.inspect 99 | 100 | git "mv", "example.gemspec", "#{gem_name}.gemspec" 101 | 102 | replace_in_file "lib/example.rb", 103 | "example" => as_path(gem_name), 104 | "Example" => as_module(gem_name) 105 | 106 | git "mv", "lib/example.rb", "lib/#{as_path(gem_name)}.rb" 107 | reindent_module "lib/#{as_path(gem_name)}.rb" 108 | 109 | replace_in_file "lib/example/version.rb", 110 | "Example" => as_module(gem_name) 111 | 112 | git "mv", "lib/example/version.rb", "lib/#{as_path(gem_name)}/version.rb" 113 | reindent_module "lib/#{as_path(gem_name)}/version.rb" 114 | 115 | replace_in_file "test/example_test.rb", 116 | "Example" => as_module(gem_name) 117 | 118 | git "mv", "test/example_test.rb", "test/#{as_path(gem_name)}_test.rb" 119 | reindent_module "test/#{as_path(gem_name)}_test.rb" 120 | 121 | replace_in_file "test/test_helper.rb", 122 | 'require "example"' => %Q(require "#{as_path(gem_name)}") 123 | 124 | git "rm", "rename_template.rb" 125 | Dir.unlink("lib/example") if Dir.empty?("lib/example") 126 | 127 | puts <<~MESSAGE 128 | 129 | All set! 130 | 131 | The project has been renamed from "example" to "#{gem_name}". 132 | Review the changes and then run: 133 | 134 | git commit && git push 135 | 136 | MESSAGE 137 | end 138 | 139 | def assert_git_repo! 140 | return if File.file?(".git/config") 141 | 142 | warn("This doesn't appear to be a git repo. Can't continue. :(") 143 | exit(1) 144 | end 145 | 146 | def git(*args) 147 | sh! "git", *args 148 | end 149 | 150 | def ensure_executable(path) 151 | return if File.executable?(path) 152 | 153 | FileUtils.chmod 0o755, path 154 | git "add", path 155 | end 156 | 157 | def sh!(*args) 158 | puts ">>>> #{args.join(' ')}" 159 | stdout, status = Open3.capture2(*args) 160 | raise("Failed to execute: #{args.join(' ')}") unless status.success? 161 | 162 | stdout 163 | end 164 | 165 | def remove_line(file, pattern) 166 | text = File.read(file) 167 | text = text.lines.filter.grep_v(pattern).join 168 | File.write(file, text) 169 | git "add", file 170 | end 171 | 172 | def ask(question, default: nil, echo: true) 173 | prompt = "#{question} " 174 | prompt << "[#{default}] " unless default.nil? 175 | print prompt 176 | answer = if echo 177 | $stdin.gets.chomp 178 | else 179 | $stdin.noecho(&:gets).tap { $stdout.print "\n" }.chomp 180 | end 181 | answer.to_s.strip.empty? ? default : answer 182 | end 183 | 184 | def ask_yes_or_no(question, default: "N") 185 | default = default == "Y" ? "Y/n" : "y/N" 186 | answer = ask(question, default:) 187 | 188 | answer != "y/N" && answer.match?(/^y/i) 189 | end 190 | 191 | def read_git_data 192 | return {} unless git("remote", "-v").match?(/^origin/) 193 | 194 | origin_url = git("remote", "get-url", "origin").chomp 195 | origin_repo_path = origin_url[%r{[:/]([^/]+/[^/]+?)(?:\.git)?$}, 1] 196 | 197 | { 198 | origin_repo_name: origin_repo_path&.split("/")&.last, 199 | origin_repo_path:, 200 | user_email: git("config", "user.email").chomp, 201 | user_name: git("config", "user.name").chomp 202 | } 203 | end 204 | 205 | def replace_in_file(path, replacements) 206 | contents = File.read(path) 207 | replacements.each do |regexp, text| 208 | contents.gsub!(regexp) do |match| 209 | next text if Regexp.last_match(1).nil? 210 | 211 | match[regexp, 1] = text 212 | match 213 | end 214 | end 215 | 216 | File.write(path, contents) 217 | git "add", path 218 | end 219 | 220 | def as_path(gem_name) 221 | gem_name.tr("-", "/") 222 | end 223 | 224 | def as_module(gem_name) 225 | parts = gem_name.split("-") 226 | parts.map do |part| 227 | part.gsub(/^[a-z]|_[a-z]/) { |str| str[-1].upcase } 228 | end.join("::") 229 | end 230 | 231 | def reindent_module(path) 232 | preamble, contents = File.read(path).match(/\A(.*?)(^(?:module|class).*\z)/m)&.captures 233 | namespace_mod = contents && contents[/(?:module|class) (\S+)/, 1] 234 | return unless namespace_mod&.include?("::") 235 | 236 | contents.sub!(namespace_mod, namespace_mod.split("::").last) 237 | namespace_mod.split("::")[0...-1].reverse_each do |mod| 238 | contents = "module #{mod}\n#{contents.gsub(/^/, ' ')}end\n" 239 | end 240 | 241 | File.write(path, [preamble, contents].join) 242 | git "add", path 243 | end 244 | 245 | def gh_present? 246 | system "gh label clone -h > /dev/null 2>&1" 247 | rescue StandardError 248 | false 249 | end 250 | 251 | def create_labels(github_repo) 252 | system "gh label clone mattbrictson/gem --repo #{github_repo.shellescape}" 253 | end 254 | 255 | main if $PROGRAM_NAME == __FILE__ 256 | -------------------------------------------------------------------------------- /test/example_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "test_helper" 4 | 5 | class ExampleTest < Minitest::Test 6 | def test_that_it_has_a_version_number 7 | refute_nil ::Example::VERSION 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /test/support/rg.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # Enable color test output 4 | require "minitest/rg" 5 | -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | $LOAD_PATH.unshift File.expand_path("../lib", __dir__) 4 | require "example" 5 | 6 | require "minitest/autorun" 7 | Dir[File.expand_path("support/**/*.rb", __dir__)].each { |rb| require(rb) } 8 | --------------------------------------------------------------------------------