...

Source file src/github.com/docker/cli/cli/command/formatter/tabwriter/tabwriter.go

Documentation: github.com/docker/cli/cli/command/formatter/tabwriter

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package tabwriter implements a write filter (tabwriter.Writer) that
     6  // translates tabbed columns in input into properly aligned text.
     7  //
     8  // The package is using the Elastic Tabstops algorithm described at
     9  // http://nickgravgaard.com/elastictabstops/index.html.
    10  //
    11  // The text/tabwriter package is frozen and is not accepting new features.
    12  
    13  // based on https://github.com/golang/go/blob/master/src/text/tabwriter/tabwriter.go Last modified 690ac40 on 31 Jan
    14  
    15  //nolint:gocyclo,nakedret,stylecheck,unused // ignore linting errors, so that we can stick close to upstream
    16  package tabwriter
    17  
    18  import (
    19  	"io"
    20  
    21  	"github.com/mattn/go-runewidth"
    22  )
    23  
    24  // ----------------------------------------------------------------------------
    25  // Filter implementation
    26  
    27  // A cell represents a segment of text terminated by tabs or line breaks.
    28  // The text itself is stored in a separate buffer; cell only describes the
    29  // segment's size in bytes, its width in runes, and whether it's an htab
    30  // ('\t') terminated cell.
    31  type cell struct {
    32  	size  int  // cell size in bytes
    33  	width int  // cell width in runes
    34  	htab  bool // true if the cell is terminated by an htab ('\t')
    35  }
    36  
    37  // A Writer is a filter that inserts padding around tab-delimited
    38  // columns in its input to align them in the output.
    39  //
    40  // The Writer treats incoming bytes as UTF-8-encoded text consisting
    41  // of cells terminated by horizontal ('\t') or vertical ('\v') tabs,
    42  // and newline ('\n') or formfeed ('\f') characters; both newline and
    43  // formfeed act as line breaks.
    44  //
    45  // Tab-terminated cells in contiguous lines constitute a column. The
    46  // Writer inserts padding as needed to make all cells in a column have
    47  // the same width, effectively aligning the columns. It assumes that
    48  // all characters have the same width, except for tabs for which a
    49  // tabwidth must be specified. Column cells must be tab-terminated, not
    50  // tab-separated: non-tab terminated trailing text at the end of a line
    51  // forms a cell but that cell is not part of an aligned column.
    52  // For instance, in this example (where | stands for a horizontal tab):
    53  //
    54  //	aaaa|bbb|d
    55  //	aa  |b  |dd
    56  //	a   |
    57  //	aa  |cccc|eee
    58  //
    59  // the b and c are in distinct columns (the b column is not contiguous
    60  // all the way). The d and e are not in a column at all (there's no
    61  // terminating tab, nor would the column be contiguous).
    62  //
    63  // The Writer assumes that all Unicode code points have the same width;
    64  // this may not be true in some fonts or if the string contains combining
    65  // characters.
    66  //
    67  // If DiscardEmptyColumns is set, empty columns that are terminated
    68  // entirely by vertical (or "soft") tabs are discarded. Columns
    69  // terminated by horizontal (or "hard") tabs are not affected by
    70  // this flag.
    71  //
    72  // If a Writer is configured to filter HTML, HTML tags and entities
    73  // are passed through. The widths of tags and entities are
    74  // assumed to be zero (tags) and one (entities) for formatting purposes.
    75  //
    76  // A segment of text may be escaped by bracketing it with Escape
    77  // characters. The tabwriter passes escaped text segments through
    78  // unchanged. In particular, it does not interpret any tabs or line
    79  // breaks within the segment. If the StripEscape flag is set, the
    80  // Escape characters are stripped from the output; otherwise they
    81  // are passed through as well. For the purpose of formatting, the
    82  // width of the escaped text is always computed excluding the Escape
    83  // characters.
    84  //
    85  // The formfeed character acts like a newline but it also terminates
    86  // all columns in the current line (effectively calling Flush). Tab-
    87  // terminated cells in the next line start new columns. Unless found
    88  // inside an HTML tag or inside an escaped text segment, formfeed
    89  // characters appear as newlines in the output.
    90  //
    91  // The Writer must buffer input internally, because proper spacing
    92  // of one line may depend on the cells in future lines. Clients must
    93  // call Flush when done calling Write.
    94  type Writer struct {
    95  	// configuration
    96  	output   io.Writer
    97  	minwidth int
    98  	tabwidth int
    99  	padding  int
   100  	padbytes [8]byte
   101  	flags    uint
   102  
   103  	// current state
   104  	buf     []byte   // collected text excluding tabs or line breaks
   105  	pos     int      // buffer position up to which cell.width of incomplete cell has been computed
   106  	cell    cell     // current incomplete cell; cell.width is up to buf[pos] excluding ignored sections
   107  	endChar byte     // terminating char of escaped sequence (Escape for escapes, '>', ';' for HTML tags/entities, or 0)
   108  	lines   [][]cell // list of lines; each line is a list of cells
   109  	widths  []int    // list of column widths in runes - re-used during formatting
   110  }
   111  
   112  // addLine adds a new line.
   113  // flushed is a hint indicating whether the underlying writer was just flushed.
   114  // If so, the previous line is not likely to be a good indicator of the new line's cells.
   115  func (b *Writer) addLine(flushed bool) {
   116  	// Grow slice instead of appending,
   117  	// as that gives us an opportunity
   118  	// to re-use an existing []cell.
   119  	if n := len(b.lines) + 1; n <= cap(b.lines) {
   120  		b.lines = b.lines[:n]
   121  		b.lines[n-1] = b.lines[n-1][:0]
   122  	} else {
   123  		b.lines = append(b.lines, nil)
   124  	}
   125  
   126  	if !flushed {
   127  		// The previous line is probably a good indicator
   128  		// of how many cells the current line will have.
   129  		// If the current line's capacity is smaller than that,
   130  		// abandon it and make a new one.
   131  		if n := len(b.lines); n >= 2 {
   132  			if prev := len(b.lines[n-2]); prev > cap(b.lines[n-1]) {
   133  				b.lines[n-1] = make([]cell, 0, prev)
   134  			}
   135  		}
   136  	}
   137  }
   138  
   139  // Reset the current state.
   140  func (b *Writer) reset() {
   141  	b.buf = b.buf[:0]
   142  	b.pos = 0
   143  	b.cell = cell{}
   144  	b.endChar = 0
   145  	b.lines = b.lines[0:0]
   146  	b.widths = b.widths[0:0]
   147  	b.addLine(true)
   148  }
   149  
   150  // Internal representation (current state):
   151  //
   152  // - all text written is appended to buf; tabs and line breaks are stripped away
   153  // - at any given time there is a (possibly empty) incomplete cell at the end
   154  //   (the cell starts after a tab or line break)
   155  // - cell.size is the number of bytes belonging to the cell so far
   156  // - cell.width is text width in runes of that cell from the start of the cell to
   157  //   position pos; html tags and entities are excluded from this width if html
   158  //   filtering is enabled
   159  // - the sizes and widths of processed text are kept in the lines list
   160  //   which contains a list of cells for each line
   161  // - the widths list is a temporary list with current widths used during
   162  //   formatting; it is kept in Writer because it's re-used
   163  //
   164  //                    |<---------- size ---------->|
   165  //                    |                            |
   166  //                    |<- width ->|<- ignored ->|  |
   167  //                    |           |             |  |
   168  // [---processed---tab------------<tag>...</tag>...]
   169  // ^                  ^                         ^
   170  // |                  |                         |
   171  // buf                start of incomplete cell  pos
   172  
   173  // Formatting can be controlled with these flags.
   174  const (
   175  	// Ignore html tags and treat entities (starting with '&'
   176  	// and ending in ';') as single characters (width = 1).
   177  	FilterHTML uint = 1 << iota
   178  
   179  	// Strip Escape characters bracketing escaped text segments
   180  	// instead of passing them through unchanged with the text.
   181  	StripEscape
   182  
   183  	// Force right-alignment of cell content.
   184  	// Default is left-alignment.
   185  	AlignRight
   186  
   187  	// Handle empty columns as if they were not present in
   188  	// the input in the first place.
   189  	DiscardEmptyColumns
   190  
   191  	// Always use tabs for indentation columns (i.e., padding of
   192  	// leading empty cells on the left) independent of padchar.
   193  	TabIndent
   194  
   195  	// Print a vertical bar ('|') between columns (after formatting).
   196  	// Discarded columns appear as zero-width columns ("||").
   197  	Debug
   198  )
   199  
   200  // A Writer must be initialized with a call to Init. The first parameter (output)
   201  // specifies the filter output. The remaining parameters control the formatting:
   202  //
   203  //	minwidth	minimal cell width including any padding
   204  //	tabwidth	width of tab characters (equivalent number of spaces)
   205  //	padding		the padding added to a cell before computing its width
   206  //	padchar		ASCII char used for padding
   207  //			if padchar == '\t', the Writer will assume that the
   208  //			width of a '\t' in the formatted output is tabwidth,
   209  //			and cells are left-aligned independent of align_left
   210  //			(for correct-looking results, tabwidth must correspond
   211  //			to the tab width in the viewer displaying the result)
   212  //	flags		formatting control
   213  func (b *Writer) Init(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer {
   214  	if minwidth < 0 || tabwidth < 0 || padding < 0 {
   215  		panic("negative minwidth, tabwidth, or padding")
   216  	}
   217  	b.output = output
   218  	b.minwidth = minwidth
   219  	b.tabwidth = tabwidth
   220  	b.padding = padding
   221  	for i := range b.padbytes {
   222  		b.padbytes[i] = padchar
   223  	}
   224  	if padchar == '\t' {
   225  		// tab padding enforces left-alignment
   226  		flags &^= AlignRight
   227  	}
   228  	b.flags = flags
   229  
   230  	b.reset()
   231  
   232  	return b
   233  }
   234  
   235  // debugging support (keep code around)
   236  func (b *Writer) dump() {
   237  	pos := 0
   238  	for i, line := range b.lines {
   239  		print("(", i, ") ")
   240  		for _, c := range line {
   241  			print("[", string(b.buf[pos:pos+c.size]), "]")
   242  			pos += c.size
   243  		}
   244  		print("\n")
   245  	}
   246  	print("\n")
   247  }
   248  
   249  // local error wrapper so we can distinguish errors we want to return
   250  // as errors from genuine panics (which we don't want to return as errors)
   251  type osError struct {
   252  	err error
   253  }
   254  
   255  func (b *Writer) write0(buf []byte) {
   256  	n, err := b.output.Write(buf)
   257  	if n != len(buf) && err == nil {
   258  		err = io.ErrShortWrite
   259  	}
   260  	if err != nil {
   261  		panic(osError{err})
   262  	}
   263  }
   264  
   265  func (b *Writer) writeN(src []byte, n int) {
   266  	for n > len(src) {
   267  		b.write0(src)
   268  		n -= len(src)
   269  	}
   270  	b.write0(src[0:n])
   271  }
   272  
   273  var (
   274  	newline = []byte{'\n'}
   275  	tabs    = []byte("\t\t\t\t\t\t\t\t")
   276  )
   277  
   278  func (b *Writer) writePadding(textw, cellw int, useTabs bool) {
   279  	if b.padbytes[0] == '\t' || useTabs {
   280  		// padding is done with tabs
   281  		if b.tabwidth == 0 {
   282  			return // tabs have no width - can't do any padding
   283  		}
   284  		// make cellw the smallest multiple of b.tabwidth
   285  		cellw = (cellw + b.tabwidth - 1) / b.tabwidth * b.tabwidth
   286  		n := cellw - textw // amount of padding
   287  		if n < 0 {
   288  			panic("internal error")
   289  		}
   290  		b.writeN(tabs, (n+b.tabwidth-1)/b.tabwidth)
   291  		return
   292  	}
   293  
   294  	// padding is done with non-tab characters
   295  	b.writeN(b.padbytes[0:], cellw-textw)
   296  }
   297  
   298  var vbar = []byte{'|'}
   299  
   300  func (b *Writer) writeLines(pos0 int, line0, line1 int) (pos int) {
   301  	pos = pos0
   302  	for i := line0; i < line1; i++ {
   303  		line := b.lines[i]
   304  
   305  		// if TabIndent is set, use tabs to pad leading empty cells
   306  		useTabs := b.flags&TabIndent != 0
   307  
   308  		for j, c := range line {
   309  			if j > 0 && b.flags&Debug != 0 {
   310  				// indicate column break
   311  				b.write0(vbar)
   312  			}
   313  
   314  			if c.size == 0 {
   315  				// empty cell
   316  				if j < len(b.widths) {
   317  					b.writePadding(c.width, b.widths[j], useTabs)
   318  				}
   319  			} else {
   320  				// non-empty cell
   321  				useTabs = false
   322  				if b.flags&AlignRight == 0 { // align left
   323  					b.write0(b.buf[pos : pos+c.size])
   324  					pos += c.size
   325  					if j < len(b.widths) {
   326  						b.writePadding(c.width, b.widths[j], false)
   327  					}
   328  				} else { // align right
   329  					if j < len(b.widths) {
   330  						b.writePadding(c.width, b.widths[j], false)
   331  					}
   332  					b.write0(b.buf[pos : pos+c.size])
   333  					pos += c.size
   334  				}
   335  			}
   336  		}
   337  
   338  		if i+1 == len(b.lines) {
   339  			// last buffered line - we don't have a newline, so just write
   340  			// any outstanding buffered data
   341  			b.write0(b.buf[pos : pos+b.cell.size])
   342  			pos += b.cell.size
   343  		} else {
   344  			// not the last line - write newline
   345  			b.write0(newline)
   346  		}
   347  	}
   348  	return
   349  }
   350  
   351  // Format the text between line0 and line1 (excluding line1); pos
   352  // is the buffer position corresponding to the beginning of line0.
   353  // Returns the buffer position corresponding to the beginning of
   354  // line1 and an error, if any.
   355  func (b *Writer) format(pos0 int, line0, line1 int) (pos int) {
   356  	pos = pos0
   357  	column := len(b.widths)
   358  	for this := line0; this < line1; this++ {
   359  		line := b.lines[this]
   360  
   361  		if column >= len(line)-1 {
   362  			continue
   363  		}
   364  		// cell exists in this column => this line
   365  		// has more cells than the previous line
   366  		// (the last cell per line is ignored because cells are
   367  		// tab-terminated; the last cell per line describes the
   368  		// text before the newline/formfeed and does not belong
   369  		// to a column)
   370  
   371  		// print unprinted lines until beginning of block
   372  		pos = b.writeLines(pos, line0, this)
   373  		line0 = this
   374  
   375  		// column block begin
   376  		width := b.minwidth // minimal column width
   377  		discardable := true // true if all cells in this column are empty and "soft"
   378  		for ; this < line1; this++ {
   379  			line = b.lines[this]
   380  			if column >= len(line)-1 {
   381  				break
   382  			}
   383  			// cell exists in this column
   384  			c := line[column]
   385  			// update width
   386  			if w := c.width + b.padding; w > width {
   387  				width = w
   388  			}
   389  			// update discardable
   390  			if c.width > 0 || c.htab {
   391  				discardable = false
   392  			}
   393  		}
   394  		// column block end
   395  
   396  		// discard empty columns if necessary
   397  		if discardable && b.flags&DiscardEmptyColumns != 0 {
   398  			width = 0
   399  		}
   400  
   401  		// format and print all columns to the right of this column
   402  		// (we know the widths of this column and all columns to the left)
   403  		b.widths = append(b.widths, width) // push width
   404  		pos = b.format(pos, line0, this)
   405  		b.widths = b.widths[0 : len(b.widths)-1] // pop width
   406  		line0 = this
   407  	}
   408  
   409  	// print unprinted lines until end
   410  	return b.writeLines(pos, line0, line1)
   411  }
   412  
   413  // Append text to current cell.
   414  func (b *Writer) append(text []byte) {
   415  	b.buf = append(b.buf, text...)
   416  	b.cell.size += len(text)
   417  }
   418  
   419  // Update the cell width.
   420  func (b *Writer) updateWidth() {
   421  	b.cell.width += runewidth.StringWidth(string(b.buf[b.pos:]))
   422  	b.pos = len(b.buf)
   423  }
   424  
   425  // To escape a text segment, bracket it with Escape characters.
   426  // For instance, the tab in this string "Ignore this tab: \xff\t\xff"
   427  // does not terminate a cell and constitutes a single character of
   428  // width one for formatting purposes.
   429  //
   430  // The value 0xff was chosen because it cannot appear in a valid UTF-8 sequence.
   431  const Escape = '\xff'
   432  
   433  // Start escaped mode.
   434  func (b *Writer) startEscape(ch byte) {
   435  	switch ch {
   436  	case Escape:
   437  		b.endChar = Escape
   438  	case '<':
   439  		b.endChar = '>'
   440  	case '&':
   441  		b.endChar = ';'
   442  	}
   443  }
   444  
   445  // Terminate escaped mode. If the escaped text was an HTML tag, its width
   446  // is assumed to be zero for formatting purposes; if it was an HTML entity,
   447  // its width is assumed to be one. In all other cases, the width is the
   448  // unicode width of the text.
   449  func (b *Writer) endEscape() {
   450  	switch b.endChar {
   451  	case Escape:
   452  		b.updateWidth()
   453  		if b.flags&StripEscape == 0 {
   454  			b.cell.width -= 2 // don't count the Escape chars
   455  		}
   456  	case '>': // tag of zero width
   457  	case ';':
   458  		b.cell.width++ // entity, count as one rune
   459  	}
   460  	b.pos = len(b.buf)
   461  	b.endChar = 0
   462  }
   463  
   464  // Terminate the current cell by adding it to the list of cells of the
   465  // current line. Returns the number of cells in that line.
   466  func (b *Writer) terminateCell(htab bool) int {
   467  	b.cell.htab = htab
   468  	line := &b.lines[len(b.lines)-1]
   469  	*line = append(*line, b.cell)
   470  	b.cell = cell{}
   471  	return len(*line)
   472  }
   473  
   474  func (b *Writer) handlePanic(err *error, op string) {
   475  	if e := recover(); e != nil {
   476  		if op == "Flush" {
   477  			// If Flush ran into a panic, we still need to reset.
   478  			b.reset()
   479  		}
   480  		if nerr, ok := e.(osError); ok {
   481  			*err = nerr.err
   482  			return
   483  		}
   484  		panic("tabwriter: panic during " + op)
   485  	}
   486  }
   487  
   488  // Flush should be called after the last call to Write to ensure
   489  // that any data buffered in the Writer is written to output. Any
   490  // incomplete escape sequence at the end is considered
   491  // complete for formatting purposes.
   492  func (b *Writer) Flush() error {
   493  	return b.flush()
   494  }
   495  
   496  // flush is the internal version of Flush, with a named return value which we
   497  // don't want to expose.
   498  func (b *Writer) flush() (err error) {
   499  	defer b.handlePanic(&err, "Flush")
   500  	b.flushNoDefers()
   501  	return nil
   502  }
   503  
   504  // flushNoDefers is like flush, but without a deferred handlePanic call. This
   505  // can be called from other methods which already have their own deferred
   506  // handlePanic calls, such as Write, and avoid the extra defer work.
   507  func (b *Writer) flushNoDefers() {
   508  	// add current cell if not empty
   509  	if b.cell.size > 0 {
   510  		if b.endChar != 0 {
   511  			// inside escape - terminate it even if incomplete
   512  			b.endEscape()
   513  		}
   514  		b.terminateCell(false)
   515  	}
   516  
   517  	// format contents of buffer
   518  	b.format(0, 0, len(b.lines))
   519  	b.reset()
   520  }
   521  
   522  var hbar = []byte("---\n")
   523  
   524  // Write writes buf to the writer b.
   525  // The only errors returned are ones encountered
   526  // while writing to the underlying output stream.
   527  func (b *Writer) Write(buf []byte) (n int, err error) {
   528  	defer b.handlePanic(&err, "Write")
   529  
   530  	// split text into cells
   531  	n = 0
   532  	for i, ch := range buf {
   533  		if b.endChar == 0 {
   534  			// outside escape
   535  			switch ch {
   536  			case '\t', '\v', '\n', '\f':
   537  				// end of cell
   538  				b.append(buf[n:i])
   539  				b.updateWidth()
   540  				n = i + 1 // ch consumed
   541  				ncells := b.terminateCell(ch == '\t')
   542  				if ch == '\n' || ch == '\f' {
   543  					// terminate line
   544  					b.addLine(ch == '\f')
   545  					if ch == '\f' || ncells == 1 {
   546  						// A '\f' always forces a flush. Otherwise, if the previous
   547  						// line has only one cell which does not have an impact on
   548  						// the formatting of the following lines (the last cell per
   549  						// line is ignored by format()), thus we can flush the
   550  						// Writer contents.
   551  						b.flushNoDefers()
   552  						if ch == '\f' && b.flags&Debug != 0 {
   553  							// indicate section break
   554  							b.write0(hbar)
   555  						}
   556  					}
   557  				}
   558  
   559  			case Escape:
   560  				// start of escaped sequence
   561  				b.append(buf[n:i])
   562  				b.updateWidth()
   563  				n = i
   564  				if b.flags&StripEscape != 0 {
   565  					n++ // strip Escape
   566  				}
   567  				b.startEscape(Escape)
   568  
   569  			case '<', '&':
   570  				// possibly an html tag/entity
   571  				if b.flags&FilterHTML != 0 {
   572  					// begin of tag/entity
   573  					b.append(buf[n:i])
   574  					b.updateWidth()
   575  					n = i
   576  					b.startEscape(ch)
   577  				}
   578  			}
   579  		} else if ch == b.endChar {
   580  			// inside escape
   581  			// end of tag/entity
   582  			j := i + 1
   583  			if ch == Escape && b.flags&StripEscape != 0 {
   584  				j = i // strip Escape
   585  			}
   586  			b.append(buf[n:j])
   587  			n = i + 1 // ch consumed
   588  			b.endEscape()
   589  		}
   590  	}
   591  
   592  	// append leftover text
   593  	b.append(buf[n:])
   594  	n = len(buf)
   595  	return
   596  }
   597  
   598  // NewWriter allocates and initializes a new tabwriter.Writer.
   599  // The parameters are the same as for the Init function.
   600  func NewWriter(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer {
   601  	return new(Writer).Init(output, minwidth, tabwidth, padding, padchar, flags)
   602  }
   603  

View as plain text