mirror of
https://github.com/rclone/rclone.git
synced 2026-01-06 02:23:24 +00:00
lsf: Add --csv flag for compliant CSV output
This commit is contained in:
@@ -4,6 +4,7 @@ package operations
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
@@ -1368,6 +1369,8 @@ type ListFormat struct {
|
||||
dirSlash bool
|
||||
output []func() string
|
||||
entry fs.DirEntry
|
||||
csv *csv.Writer
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
// SetSeparator changes separator in struct
|
||||
@@ -1380,6 +1383,21 @@ func (l *ListFormat) SetDirSlash(dirSlash bool) {
|
||||
l.dirSlash = dirSlash
|
||||
}
|
||||
|
||||
// SetCSV defines if the output should be csv
|
||||
//
|
||||
// Note that you should call SetSeparator before this if you want a
|
||||
// custom separator
|
||||
func (l *ListFormat) SetCSV(useCSV bool) {
|
||||
if useCSV {
|
||||
l.csv = csv.NewWriter(&l.buf)
|
||||
if l.separator != "" {
|
||||
l.csv.Comma = []rune(l.separator)[0]
|
||||
}
|
||||
} else {
|
||||
l.csv = nil
|
||||
}
|
||||
}
|
||||
|
||||
// SetOutput sets functions used to create files information
|
||||
func (l *ListFormat) SetOutput(output []func() string) {
|
||||
l.output = output
|
||||
@@ -1439,18 +1457,23 @@ func (l *ListFormat) AddMimeType() {
|
||||
|
||||
// AppendOutput adds string generated by specific function to printed output
|
||||
func (l *ListFormat) AppendOutput(functionToAppend func() string) {
|
||||
if len(l.output) > 0 {
|
||||
l.output = append(l.output, func() string { return l.separator })
|
||||
}
|
||||
l.output = append(l.output, functionToAppend)
|
||||
}
|
||||
|
||||
// Format prints information about the DirEntry in the format defined
|
||||
func (l *ListFormat) Format(entry fs.DirEntry) string {
|
||||
func (l *ListFormat) Format(entry fs.DirEntry) (result string) {
|
||||
l.entry = entry
|
||||
var out string
|
||||
var out []string
|
||||
for _, fun := range l.output {
|
||||
out += fun()
|
||||
out = append(out, fun())
|
||||
}
|
||||
return out
|
||||
if l.csv != nil {
|
||||
l.buf.Reset()
|
||||
_ = l.csv.Write(out) // can't fail writing to bytes.Buffer
|
||||
l.csv.Flush()
|
||||
result = strings.TrimRight(l.buf.String(), "\n")
|
||||
} else {
|
||||
result = strings.Join(out, l.separator)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user