A platform for community discussion. Free, open, simple.
FEATURE: Improved deprecation warnings (#6722)
Xiao Guan7ec124fc897d
diff --git a/app/assets/javascripts/discourse-common/lib/deprecated.js.es6 b/app/assets/javascripts/discourse-common/lib/deprecated.js.es6index ecb2f152d51..e1d82d3bb20 100644--- a/app/assets/javascripts/discourse-common/lib/deprecated.js.es6+++ b/app/assets/javascripts/discourse-common/lib/deprecated.js.es6@@ -1,3 +1,15 @@-export default function deprecated(msg) {- console.warn(`DEPRECATION: ${msg}`); // eslint-disable-line no-console+export default function deprecated(msg, opts = {}) {+ msg = ["Deprecation notice:", msg];+ if (opts.since) {+ msg.push(`(deprecated since Discourse ${opts.since})`);+ }+ if (opts.dropFrom) {+ msg.push(`(removal in Discourse ${opts.dropFrom})`);+ }+ msg = msg.join(" ");++ if (opts.raiseError) {+ throw msg;+ }+ console.warn(msg); // eslint-disable-line no-console}diff --git a/lib/discourse.rb b/lib/discourse.rbindex 7991eb3e5e8..cab68f014fa 100644--- a/lib/discourse.rb+++ b/lib/discourse.rb@@ -602,9 +602,18 @@ module Discourseendend- def self.deprecate(warning)- location = caller_locations[1]- warning = "Deprecation Notice: #{warning}\nAt: #{location.label} #{location.path}:#{location.lineno}"+ def self.deprecate(warning, drop_from: nil, since: nil, raise_error: false)+ location = caller_locations[1].yield_self { |l| "#{l.path}:#{l.lineno}:in \`#{l.label}\`" }+ warning = ["Deprecation notice:", warning]+ warning << "(deprecated since Discourse #{since})" if since+ warning << "(removal in Discourse #{drop_from})" if drop_from+ warning << "\nAt #{location}"+ warning = warning.join(" ")++ if raise_error+ raise Deprecation.new(warning)+ end+if Rails.env == "development"STDERR.puts(warning)enddiff --git a/spec/components/discourse_spec.rb b/spec/components/discourse_spec.rbindex 4a084c2d442..5d53b71f370 100644--- a/spec/components/discourse_spec.rb+++ b/spec/components/discourse_spec.rb@@ -300,6 +300,24 @@ describe Discourse doexpect(Rails.logger.warnings).to eq([old_method_caller(k)])end++ it 'can report the deprecated version' do+ Discourse.deprecate(SecureRandom.hex, since: "2.1.0.beta1")++ expect(Rails.logger.warnings[0]).to include("(deprecated since Discourse 2.1.0.beta1)")+ end++ it 'can report the drop version' do+ Discourse.deprecate(SecureRandom.hex, drop_from: "2.3.0")++ expect(Rails.logger.warnings[0]).to include("(removal in Discourse 2.3.0)")+ end++ it 'can raise deprecation error' do+ expect {+ Discourse.deprecate(SecureRandom.hex, raise_error: true)+ }.to raise_error(Discourse::Deprecation)+ endendend