Class: Subversion::SvnCommand

Inherits:
Console::Command
  • Object
show all
Defined in:
lib/svn-command/svn_command.rb

Overview

Tested by: ../../test/svn_command_test.rb

Defined Under Namespace

Modules: Add, Commit, Diff, EditMessage, EditRevisionProperty, Externalize, ExternalsItems, GetMessage, Help, Log, Move, Revisions, SetMessage, Status, Update, ViewCommits

Constant Summary collapse

@@standard_remote_command_options =
{
  [:__username] => 1,
  [:__password] => 1,
  [:__no_auth_cache] => 0,
  [:__non_interactive] => 0,
  [:__config_dir] => 1,
}
@@subcommand_list =

This shouldn’t be necessary. Console::Command should allow introspection. But until such time…

[
  'each_unadded',
  'externals_items', 'externals_outline', 'externals_containers', 'edit_externals', 'externalize',
  'ignore',
  'revisions',
  'get_message', 'set_message', 'edit_message',
  'view_commits',
  'repository_root',
  'latest_revision',
  'delete_svn'
]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ SvnCommand

Returns a new instance of SvnCommand.



110
111
112
113
# File 'lib/svn-command/svn_command.rb', line 110

def initialize(*args)
  @passthrough_options = []
  super
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(subcommand, *args) ⇒ Object

Any subcommands that we haven’t implemented here will simply be passed on to the built-in svn command. :todo: Distinguish between subcommand_missing and method_missing !

Currently, for example, if as isn't defined, this: puts Subversion.externalize(repo_path, {:as => as })
will call method_missing and try to run `svn as`, which of course will fail (without a sensible relevant error)...
I think we should probably just have a separate subcommand_missing, like we already have a separate option_missing !!!
Even a simple type (sss instead of ss) causes trouble... *this* was causing a call to "/usr/bin/svn new_messsage" -- what huh??
   def set_message(new_message = nil)
     args << new_messsage if new_message


158
159
160
161
# File 'lib/svn-command/svn_command.rb', line 158

def method_missing(subcommand, *args)
  #puts "method_missing(#{subcommand}, #{args.inspect})"
  svn :exec, subcommand, *args
end

Class Method Details

.parse_revision_ranges(revisions_array) ⇒ Object



574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'lib/svn-command/svn_command.rb', line 574

def SvnCommand.parse_revision_ranges(revisions_array)
  revisions_array.map do |item|
    case item
      when /(\d+):(\d+)/
        ($1.to_i .. $2.to_i)
      when /(\d+)-(\d+)/
        ($1.to_i .. $2.to_i)
      when /(\d+)\.\.(\d+)/
        ($1.to_i .. $2.to_i)
      when /\d+/
        item.to_i
      else
        raise "Item in revisions_array had an unrecognized format: #{item}"
    end
  end.expand_ranges
end

Instance Method Details

#__debugObject



122
123
124
# File 'lib/svn-command/svn_command.rb', line 122

def __debug
  $debug = true
end

#__dry_runObject



125
126
127
# File 'lib/svn-command/svn_command.rb', line 125

def __dry_run
  Subversion::dry_run = true
end

#__exceptObject Also known as: __exclude

Usually most Subversion commands are recursive and all-inclusive. This option adds file exclusion to most of Subversion’s commands. Use this if you want to commit (/add/etc.) everything but a certain file or set of files

svn commit dir1 dir2 --except dir1/not_ready_yet.rb


140
141
142
143
144
# File 'lib/svn-command/svn_command.rb', line 140

def __except
  # We'll have to use a FileList to do this. This option will remove all file arguments, put them into a FileList as inclusions, 
  # add the exclusions, and then pass the resulting list of files on to the *actual* svn command.
  # :todo:
end

#__no_colorObject



119
120
121
# File 'lib/svn-command/svn_command.rb', line 119

def __no_color
  Subversion::color = false
end

#__print_commandsObject Also known as: __show_commands, _V, __Verbose



129
130
131
# File 'lib/svn-command/svn_command.rb', line 129

def __print_commands
  Subversion::print_commands = true
