Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,42 @@ With `--all`:

The CLI retries a request that gets HTTP 429 (rate limited), a 5xx error, or a network error, up to 3 attempts in total. It waits about 1 second before the first retry and longer before each later one, up to 10 seconds. On a 429 it waits for the time the API gives in `X-RateLimit-RetryAfter`, also up to 10 seconds. Each request, with its retries, times out after 30 seconds. If the last attempt still fails, the command reports the error.

## Output Formats

Most `fcs` list and get commands accept `--output` (default `table`):

| Format | Description |
|--------|-------------|
| `table` | Aligned columns for terminals; long values are truncated (see `--max-col-width`, `--no-truncate`) |
| `json` | Full API objects as an indented JSON array |
| `jsonl` | One JSON object per line, for piping to `jq` |
| `toon` | Token-Oriented Object Notation, a compact encoding of the JSON output |
| `csv` | CSV with RFC 4180-style quoting and the same columns as `table` |

The `csv` format writes a header row followed by one row per item, with LF
line endings. Values that contain commas, double quotes, or line breaks are
quoted. Values are never truncated, so `--max-col-width` and `--no-truncate`
have no effect. `--columns` and `--no-headers` apply to CSV as they do to the
table; with `--output csv`, a `--columns` list that matches no column is an
error that lists the valid names. An empty result prints only the header row.
The `fcs doctor` command does not support `csv`.

```bash
falcon fcs iom list --output csv > iom.csv
falcon fcs assets list --output csv --columns id,name,provider --no-headers
```

> **Caution:** CSV values are written exactly as returned by the API. A cell

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Really appreciate the caution note here. One related idea: when Excel on Windows opens a CSV by double-click it assumes a legacy code page, so non-ASCII values (like the 東京 / café cases in the tests) can show up garbled. A short note about importing as UTF-8, or an opt-in BOM flag, might save someone a confusing moment. Totally fine as a follow-up.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a note in f3c4e81: the output is UTF-8 without a BOM, and Excel on Windows users should use Data > From Text/CSV and pick UTF-8 (65001). I left out a BOM because it shows up as stray bytes on the first header for head/cut and in older tools. An opt-in --bom flag can come later if people ask.

> that begins with `=`, `+`, `-`, or `@` may be treated as a formula when the
> file is opened in a spreadsheet application. Treat CSV exported from tenant
> data as untrusted input, and import it as text when you open it in a
> spreadsheet.

> **Note:** CSV output is UTF-8 without a byte order mark. Excel on Windows
> may show non-ASCII characters incorrectly when the file is opened by
> double-click. Use **Data > From Text/CSV** and choose UTF-8 (65001) as the
> file origin instead.

## Authentication

The CLI uses CrowdStrike API credentials (OAuth2 client ID and secret). Configure them interactively:
Expand Down
10 changes: 5 additions & 5 deletions pkg/cmdutil/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ func AddSortFlag(cmd *cobra.Command, p *string) {
cmd.Flags().StringVar(p, "sort", "", "Sort expression (e.g. \"severity|desc\")")
}

// AddOutputFlag adds an --output flag (table|json|jsonl|toon).
// AddOutputFlag adds an --output flag (table|json|jsonl|toon|csv).
func AddOutputFlag(cmd *cobra.Command, p *string) {
cmd.Flags().StringVar(p, "output", "table", "Output format: table, json, jsonl, or toon")
cmd.Flags().StringVar(p, "output", "table", "Output format: table, json, jsonl, toon, or csv")
}

