aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar √Čtienne Deparis 2020-10-20 09:05:19 +0200
committerGravatar √Čtienne Deparis 2020-10-20 09:05:19 +0200
commitf17102b344f34381f2e3195a4feb3f1c691b80b7 (patch)
tree7cbfb82d9bf3bf02f4f4d321a1da6d3148b1a93c
parent7ef9d00ad3eadc13664ddb0bbf7fda1377967934 (diff)
downloadshell_utils-f17102b344f34381f2e3195a4feb3f1c691b80b7.tar.gz
shell_utils-f17102b344f34381f2e3195a4feb3f1c691b80b7.tar.xz
shell_utils-f17102b344f34381f2e3195a4feb3f1c691b80b7.zip
feat(gitutils): Add a new command git-restoretime.rb
-rw-r--r--git-restoretime.rb53
1 files changed, 53 insertions, 0 deletions
diff --git a/git-restoretime.rb b/git-restoretime.rb
new file mode 100644
index 0000000..8175b14
--- /dev/null
+++ b/git-restoretime.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+require 'date'
+require 'optparse'
+require 'fileutils'
+require File.expand_path('./git_utils', __dir__)
+
+unless GitUtils.in_git_repository?
+ warn 'fatal: Not in a git repository'
+ exit 1
+end
+
+options = { verbose: false, dryrun: false }
+
+OptionParser.new do |parser|
+ parser.banner = 'Usage: git restoretime [-h] [-v] [-n]'
+
+ parser.on('-h', '--help', 'Show this help message') do
+ puts parser.help
+ exit
+ end
+
+ parser.on('-v', '--verbose', 'Wether to display modification messages') do
+ options[:verbose] = true
+ end
+
+ parser.on('-n', '--dryrun', 'Do not actually make any change') do
+ options[:verbose] = true
+ options[:dryrun] = true
+ end
+end.parse!
+
+cmd = [
+ 'git', 'ls-tree', '-r', '--name-only', 'HEAD', ARGV[0]
+].compact.join(' ')
+git_log_cmd = 'git log -1 --pretty="%ad" --date="format:%Y%m%d%H%M.%S"'
+
+`#{cmd}`.split("\n").each do |file_path|
+ current_mtime = File.mtime(file_path)
+ git_raw_time = `#{git_log_cmd} -- #{file_path}`.strip
+ git_time = DateTime.strptime(git_raw_time, '%Y%m%d%H%M.%S').to_time
+ if git_time < current_mtime
+ # The file has been wrongly not as more recent than it is, maybe
+ # because of a recent clone. Restore its modification time
+ human_date = git_time.strftime('%Y-%m-%d %H:%M')
+ FileUtils.touch(
+ file_path,
+ mtime: git_time,
+ noop: options[:dryrun],
+ verbose: options[:verbose]
+ )
+ end
+end