end

#add(*args) ⇒ Object



210
211
212
213
# File 'lib/svn-command/svn_command.rb', line 210

def add(*args)
  #puts "add #{args.inspect}"
  svn :exec, 'add', *args
end

#add_all_unaddedObject


Raises:

  • (NotImplementedError)


915
916
917
# File 'lib/svn-command/svn_command.rb', line 915

def add_all_unadded
  raise NotImplementedError
end

#commit(*args) ⇒ Object



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/svn-command/svn_command.rb', line 251

def commit(*args)
  latest_rev_before_commit = Subversion.latest_revision if @broken || @skip_notification

  Subversion.print_commands_for do
    puts svn(:capture, "propset svn:skip_commit_notification_for_next_commit true --revprop -r #{latest_rev_before_commit}", :prepare_args => false)
  end if @skip_notification
  # :todo:
  # Add some logic to automatically skip the commit e-mail if the size of the files to be committed exceeds a threshold of __ MB.
  # (Performance idea: Only check the size of the files if svn st includes (bin)?)

  svn(:system, 'commit', *(['--force-log'] + args))

  # The following only works if we do :capture (`svn`), but that doesn't work so well (at all) if svn tries to open up an editor (vim),
  # which is what happens if you don't specify a message.:
  #   puts output = svn(:capture, 'commit', *(['--force-log'] + args))
  #   just_committed = (matches = output.match(/Committed revision (\d+)\./)) && matches[1]

  Subversion.print_commands_for do
    puts svn(:capture, "propset code:broken true --revprop -r #{latest_rev_before_commit + 1}", :prepare_args => false)
  end if @broken

end

#defaultObject