// AddIDsFlag adds an --ids flag for multi-ID commands.
Expand All @@ -96,10 +96,10 @@ type TableFormattingOptions struct {

// AddTableFormattingFlags adds --no-truncate, --max-col-width, --columns, and --no-headers flags.
func AddTableFormattingFlags(cmd *cobra.Command, opts *TableFormattingOptions) {
cmd.Flags().BoolVar(&opts.NoTruncate, "no-truncate", false, "Disable column value truncation")
cmd.Flags().IntVar(&opts.MaxColWidth, "max-col-width", 50, "Maximum column width before truncation (0 = unlimited)")
cmd.Flags().BoolVar(&opts.NoTruncate, "no-truncate", false, "Disable column value truncation (csv never truncates)")
cmd.Flags().IntVar(&opts.MaxColWidth, "max-col-width", 50, "Maximum column width before truncation (0 = unlimited; ignored for csv)")
cmd.Flags().StringVar(&opts.Columns, "columns", "", "Comma-separated list of columns to display (e.g. id,name,provider)")
cmd.Flags().BoolVar(&opts.NoHeaders, "no-headers", false, "Suppress table header row")
cmd.Flags().BoolVar(&opts.NoHeaders, "no-headers", false, "Suppress header row (table and csv)")
}

// ToOutputTableOptions converts TableFormattingOptions to output.TableOptions.
Expand Down
117 changes: 117 additions & 0 deletions pkg/output/csv.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// Copyright (c) 2026 CrowdStrike, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

package output

import (
"encoding/csv"
"errors"
"fmt"
"io"
"reflect"
"strings"
)

// ErrNoTableDefinition is returned when a format that renders columns (such
// as CSV) is requested from a command that has no TableDefinition.
var ErrNoTableDefinition = errors.New("this command does not support column-based output")

// ErrUnknownColumns is returned by the CSV printer when --columns names no
// known column, so a typo fails loudly instead of producing an empty file.
var ErrUnknownColumns = errors.New("no known columns selected")

// csvPrinter writes one record per item using the TableDefinition headers and
// RowFunc, with RFC 4180-style quoting and LF line endings. Values are written
// in full: the truncation and width options of the table format are ignored.
// Columns and NoHeaders are honoured.
type csvPrinter struct {
def *TableDefinition
opts *TableOptions
}

func (p *csvPrinter) Print(w io.Writer, data any) error {
if p.def == nil {
return fmt.Errorf("--output %s: %w", FormatCSV, ErrNoTableDefinition)
}

activeIdx := columnIndices(p.def.Headers, p.opts.Columns)
if len(activeIdx) == 0 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tiny nit, and it matches the table printer, so feel free to ignore: if --columns names only unknown columns we return with no output and no error. For CSV in a script, a short error listing the valid column names might be a little friendlier to debug.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed in f3c4e81. With --output csv, a --columns list that matches nothing now returns ErrUnknownColumns and lists the valid names, e.g. --columns bogus: no known columns selected (valid columns: id, name, type, provider, region, account), and exits non-zero. I kept it to CSV for this PR. The table printer has the same problem (it prints blank lines), and I'd rather fix that in its own PR.

valid := make([]string, len(p.def.Headers))
for i, h := range p.def.Headers {
valid[i] = strings.ToLower(h)
}
return fmt.Errorf("--columns %s: %w (valid columns: %s)",
strings.Join(p.opts.Columns, ","), ErrUnknownColumns, strings.Join(valid, ", "))
}

cw := csv.NewWriter(w)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small thought, very optional: RFC 4180 specifies CRLF record endings, and csv.Writer defaults to LF. Most parsers handle LF fine, so we could set cw.UseCRLF = true to match the docs exactly, or just soften the docs to "RFC 4180-style quoting". Either seems fine to me.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went with softening the docs (f3c4e81). They now say "RFC 4180-style quoting" with LF line endings, and so does the type comment. This output mostly goes to stdout and through pipes, where CRLF leaves a trailing \r on the last field for cut/awk/grep. pandas, DuckDB and csv.Reader all read LF without any trouble.

record := make([]string, len(activeIdx))
write := func(cols []string) error {
for j, i := range activeIdx {
record[j] = ""
if i < len(cols) {
record[j] = cols[i]
}
}
// csv.Writer renders a lone empty field as a blank line, which
// readers (including csv.Reader) skip, dropping the row. Write an
// explicit empty quoted field instead.
if len(record) == 1 && record[0] == "" {
cw.Flush()
if err := cw.Error(); err != nil {
return err
}
_, err := io.WriteString(w, `""`+"\n")
return err
}
return cw.Write(record)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I hit one small edge case here while testing: when the record has exactly one field and it's empty (e.g. --columns resource_id on an item with no resource ID), csv.Writer writes a bare blank line instead of "". Many readers, including csv.Reader and pandas by default, skip blank lines, so the row can quietly go missing and the rows after it shift up.

One possible approach, if it seems reasonable:

if len(record) == 1 && record[0] == "" {
	cw.Flush()
	if err := cw.Error(); err != nil {
		return err
	}
	_, err := io.WriteString(w, "\"\"\n")
	return err
}
return cw.Write(record)

A matching test case might be nice too, e.g. Columns: []string{"note"} with Note: "", expecting "NOTE\n\"\"\n".

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in f3c4e81. I reproduced it against a live tenant: fcs assets list --output csv --columns name (every asset there has an empty name) wrote NAME\n\n\n..., and csv.Reader read back 1 record out of 6. pandas drops those rows too. A one-field record with an empty value is now written as "". I added your test case, plus a csv.Reader round-trip test with a single column, which fails without the fix.

}

if !p.opts.NoHeaders {
if err := write(p.def.Headers); err != nil {
return fmt.Errorf("writing CSV header: %w", err)
}
}

v := reflect.ValueOf(data)
if v.Kind() == reflect.Pointer {
v = v.Elem()
}
switch {
case !v.IsValid():
// nil data or nil pointer: header only.
case v.Kind() == reflect.Slice:
for i := 0; i < v.Len(); i++ {
if err := write(p.def.RowFunc(v.Index(i).Interface())); err != nil {
return fmt.Errorf("writing CSV row: %w", err)
}
}
default:
if err := write(p.def.RowFunc(data)); err != nil {
return fmt.Errorf("writing CSV row: %w", err)
}
}

cw.Flush()
if err := cw.Error(); err != nil {
return fmt.Errorf("writing CSV: %w", err)
}
return nil
}
Loading
Loading