Repository: searls/todo_or_die Branch: master Commit: 9a0436a6bfa2 Files: 17 Total size: 20.1 KB Directory structure: gitextract_7mtzd5p0/ ├── .claude/ │ └── settings.json ├── .github/ │ └── workflows/ │ └── main.yml ├── .gitignore ├── .tldr.yml ├── CHANGELOG.md ├── Gemfile ├── LICENSE.txt ├── README.md ├── Rakefile ├── bin/ │ ├── console │ └── setup ├── lib/ │ ├── todo_or_die/ │ │ ├── overdue_error.rb │ │ └── version.rb │ └── todo_or_die.rb ├── test/ │ ├── helper.rb │ └── todo_or_die_test.rb └── todo_or_die.gemspec ================================================ FILE CONTENTS ================================================ ================================================ FILE: .claude/settings.json ================================================ { "hooks": { "PostToolUse": [ { "matcher": "Edit|MultiEdit|Write", "hooks": [ { "type": "command", "command": "bundle exec tldr --timeout 0.1 --exit-0-on-timeout --exit-2-on-failure" } ] } ] } } ================================================ FILE: .github/workflows/main.yml ================================================ name: Ruby on: push: branches: - master pull_request: jobs: build: runs-on: ubuntu-latest name: Ruby ${{ matrix.ruby }} strategy: matrix: ruby: - '3.2.1' steps: - uses: actions/checkout@v3 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby }} bundler-cache: true - name: Run the default task run: bundle exec rake ================================================ FILE: .gitignore ================================================ /.bundle/ /.yardoc /_yardoc/ /coverage/ /doc/ /pkg/ /spec/reports/ /tmp/ ================================================ FILE: .tldr.yml ================================================ parallel: false ================================================ FILE: CHANGELOG.md ================================================ # Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [0.1.1] - 2022-07-01 - Fix `warn_by` [#16](https://github.com/searls/todo_or_die/pull/16) ## [0.1.0] - 2022-06-27 - Add `warn_by` option [#14](https://github.com/searls/todo_or_die/pull/14) ## [0.0.3] - 2019-11-26 ### Added - Boolean-returning conditionals or callables (Proc, Block, Lambda) can be passed to the new `if` argument. `if` can be used instead of or in conjunction with the `by` argument to die on a specific date OR when a specific condition becomes true. ### Changed - Date strings can now be parsed parsed internally without calling `Time` or `Date` classes explicitely. ## [0.0.2] - 2019-02-15 ### Changed - Exclude this gem's backtrace location from exceptions thrown to make it easier to find TODOs. ## [0.0.1] - 2019-01-01 [Unreleased]: https://github.com/olivierlacan/keep-a-changelog/compare/v0.0.3...HEAD [0.0.3]: https://github.com/olivierlacan/keep-a-changelog/compare/v0.0.2...v0.0.3 [0.0.2]: https://github.com/olivierlacan/keep-a-changelog/compare/v0.0.1...v0.0.2 [0.0.1]: https://github.com/olivierlacan/keep-a-changelog/releases/tag/v0.0.1 ================================================ FILE: Gemfile ================================================ source "https://rubygems.org" git_source(:github) { |repo_name| "https://github.com/#{repo_name}" } # Specify your gem's dependencies in todo_or_die.gemspec gemspec gem "rake" gem "standard" gem "timecop" gem "tldr" ================================================ FILE: LICENSE.txt ================================================ Copyright (c) 2019 Justin Searls Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # TODO or Die! TODO or Die NES cart ## Usage Stick this in your Gemfile and bundle it: ```ruby gem "todo_or_die" ``` Once required, you can mark TODOs for yourself anywhere you like: ```ruby TodoOrDie("Update after APIv2 goes live", by: Date.civil(2019, 2, 4)) ``` To understand why you would ever call a method to write a comment, read on. ### The awful way you used to procrastinate In the Bad Old Days™, if you had a bit of code you knew you needed to change later, you might leave yourself a code comment to remind yourself to change it. For example, here's the real world code comment that inspired this gem: ``` ruby class UsersController < ApiController # TODO: remember to delete after JS app has propagated def show redirect_to root_path end end ``` This was bad. The comment did nothing to remind myself or anyone else to actually delete the code. Because no one was working on this part of the system for a while, the _continued existence of the redirect_ eventually resulted in an actual support incident (long story). ### The cool new way you put off coding now So I did what any programmer would do in the face of an intractable social problem: I wrote code in the vain hope of solving things without needing to talk to anyone. And now this gem exists. To use it, try replacing one of your TODO comments with something like this: ``` ruby class UsersController < ApiController TodoOrDie("delete after JS app has propagated", by: "2019-02-04") def show redirect_to root_path end end ``` Nothing will happen at all until February 4th, at which point the gem will raise an error whenever this class is loaded until someone deals with it. You may also pass a condition, either as a callable (e.g. proc/lambda/method) or a boolean test: ``` ruby class User < ApplicationRecord TodoOrDie("delete after someone wins", if: User.count > 1000000) def is_one_millionth_user? id == 1000000 end end ``` You can also pass both `by` and `if` (where both must be met for an error to be raised) or, I guess, neither (where an error will be raised as soon as `TodoOrDie` is invoked). ### What kind of error? It depends on whether you're using [Rails](https://rubyonrails.org) or not. #### When you're writing Real Ruby If you're not using Rails (i.e. `defined?(Rails)` is false), then the gem will raise a `TodoOrDie::OverdueError` whenever a TODO is overdue. The message looks like this: ``` TODO: "Visit Wisconsin" came due on 2016-11-09. Do it! ``` #### When `Rails` is a thing If TodoOrDie sees that `Rails` is defined, it'll assume you probably don't want this tool to run outside development and test, so it'll log the error message to `Rails.logger.warn` in production (while still raising the error in development and test). ### Wait, won't sprinkling time bombs throughout my app ruin my weekend? Sure will! It's "TODO or Die", not "TODO and Remember to Pace Yourself". Still, someone will probably get mad if you break production because you forgot to follow through on removing an A/B test, so I'd [strongly recommend you read what the default hook actually does](lib/todo_or_die.rb#L8-L16) before this gem leads to you losing your job. (Speaking of, please note the lack of any warranty in `todo_or_die`'s [license](LICENSE.txt).) To appease your boss, you may customize the gem's behavior by passing in your own `call`'able lambda/proc/dingus like this: ```ruby TodoOrDie.config( die: ->(message, due_at) { if message.include?("Karen") raise "Hey Karen your code's broke" end } ) ``` Now, any `TodoOrDie()` invocations in your codebase (other than Karen's) will be ignored. (You can restore the default hook with `TodoOrDie.reset`). ## When is this useful? This gem may come in handy whenever you know the code _will_ need to change, but it can't be changed just yet, and you lack some other reliable means of ensuring yourself (or your team) will actually follow through on making the change later. This is a good time to recall [LeBlanc's Law](https://www.quora.com/What-resources-could-I-read-about-Leblancs-law), which states that `Later == Never`. Countless proofs of this theorem have been reproduced by software teams around the world. Some common examples: * A feature flag was added to the app a long time ago, but the old code path is still present, even after the flag had been enabled for everyone. Except now there's also a useless `TODO: delete` comment to keep it company * A failing test was blocking the build and someone felt an urgent pressure to deploy the app anyway. So, rather than fix the test, Bill commented it out "for now" * You're a real funny guy and you think it'd be hilarious to make a bunch of Aaron's tests start failing on Christmas morning ## Pro-tip Cute Rails date helpers are awesome, but don't think you're going to be able to do this and actually accomplish anything: ```ruby TodoOrDie("Update after APIv2 goes live", 2.weeks.from_now) ``` It will never be two weeks from now. ================================================ FILE: Rakefile ================================================ require "bundler/gem_tasks" require "standard/rake" require "tldr/rake" task default: [:tldr, "standard:fix"] ================================================ FILE: bin/console ================================================ #!/usr/bin/env ruby require "bundler/setup" require "todo_or_die" # You can add fixtures and/or initialization code here to make experimenting # with your gem easier. You can also use a different console, if you like. # (If you use this, don't forget to add pry to your Gemfile!) # require "pry" # Pry.start require "irb" IRB.start(__FILE__) ================================================ FILE: bin/setup ================================================ #!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' set -vx bundle install # Do any other automated setup that you need to do here ================================================ FILE: lib/todo_or_die/overdue_error.rb ================================================ module TodoOrDie class OverdueTodo < StandardError end end ================================================ FILE: lib/todo_or_die/version.rb ================================================ module TodoOrDie VERSION = "0.1.1" end ================================================ FILE: lib/todo_or_die.rb ================================================ require "time" require "todo_or_die/version" require "todo_or_die/overdue_error" # The namespace module TodoOrDie DEFAULT_CONFIG = { die: ->(message, due_at, condition) { error_message = [ "TODO: \"#{message}\"", (" came due on #{due_at.strftime("%Y-%m-%d")}" if due_at), (" and" if due_at && condition), (" has met the conditions to be acted upon" if condition), ". Do it!" ].compact.join("") if defined?(Rails) && Rails.env.production? Rails.logger.warn(error_message) else raise TodoOrDie::OverdueTodo, error_message, TodoOrDie.__clean_backtrace(caller) end }, warn: lambda { |message, due_at, warn_at, condition| error_message = [ "TODO: \"#{message}\"", (" is due on #{due_at.strftime("%Y-%m-%d")}" if due_at), (" and" if warn_at && condition), (" has met the conditions to be acted upon" if condition), ". Don't forget!" ].compact.join("") puts error_message Rails.logger.warn(error_message) if defined?(Rails) } }.freeze def self.config(options = {}) @config ||= reset @config.merge!(options) end def self.reset @config = DEFAULT_CONFIG.dup end FILE_PATH_REGEX = Regexp.new(Regexp.quote(__dir__)).freeze def self.__clean_backtrace(stack) stack.delete_if { |line| line =~ FILE_PATH_REGEX } end end # The main event def TodoOrDie(message, by: by_omitted = true, if: if_omitted = true, warn_by: warn_by_omitted = true) due_at = Time.parse(by.to_s) unless by_omitted warn_at = Time.parse(warn_by.to_s) unless warn_by_omitted condition = binding.local_variable_get(:if) unless if_omitted is_past_due_date = by_omitted || Time.now > due_at die_condition_met = if_omitted || (condition.respond_to?(:call) ? condition.call : condition) no_conditions_given = by_omitted && if_omitted && warn_by_omitted only_warn_condition_given = if_omitted && by_omitted && !warn_by_omitted ready_to_die = is_past_due_date && die_condition_met && !only_warn_condition_given should_die = no_conditions_given || ready_to_die should_warn = !warn_by_omitted && Time.now > warn_at if should_die die = TodoOrDie.config[:die] die.call(*[message, due_at, condition].take(die.arity.abs)) elsif should_warn warn = TodoOrDie.config[:warn] warn.call(*[message, due_at, warn_at, condition].take(warn.arity.abs)) end end ================================================ FILE: test/helper.rb ================================================ require "ostruct" require "timecop" Timecop.thread_safe = true require "todo_or_die" require "tldr" if defined?(Minitest::Test) TLDR::MinitestTestBackup = Minitest::Test Minitest.send(:remove_const, "Test") end module Minitest class Test < TLDR include TLDR::MinitestCompatibility end end class UnitTest < Minitest::Test def teardown Timecop.return TodoOrDie.reset Object.send(:remove_const, :Rails) if defined?(Rails) end def make_it_be_rails(is_production) rails = Object.const_set(:Rails, Module.new) rails.define_singleton_method(:env) do OpenStruct.new(production?: is_production) end fake_logger = FauxLogger.new rails.define_singleton_method(:logger) do fake_logger end fake_logger end class FauxLogger attr_reader :warning def warn(message) @warning = message end end end ================================================ FILE: test/todo_or_die_test.rb ================================================ class TodoOrDieTest < UnitTest def test_not_due_todo_does_nothing Timecop.travel(Date.civil(2200, 2, 3)) TodoOrDie("Fix stuff", by: Date.civil(2200, 2, 4)) # 🦗 sounds end def test_due_todo_blows_up Timecop.travel(Date.civil(2200, 2, 4)) error = assert_raises(TodoOrDie::OverdueTodo) { TodoOrDie("Fix stuff", by: Date.civil(2200, 2, 4)) } assert_equal <<~MSG.chomp, error.message TODO: "Fix stuff" came due on 2200-02-04. Do it! MSG end def test_warns_when_by_not_passed Timecop.travel(Date.civil(2200, 2, 4)) out, _err = capture_io { TodoOrDie("Fix stuff", warn_by: Date.civil(2200, 2, 4)) } assert_equal <<~MSG.chomp, out.strip TODO: "Fix stuff". Don't forget! MSG end def test_warns_with_by Timecop.travel(Date.civil(2200, 2, 4)) out, _err = capture_io { TodoOrDie("Fix stuff", by: Date.civil(2200, 2, 5), warn_by: Date.civil(2200, 2, 4)) } assert_equal <<~MSG.chomp, out.strip TODO: "Fix stuff" is due on 2200-02-05. Don't forget! MSG end def test_doesnt_warn_early Timecop.travel(Date.civil(2200, 2, 3)) out, _err = capture_io { TodoOrDie("Fix stuff", by: Date.civil(2200, 2, 5), warn_by: Date.civil(2200, 2, 4)) } assert_equal "", out.strip end def test_config_warn Timecop.travel(Date.civil(2200, 2, 5)) actual_message, actual_by = nil TodoOrDie.config( warn: ->(message, by) { actual_message = message actual_by = by "pants" } ) some_time = Time.parse("2200-02-06") some_earlier_time = Time.parse("2200-02-03") result = TodoOrDie("kaka", by: some_time, warn_by: some_earlier_time) assert_equal result, "pants" assert_equal actual_message, "kaka" assert_equal actual_by, some_time end def test_config_custom_explosion Timecop.travel(Date.civil(2200, 2, 5)) actual_message, actual_by = nil TodoOrDie.config( die: ->(message, by) { actual_message = message actual_by = by "pants" } ) some_time = Time.parse("2200-02-04") result = TodoOrDie("kaka", by: some_time) assert_equal result, "pants" assert_equal actual_message, "kaka" assert_equal actual_by, some_time end def test_config_custom_0_arg_die_callable Timecop.travel(Date.civil(2200, 2, 5)) TodoOrDie.config( die: -> { :neat } ) result = TodoOrDie(nil, by: "2200-02-04") assert_equal result, :neat end def test_config_custom_1_arg_die_callable Timecop.travel(Date.civil(2200, 2, 5)) actual_message = nil TodoOrDie.config( die: ->(message) { actual_message = message :cool } ) some_time = Time.parse("2200-02-04") result = TodoOrDie("secret", by: some_time) assert_equal result, :cool assert_equal actual_message, "secret" end def test_config_and_reset some_lambda = -> {} TodoOrDie.config(die: some_lambda) assert_equal TodoOrDie.config[:die], some_lambda assert_equal TodoOrDie.config({})[:die], some_lambda TodoOrDie.reset assert_equal TodoOrDie.config[:die], TodoOrDie::DEFAULT_CONFIG[:die] end def test_when_rails_is_a_thing_and_not_production make_it_be_rails(false) Timecop.travel(Date.civil(1980, 1, 20)) assert_raises(TodoOrDie::OverdueTodo) { TodoOrDie("I am in Rails", by: Date.civil(1980, 1, 15)) } end def test_when_rails_is_a_thing_and_is_production faux_logger = make_it_be_rails(true) Timecop.travel(Date.civil(1980, 1, 20)) TodoOrDie("Solve the Iranian hostage crisis", by: Date.civil(1980, 1, 20)) assert_equal <<~MSG.chomp, faux_logger.warning TODO: "Solve the Iranian hostage crisis" came due on 1980-01-20. Do it! MSG end def test_warn_when_rails_is_a_thing faux_logger = make_it_be_rails(true) Timecop.travel(Date.civil(2200, 2, 4)) TodoOrDie("Fix stuff", by: Date.civil(2200, 2, 5), warn_by: Date.civil(2200, 2, 4)) assert_equal <<~MSG.chomp, faux_logger.warning TODO: "Fix stuff" is due on 2200-02-05. Don't forget! MSG end def test_todo_or_die_file_path_removed_from_backtrace Timecop.travel(Date.civil(2200, 2, 4)) error = assert_raises(TodoOrDie::OverdueTodo) { TodoOrDie("Fix stuff", by: Date.civil(2200, 2, 4)) } assert_empty(error.backtrace.select { |line| line.match?(/todo_or_die\.rb/) }) end def test_has_version assert TodoOrDie::VERSION end def test_by_string_due_blows_up Timecop.travel(Date.civil(2200, 2, 4)) assert_raises(TodoOrDie::OverdueTodo) { TodoOrDie("Feelin' stringy", by: "2200-02-04") } end def test_by_string_not_due_does_not_blow_up Timecop.travel(Date.civil(2100, 2, 4)) TodoOrDie("Feelin' stringy", by: "2200-02-04") # 🦗 sounds end def test_due_when_no_by_or_if_is_passed Timecop.travel(Date.civil(2200, 2, 4)) assert_raises(TodoOrDie::OverdueTodo) { TodoOrDie("Check your math") } end def test_due_and_if_condition_is_true_blows_up Timecop.travel(Date.civil(2200, 2, 4)) assert_raises(TodoOrDie::OverdueTodo) { TodoOrDie("Check your math", by: Date.civil(2200, 2, 4), if: -> { 2 + 2 == 4 }) } end def test_not_due_and_if_condition_is_true_does_not_blow_up Timecop.travel(Date.civil(2100, 2, 4)) TodoOrDie("Check your math", by: Date.civil(2200, 2, 4), if: -> { 2 + 2 == 4 }) # 🦗 sounds end def test_due_and_if_condition_is_false_does_not_blow_up Timecop.travel(Date.civil(2200, 2, 4)) TodoOrDie("Check your math", by: Date.civil(2200, 2, 4), if: -> { 2 + 2 == 5 }) # 🦗 sounds end def test_by_not_passed_and_if_condition_is_true_blows_up error = assert_raises(TodoOrDie::OverdueTodo) { TodoOrDie("Check your math", if: -> { 2 + 2 == 4 }) } assert_equal <<~MSG.chomp, error.message TODO: "Check your math" has met the conditions to be acted upon. Do it! MSG end def test_by_and_if_condition_both_true_prints_full_message error = assert_raises(TodoOrDie::OverdueTodo) { TodoOrDie("Stuff", by: "1904-02-03", if: -> { true }) } assert_equal <<~MSG.chomp, error.message TODO: "Stuff" came due on 1904-02-03 and has met the conditions to be acted upon. Do it! MSG end def test_no_condition_passed_prints_short_message error = assert_raises(TodoOrDie::OverdueTodo) { TodoOrDie("Stuff") } assert_equal <<~MSG.chomp, error.message TODO: "Stuff". Do it! MSG end def test_by_not_passed_and_if_condition_false_does_not_blow_up TodoOrDie("Check your math", if: -> { 2 + 2 == 5 }) # 🦗 sounds end def test_by_not_passed_and_if_condition_is_false_boolean_does_not_blow_up TodoOrDie("Check your math", if: false) # 🦗 sounds end def test_by_not_passed_and_if_condition_is_true_boolean_blows_up assert_raises(TodoOrDie::OverdueTodo) { TodoOrDie("Check your math", if: true) } end def test_by_not_passed_and_if_condition_is_truthy_blows_up assert_raises(TodoOrDie::OverdueTodo) { TodoOrDie("Check your math", if: 42) } end def test_by_not_passed_and_if_condition_is_falsy_does_not_blow_up TodoOrDie("Check your math", if: nil) # 🦗 sounds end end ================================================ FILE: todo_or_die.gemspec ================================================ lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "todo_or_die" Gem::Specification.new do |spec| spec.name = "todo_or_die" spec.version = TodoOrDie::VERSION spec.authors = ["Justin Searls"] spec.email = ["searls@gmail.com"] spec.summary = "Write TO​DOs in code that ensure you actually do them" spec.homepage = "https://github.com/searls/todo_or_die" spec.files = Dir.chdir(File.expand_path("..", __FILE__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } end spec.require_paths = ["lib"] end