33

当您运行时git clone,它会更新进度。例如,对象收到就地变化的百分比。

user@athena:~/cloj/src$ git clone git://git.boinkor.net/slime.git
Initialized empty Git repository in /home/user/cloj/src/slime/.git/
remote: Counting objects: 15936, done.
remote: Compressing objects: 100% (5500/5500), done.
Receiving objects:  28% (4547/15936), 3.16 MiB | 165 KiB/s

这是如何实现的?它是否使用 ncurses 或更简单的东西,例如退格字符和常规字符输出的某种组合?

我对如何从 Ruby 完成这种控制台输出特别感兴趣。

编辑

我原来的问题得到了回答。但这里有一个附录。例如,当您使用 MPlayer 时,它不仅会更新一行以显示当前进度,还会更新一行(例如,当您按下暂停键时)。

 =====  PAUSE  =====
A:  79.9 (01:19.9) of 4718.0 ( 1:18:38.0)  0.3% 

您将如何就地更新两行输出?

4

5 回答 5

38

使用回车。'\r' 通常应该可以工作。

于 2010-02-25T18:33:26.867 回答
8

git/progress.c

...
        eol = done ? done : "   \r";
...
                fprintf(stderr, "...%s", ..., eol);
                fflush(stderr);

Git 只是发出一个回车而不是换行,终端将其解释为“移动到第一列”。

于 2010-02-25T18:40:27.163 回答
3

您必须使用另一种方法(如 Curses)来就地更新两行。

ablogaboutcode.com | web.archive.org

...和...

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/curses/rdoc/Curses.html

于 2013-04-01T22:54:32.457 回答
3

我为多行输出更新编写了一个小类:

class ConsoleReset
  # Unix
  # Contains a string to clear the line in the shell
  CLR = "\e[0K"
  # ANSI escape sequence for hiding terminal cursor
  ESC_CURS_INVIS = "\e[?25l"
  # ANSI escape sequence for showing terminal cursor
  ESC_CURS_VIS   = "\e[?25h"
  # ANSI escape sequence for clearing line in terminal
  ESC_R_AND_CLR  = "\r#{CLR}"
  # ANSI escape sequence for going up a line in terminal
  ESC_UP_A_LINE = "\e[1A"

  def initialize
    @first_call = true
  end

  def reset_line(text = '')
    # Initialise ANSI escape string
    escape = ""

    # The number of lines the previous message spanned
    lines = text.strip.lines.count - 1

    # Clear and go up a line
    lines.times { escape += "#{ESC_R_AND_CLR}#{ESC_UP_A_LINE}" }

    # Clear the line that is to be printed on
    # escape += "#{ESC_R_AND_CLR}"

    # Console is clear, we can print!
    STDOUT.print escape if !@first_call
    @first_call = false
    print text
  end

  def hide_cursor
    STDOUT.print(ESC_CURS_INVIS)
  end

  def show_cursor
    STDOUT.print(ESC_CURS_VIS)
  end

  def test
    hide_cursor

    5.times do |i|
      line = ['===========================================']
      (1..10).each do |num|
        line << ["#{num}:\t#{rand_num}"]
      end
      line << ['===========================================']
      line = line.join("\n")
      reset_line(line)
      sleep 1
    end

    show_cursor

    puts ''
  end

  private
    def rand_num
      rand(10 ** rand(10))
    end
end

灵感来自prydonius/spinning_cursor. 示例用法见test方法。

于 2017-02-10T12:51:43.157 回答
-1

Ruby 有许多诅咒库。我相信 rbbcurse 是最维护的。

于 2010-02-25T18:39:59.930 回答