This is here solely to allow subcommandless commands like ‘svn –version`



163
164
165
# File 'lib/svn-command/svn_command.rb', line 163

def default()
  svn :exec
end

#delete_svnObject


Cause a working copy to cease being a working copy



908
909
910
911
# File 'lib/svn-command/svn_command.rb', line 908

def delete_svn
  system('find -name .svn | xargs -n1 echo')
  system('find -name .svn | xargs -n1 rm -r')
end

#diff(*directories) ⇒ Object



341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'lib/svn-command/svn_command.rb', line 341

def diff(*directories)
  directories = ['./'] if directories.empty?
  puts Extensions.diff(*(directories + @passthrough_options))

  begin # Show diff for externals (if there *are* any and the user didn't tell us to ignore them)
    output = StringIO.new
    #paths = args.reject{|arg| arg =~ /^-/} || ['./']
    directories.each do |path|
      (Subversion.externals_items(path) || []).each do |item|
        diff_output = Extensions.diff(item).strip
        unless diff_output == ""
          #output.puts '-'*100
          #output.puts item.ljust(100, ' ').black_on_white.bold.underline
          output.puts item.ljust(100).black_on_white.bold
          output.puts diff_output
        end
      end
    end
    unless output.string == ""
      #puts '='*100
      puts (' '*100).yellow.underline
      puts " Diff of externals (**don't forget to commit these too!**):".ljust(100, ' ').yellow_on_red.bold.underline
      puts output.string
    end
  end unless @ignore_externals
end

#each_unadded(*args) ⇒ Object


Goes through each “unadded” file (each file reporting a status of ?) reported by svn status and asks you what you want to do with them (add, delete, or ignore)



593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
# File 'lib/svn-command/svn_command.rb', line 593

def each_unadded(*args)
  catch :exit do

    $ignore_dry_run_option = true
    Subversion::Extensions.each_unadded( Subversion.status(*args) ) do |file|
      $ignore_dry_run_option = false
      begin
        puts( ('-'*100).green )
        puts "What do you want to do with '#{file.white.underline}'?".white.bold
        begin
          if !File.exist?(file)
            raise "#{file} doesn't seem to exist -- even though it was reported by svn status"
          end
          if File.file?(file)
            if FileTest.binary_file?(file)
              puts "(Binary file -- cannot show preview)".bold
            else
              puts "File contents:"
              # Only show the first x bytes so that we don't accidentally dump the contens of some 20 GB log file to screen...
              contents = File.read(file, bytes_threshold = 5000) || ''
              max_lines = 55
              contents.lines[0..max_lines].each {|line| puts line}
              puts "..." if contents.length >= bytes_threshold          # So they know that there may be *more* to the file than what's shown
            end
          elsif File.directory?(file)
            puts "Directory contains:"
            Dir.new(file).reject {|f| ['.','..'].include? f}.each do |f|
              puts f
            end
          else
            raise "#{file} is not a file or directory -- what *is* it then???"
          end
        end
        print(
          "Add".menu_item(:green) + ", " +
          "Delete".menu_item(:red) + ", " +
          "add to " + "svn:".yellow + "Ignore".menu_item(:yellow) + " property, " + 
          "or " + "any other key".white.bold + " to do nothing > "
        )
        response = ""
        response = $stdin.getc.chr.downcase # while !['a', 'd', 'i', "\n"].include?(begin response.downcase!; response end)


        case response
          when 'a'
            print "\nAdding... "
            Subversion.add file
            puts
          when 'd'
            puts

            response = ""
            if File.directory?(file)
              response = confirm("Are you pretty much " + "SURE".bold + " you want to '" + "rm -rf #{file}".red.bold + "'? ")
            else
              response = "y"
            end

            puts "response=#{response}"
            if response == 'y'
              print "\nDeleting... "
              FileUtils.rm_rf file
              puts
            else
              puts "\nI figured as much!"
            end
          when 'i'
            print "\nIgnoring... "
            Subversion.ignore file
            puts
          else
            # Skip / Do nothing with this file
            puts " (Skipping...)"
        end
      rescue Interrupt
        puts "\nGoodbye!"
        throw :exit
      end
    end # each_unadded

  end # catch :exit
end

#edit_externals(directory = nil) ⇒ Object



752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
# File 'lib/svn-command/svn_command.rb', line 752

def edit_externals(directory = nil)
  catch :exit do
    if directory.nil? || !Subversion::ExternalsContainer.new(directory).has_entries?
      if directory.nil?
        puts "No directory specified. Editing externals for *all* externals dirs..."
        directory = "./"
      else
        puts "Editing externals for *all* externals dirs..."
      end
      Subversion.externals_containers(directory).each do |external|
        puts external.to_s
        command = "#{Subversion.executable} propedit svn:externals #{external.container_dir}"
        #puts command
        begin
          response = confirm("Do you want to edit svn:externals for this directory?".black_on_white)
          system command if response == 'y'
        rescue Interrupt
          puts "\nGoodbye!"
          throw :exit
        ensure
          puts
        end
      end
      puts 'Done'
    else
      system "#{Subversion.executable} propedit svn:externals #{directory}"
    end
  end # catch :exit
end

#edit_message(directory = './') ⇒ Object



899
900
901
# File 'lib/svn-command/svn_command.rb', line 899

def edit_message(directory = './')
  edit_revision_property('svn:log', directory)
end

#edit_property(property_name, directory = './') ⇒ Object



903
904
# File 'lib/svn-command/svn_command.rb', line 903

def edit_property(property_name, directory = './')
end

#edit_revision_property(property_name, directory = './') ⇒ Object



866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
# File 'lib/svn-command/svn_command.rb', line 866

def edit_revision_property(property_name, directory = './')
  args = ['propedit', '--revprop', property_name, directory]
  rev = @revision ? @revision : 'head'
  args.concat ['-r', rev]
  Subversion.print_commands_for do
    svn :system, *args
  end

  value = Subversion::get_revision_property(property_name, rev)
  p value

  # Currently there is no seperate option to *delete* a revision property (propdel)... That would be useful for those
  # properties that are just boolean *flags* (set or not set).
  # I'm assuming most people will very rarely if ever actually want to set a property to the empty string (''), so
  # we can use the empty string as a way to trigger a propdel...
  if value == ''
    puts
    response = confirm("Are you sure you want to delete property #{property_name}".red.bold + "'? ")
    puts
    if response == 'y'
      Subversion.print_commands_for do
        Subversion::delete_revision_property(property_name, rev)
      end
    end
  end
end

#externalize(repo_path, as_arg = nil) ⇒ Object

svn externalize your/repo/shared_tasks/tasks –as shared or

svn externalize http://your/repo/shared_tasks/tasks shared


799
800
801
802
803
804
# File 'lib/svn-command/svn_command.rb', line 799

def externalize(repo_path, as_arg = nil)
  # :todo: let them pass in local_path as well? -- then we would need to accept 2 -- 3 -- args, the first one poylmorphic, the second optional
  # :todo: automated test for as_arg/as combo

  Subversion.externalize(repo_path, {:as => as || as_arg})
end

#externals_containers(directory = "./") ⇒ Object

Lists directories that have the svn:externals property set.



745
746
747
748
749
# File 'lib/svn-command/svn_command.rb', line 745

def externals_containers(directory = "./")
  puts Subversion.externals_containers(directory).map { |external|
    external.container_dir
  }
end

#externals_items(directory = "./") ⇒ Object



698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
# File 'lib/svn-command/svn_command.rb', line 698

def externals_items(directory = "./")
  longest_path_name = 25

  externals_structs = Subversion.externals_containers(directory).map do |external|
    returning(
      external.entries_structs.map do |entry|
          Struct.new(:path, :repository_path).new(
            File.join(external.container_dir, entry.name).relativize_path,
            entry.repository_path
          )
        end
    ) do |entries_structs|
      longest_path_name = 
        [
          longest_path_name,
          entries_structs.map { |entry|
            entry.path.size
          }.max
        ].max
    end
  end

  puts '(Use the -o/--omit-repository-path option if you just want the external paths/names without the repository paths)' unless @omit_repository_path
  puts externals_structs.map { |entries_structs|
    entries_structs.map { |entry|
      entry.path.ljust(longest_path_name + 1) +
        (@omit_repository_path ? '' : entry.repository_path)
    }
  }
end

#externals_outline(directory = "./") ⇒ Object

For every directory that has the svn:externals property set, this prints out the container name and then lists the contents of its svn:externals property (dir, URL) as a bulleted list



736
737
738
739
740
# File 'lib/svn-command/svn_command.rb', line 736

def externals_outline(directory = "./")
  puts Subversion.externals_containers(directory).map { |external|
    external.to_s.relativize_path
  }
end

#fix_out_of_date_commit_state(dir) ⇒ Object

A fix for this annoying problem that I seem to come across all too frequentrly:

svn: Commit failed (details follow):
svn: Your file or directory 'whatever.rb' is probably out-of-date


281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/svn-command/svn_command.rb', line 281

def fix_out_of_date_commit_state(dir)
  dir = $1 if dir =~ %r|^(.*)/$|                           # Strip trailing slash.

  puts Subversion.export("#{dir}", "#{dir}.new").          # Exports (copies) the contents of working copy 'dir' (including your uncommitted changes, don't worry! ... and you'll get a chance to confirm before anything is deleted; but sometimes although it exports files that are scheduled for addition, they are no longer scheduled for addition in the new working copy, so you have to re-add them) to non-working-copy 'dir.new'
    add_exit_code_error 
  return if !$?.success?

  system("mv #{dir} #{dir}.backup")                        # Just in case something goes ary
  puts ''.add_exit_code_error
  return if !$?.success?

  puts "Restoring #{dir}..."
  Subversion.update dir                                    # Restore the directory to a pristine state so we will no longer get that annoying error

  # Assure the user that dir.new really does have your latest changes
  #puts "Here's a diff. Your changes/additions will be in the *right* (>) file."
  #system("diff #{dir}.backup #{dir}")

  # Merge those latest changes back into the pristine working copy
  system("cp -R #{dir}.new/. #{dir}/")

  # Assure the user one more time
  puts Extensions.diff(dir)

  # Actually commit
  puts
  response = confirm("Are you ready to try the commit again now?")
  puts
  if response == 'y'
    puts "Great. Go for it."
    #Subversion.commit dir
  end

  # Clean up
  #puts
  #response = confirm("Do you want to delete array.backup array.new now?")
  puts "Don't forget to delete array.backup array.new now!"
  #rm_rf array.backup, array.new
  puts
end

#get_messageObject



822
823
824
825
826
827
828
829
830
831
832
# File 'lib/svn-command/svn_command.rb', line 822

def get_message()
  #svn propget --revprop svn:log -r2325
  args = ['propget', '--revprop', 'svn:log']
  #args.concat ['-r', @revision ? @revision : Subversion.latest_revision]
  args.concat ['-r', (revision = @revision ? @revision : 'head')]
  puts "Message for r#{Subversion.latest_revision} :" if revision == 'head'

  $ignore_dry_run_option = true
  puts filtered_svn(*args)
  $ignore_dry_run_option = false
end

#grepObject

Raises:

  • (NotImplementedError)


918
919
920
# File 'lib/svn-command/svn_command.rb', line 918

def grep
  raise NotImplementedError
end

#grep_externalsObject

Raises:

  • (NotImplementedError)


921
922
923
# File 'lib/svn-command/svn_command.rb', line 921

def grep_externals
  raise NotImplementedError
end

#grep_logObject

Raises:

  • (NotImplementedError)


924
925
926
# File 'lib/svn-command/svn_command.rb', line 924

def grep_log
  raise NotImplementedError
end

#help(subcommand = nil) ⇒ Object



376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'lib/svn-command/svn_command.rb', line 376

def help(subcommand = nil)
  case subcommand
    when "externals"
      puts %Q{
             | externals (ext): Lists all externals in the given working directory.
             | usage: externals [PATH]
             }.margin
      # :todo: Finish...

    when nil
      puts "You are using " + 
           's'.green.bold + 'v'.cyan.bold + 'n'.magenta.bold + '-' + 'c'.red.bold + 'o'.cyan.bold + 'm'.blue.bold + 'm'.yellow.bold + 'a'.green.bold + 'n'.white.bold + 'd'.green.bold + ' version ' + Project::Version
           ", a colorful, useful replacement/wrapper for the standard svn command."
      puts "svn-command is installed at: " + $0.bold
      puts "You may bypass this wrapper by using the full path to svn: " + Subversion.executable.bold
      puts
      puts Subversion.help(subcommand).gsub(<<End, '')

Subversion is a tool for version control.
For additional information, see http://subversion.tigris.org/
End

      puts
      puts 'Subcommands added by svn-command (refer to '.green.underline + 'http://svn-command.rubyforge.org/'.white.underline + ' for usage details):'.green.underline
      @@subcommand_list.each do |subcommand|
        aliases_list = subcommand_aliases_list(subcommand.option_methodize.to_sym)
        aliases_list = aliases_list.empty? ? '' : ' (' + aliases_list.join(', ') + ')'
        puts '   ' + subcommand + aliases_list
      end
      #p subcommand_aliases_list(:edit_externals)

    else
      #puts "help #{subcommand}"
      puts Subversion.help(subcommand)
  end
end

#ignore(file) ⇒ Object




809
810
811
# File 'lib/svn-command/svn_command.rb', line 809

def ignore(file)
  Subversion.ignore(file)
end

#latest_revision(*args) ⇒ Object




529
530
531
# File 'lib/svn-command/svn_command.rb', line 529

def latest_revision(*args)
  puts Subversion.latest_revision
end

#log(*args) ⇒ Object



427
428
429
430
# File 'lib/svn-command/svn_command.rb', line 427

def log(*args)
  puts Subversion.log( @passthrough_options + args )
  #svn :exec, *args
end

#move(*args) ⇒ Object

Unlike the built-in move, this one lets you list multiple source files

Source... DestinationDir

or

Source Destination


454
455
456
457
458
459
460
461
462
463
464
465
# File 'lib/svn-command/svn_command.rb', line 454

def move(*args)
  if args.length >= 3
    destination = args.pop
    sources = args

    sources.each do |source|
      puts filtered_svn('move', source, destination)
    end
  else
    svn :exec, 'move', *args
  end
end

#option_missing(option_name, args) ⇒ Object



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/svn-command/svn_command.rb', line 167

def option_missing(option_name, args)
  #puts "#{@subcommand} defined? #{@subcommand_is_defined}"
  if !@subcommand_is_defined
    # It's okay to use this for pass-through subcommands, because we just pass all options/arguments verbatim anyway...
    #puts "option_missing(#{option_name}, #{args.inspect})"
  else
    # But for subcommands that are defined here, we should know better! All valid options should be explicitly listed!
    raise UnknownOptionError.new(option_name)
  end

  # The following is necessary because we really don't know the arity (how many subsequent tokens it should eat) of the option -- we don't know anything about the options, in fact; that's why we've landed in option_missing.
  # This is kind of a hokey solution, but for any unrecognized options/args (which will be *all* of them unless we list the available options in the subcommand module), we just eat all of the args, store them in @passthrough_options, and later we will add them back on.
  # What's annoying about it this solution is that *everything* after the first unrecognized option comes in as args, even if they are args for the subcommand and not for the *option*!
  # But...it seems to work to just pretend they're options.
  # It seems like this is mostly a problem for *wrappers* that try to use Console::Command. Sometimes you just want to *pass through all args and options* unchanged and just filter the output somehow.
  # Command doesn't make that super-easy though. If an option (--whatever) isn't defined, then the only way to catch it is in option_missing. And since we can't the arity unless we enumerate all options, we have to hokily treat the first option as having unlimited arity.
  #   Alternatives considered: 
  #     * Assume arity of 0. Then I'm afraid it would extract out all the option flags and leave the args that were meant for the args dangling there out of order ("-r 1 -m 'hi'" => "-r -m", "1 'hi'")
  #     * Assume arity of 1. Then if it was really 0, it would pick up an extra arg that really wasn't supposed to be an arg for the *option*.
  # Ideally, we wouldn't be using option_missing at all because all options would be listed in the respective subcommand module...but for subcommands handled through method_missing, we don't have that option.

  @passthrough_options << "#{option_name}" << args
  @passthrough_options.flatten!

  return arity = args.size  # All of 'em
end

#repository_root(*args) ⇒ Object




522
523
524
# File 'lib/svn-command/svn_command.rb', line 522

def repository_root(*args)
  puts Subversion.repository_root(*args)
end

#revisions(directory = './') ⇒ Object



954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
# File 'lib/svn-command/svn_command.rb', line 954

def revisions(directory = './')
  puts "Getting list of revisions for '#{directory.white.bold}' ..."

  head = Subversion.latest_revision
  revision_of_directory = Subversion.latest_revision_for_path(directory)

  # It's possible for a working copy to get "out of date" (even if you were the last committer!), in which case svn log will
  # only list revisions up to that revision (actually looks like it only goes up to and including Last Changed Rev: 2838,
  # not Revision: 2839, as reported by svn info...)
  if revision_of_directory < head
    puts "The working copy '#{directory.white.bold}' appears to be out-of-date (#{revision_of_directory}) with respect to the head revision (#{head}). Updating..."
    Subversion.update(directory)
  end

  revisions = Subversion.revisions(directory)

  puts "#{revisions.length.to_s.bold} revisions found. Starting with #{@reverse ? 'oldest' : 'most recent'} revision and #{@reverse ? 'going forward in time' : 'going backward in time'}..."
  revisions.instance_variable_get(:@revisions).reverse! if @reverse
  revision_ids = revisions.map(&:identifier)

  target_rev = nil # revision_ids.first
  show_revision_again = true
  revisions.each do |revision|
    rev = revision.identifier
    other_rev = rev-1
    if target_rev
      if rev == target_rev
        target_rev = nil    # We have arrived.
      else
        next                # Keep going (hopefully in the right direction!)
      end
    end

    # Display the revision
    if show_revision_again
      puts((' '*100).green.underline)
      puts "#{revisions.length - revision_ids.index(rev)}. ".green.bold +
        "r#{rev}".magenta.bold + (rev == head ? ' (head)'.bold : '') + 
        " | #{revision.developer} | #{revision.time.strftime('%Y-%m-%d %H:%M:%S')}".magenta.bold
      puts revision.message
      puts
      #pp revision
      puts revision.map {|a|
        (a.status ? a.status[0..0].colorize_svn_status_code : ' ') +   # This check is necessary because RSCM doesn't recognize several Subversion status flags, including 'R', and status will return nil in these cases.
          ' ' + a.path
      }.join("\n")
    else
      show_revision_again = true
    end

    # Display the menu
    print(
      'View this changeset'.menu_item(:cyan) + ', ' +
      'Diff against specific revision'.menu_item(:cyan, 'D') + ', ' +
      'Grep the changeset'.menu_item(:cyan, 'G') + ', ' +
      'List or '.menu_item(:magenta, 'L') + '' +
      'Edit revision properties'.menu_item(:magenta, 'E') + ', ' +
      'svn Cat all files from revision'.menu_item(:cyan, 'C') + ', ' +
      'grep the cat'.menu_item(:cyan, 'a') + ', ' + "\n  " +
      'mark as Reviewed'.menu_item(:green, 'R') + ', ' +
      'edit log Message'.menu_item(:yellow, 'M') + ', ' +
      'or ' + 'browse using ' + 'Up/Down/Enter'.white.bold + ' keys > '
    )

    # Get response from user and then act on it
    begin # rescue
      response = ""
      response = $stdin.getc.chr.downcase

      # Escape sequence such as the up arrow key ("\e[A")
      if response == "\e"
        response << (next_char = $stdin.getc.chr)
        if next_char == '['
          response << (next_char = $stdin.getc.chr)
        end
      end

      if response == 'd' # diff against Other revision
        response = 'v'
        puts
        print 'All right, which revision shall it be then? '.bold + ' (backspace not currently supported)? '
        other_rev = $stdin.gets.chomp.to_i
      end

      case response
        when 'v'  # Diff
          revs_to_compare = [other_rev, rev]
          puts "\n"*10
          puts((' '*100).green.underline)
          print "Diffing #{revs_to_compare.min}:#{revs_to_compare.max}... ".bold
          puts
          #Subversion.repository_root
          SvnCommand.execute("diff #{directory} --ignore-externals -r #{revs_to_compare.min}:#{revs_to_compare.max}")

        when 'g'  # Grep the changeset
          # :todo; make it accept regexpes like /like.*this/im so you can make it case insensitive or multi-line
          revs_to_compare = [other_rev, rev]
          puts
          print 'Grep for'.bold + ' (Regular expressions ' + 'like.*this'.bold.blue + ' are allowed, but not ' + '/like.*this/im'.bold.blue + '): '
          search_pattern = $stdin.gets.chomp.to_rx
          puts((' '*100).green.underline)
          puts "Searching `svn diff #{revs_to_compare.min}:#{revs_to_compare.max}` for #{search_pattern.to_s}... ".bold
          diffs = Subversion.diffs(directory, '-r', "#{revs_to_compare.min}:#{revs_to_compare.max}")

          hits = 0
          diffs.each do |filename, diff|
            #.grep(search_pattern)
            if diff.diff =~ search_pattern
              puts diff.filename_pretty
              puts( diff.diff.grep(search_pattern). # This will get us just the interesting *lines* (as an array). 
                map { |line|                        # Now, for each line...
                  hits += 1
                  line.highlight_occurences(search_pattern)
                }
              )
            end
          end
          if hits == 0
            puts "Search term not found!".red.bold
          end
          show_revision_again = false

        when 'l'  # List revision properties
          puts
          puts Subversion::Extensions::printable_revision_properties(rev)
          show_revision_again = false

        when 'e'  # Edit revision property
          puts
          puts Subversion::Extensions::printable_revision_properties(rev)
          puts "Warning: These properties are *not* under version control! Try not to permanently destroy anything *too* important...".red.bold
          puts "Note: If you want to *delete* a property, simply set its value to '' and it will be deleted (propdel) for you."
          print 'Which property would you like to edit'.bold + ' (backspace not currently supported)? '
          property_name = $stdin.gets.chomp
          unless property_name == ''
            Subversion.print_commands_for do
              @revision = rev
              edit_revision_property(property_name, directory)
            end
          end

          show_revision_again = false

        when 'c'  # Cat all files from revision
          puts 'Not implemented yet'
          show_revision_again = false

        when 'a'  # Grep the cat
          puts 'Not implemented yet'
          show_revision_again = false

        when 'r'  # Mark as reviewed
          puts
          your_name = ENV['USER'] # I would use the same username that Subversion itself would use if you committed
                                  # something (since it is sometimes different from your system username), but I don't know
                                  # how to retrieve that (except by poking around in your ~/.subversion/ directory, but
                                  # that seems kind of rude...).
          puts "Marking as reviewed by '#{your_name}'..."
          Subversion.print_commands_for do
            puts svn(:capture, "propset code:reviewed '#{your_name}' --revprop -r #{rev}", :prepare_args => false)
            # :todo: Maybe *append* to code:reviewed (,-delimited) rather than overwriting it?, in case there is a policy of requiring 2 reviewers or something
          end

        when 'm'  # Edit log message
          puts
          Subversion.print_commands_for do
            SvnCommand.execute("edit_message -r #{rev}")
          end

        when "\e[A" # Up
          i = revision_ids.index(rev)
          target_rev = revision_ids[i - 1]
          puts " Previous..."
          retry

          
        when /\n|\e\[B/ # Enter or Down
          # Skip / Do nothing with this file
          puts " Next..."
          next

        else
          # Invalid option. Do nothing.
          #puts response.inspect
          puts
          show_revision_again = false

      end # case response

      redo # Until they tell us they're ready to move on...

    rescue Interrupt
      puts "\nGoodbye!"
      return
    end # rescue
  end
end

#set_message(new_message) ⇒ Object



842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
# File 'lib/svn-command/svn_command.rb', line 842

def set_message(new_message)
  #svn propset --revprop -r 25 svn:log "Journaled about trip to New York."
  puts "Message before changing:"
  get_message

  args = ['propset', '--revprop', 'svn:log']
  args.concat ['-r', @revision ? @revision : 'head']
  args << new_message if new_message
  if @filename
    contents = File.readlines(@filename).join.strip
    puts "Read file '#{@filename}':"
    print contents
    puts
    args << contents
  end
  svn :exec, *args
end

#status(*args) ⇒ Object



482
483
484
485
486
487
# File 'lib/svn-command/svn_command.rb', line 482

def status(*args)
  #puts "in status(#{args.inspect})"
  #puts "#{self}.@passthrough_options == #{@passthrough_options.inspect}"
  #print Subversion::Extensions.status_lines_filter( Subversion.status(*(@passthrough_options + args)) )
  print Subversion::Extensions.status_lines_filter( Subversion.status(*(@passthrough_options + args)) )
end

#update(*args) ⇒ Object



500
501
502
# File 'lib/svn-command/svn_command.rb', line 500

def update(*args)
  puts Subversion::Extensions.update_lines_filter( Subversion.update(*prepare_args(args)) )
end

#url(*args) ⇒ Object




517
518
519
# File 'lib/svn-command/svn_command.rb', line 517

def url(*args)
  puts Subversion.url(*args)
end

#view_commits(path = "./") ⇒ Object



555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
# File 'lib/svn-command/svn_command.rb', line 555

def view_commits(path = "./")
  if @revisions.nil?
    raise "-r (revisions) option is mandatory"
  end
  $ignore_dry_run_option = true
  base_url = Subversion.base_url(path)
  $ignore_dry_run_option = false
  #puts "Base URL: #{base_url}"
  revisions = self.class.parse_revision_ranges(@revisions)
  revisions.each do |revision|
    puts Subversion.log("-r #{revision} -v #{base_url}")
  end
  
  puts Subversion.diff("-r #{revisions.first}:#{revisions.last} #{path}")
  #/usr/bin/svn diff http://code.qualitysmith.com/gemables/subversion@2279 http://code.qualitysmith.com/gemables/svn-command@2349 --diff-cmd colordiff

end