Skip to content

Commit 76e00e7

Browse files
authored
added --timestamp option
1 parent 7e8abef commit 76e00e7

File tree

2 files changed

+35
-10
lines changed

2 files changed

+35
-10
lines changed

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
- Compare CSV, TSV, and JSON files for differences
3636
- Human-readable and machine-readable (JSON) output
3737
- JSON output to file with filename and path support
38+
- Optional timestamp in output filenames
3839
- Detects added, removed, and changed rows and columns
3940
- Supports custom key columns for row identity
4041
- Field inclusion/exclusion for focused diffs
@@ -279,6 +280,7 @@ A summary of key options:
279280
| `--output TEXT` | Output format: `readable`, `json`, or `jsonfile` (default: readable) |
280281
| `--outfilename FILE` | File to write JSON output to (used with `--output=jsonfile`) |
281282
| `--outfilepath DIR` | Directory to save the output file (used with `--output=jsonfile`) |
283+
| `--timestamp TEXT` | Include timestamp in output filename: `true` or `false` (default: true) |
282284
| `--fields TEXT` | Comma-separated list of fields to compare (all others ignored) |
283285
| `--ignorefields TEXT` | Comma-separated list of fields to ignore during comparison |
284286
| `--showunchanged` | Show all fields for changed records, not just changed fields |
@@ -312,6 +314,12 @@ db-diff one.csv two.csv --key=Id --output=json
312314
db-diff one.csv two.csv --key=Id --output=jsonfile --outfilename=diffs.json
313315
```
314316

317+
**Save JSON output without timestamp in filename:**
318+
319+
```sh
320+
db-diff one.csv two.csv --key=Id --output=jsonfile --timestamp=false
321+
```
322+
315323
**Compare only specific fields:**
316324

317325
```sh

db_diff/cli.py

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,8 @@ def load(filename: str, key: str, input_format: str, encoding: str = "utf-8") ->
115115
raise click.ClickException(f"Failed to load '{filename}': {e}")
116116

117117
def generate_output_filename(previous: str, current: str, output_file: Optional[str],
118-
output_path: Optional[str], timestamp: Optional[str] = None) -> str:
118+
output_path: Optional[str], timestamp: Optional[str] = None,
119+
use_timestamp: bool = True) -> str:
119120
"""
120121
Generate an output filename for the diff result.
121122
@@ -125,27 +126,33 @@ def generate_output_filename(previous: str, current: str, output_file: Optional[
125126
output_file: User-specified output filename (optional)
126127
output_path: User-specified output directory (optional)
127128
timestamp: Timestamp to use (optional)
129+
use_timestamp: Whether to include timestamp in filename (default: True)
128130
129131
Returns:
130132
Full path to the output file
131133
132134
Raises:
133135
click.ClickException: If the output path doesn't exist
134136
"""
135-
if timestamp is None:
136-
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
137+
timestamp_prefix = ""
138+
if use_timestamp:
139+
if timestamp is None:
140+
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
141+
timestamp_prefix = f"{timestamp}_"
137142

138143
# Extract base filenames without extensions for the comparison files
139144
prev_basename = os.path.splitext(os.path.basename(previous))[0]
140145
curr_basename = os.path.splitext(os.path.basename(current))[0]
141146

142147
if not output_file:
143148
# Default output filename
144-
output_file = f"{timestamp}_diffs_{prev_basename}__VS__{curr_basename}.json"
149+
output_file = f"{timestamp_prefix}diffs_{prev_basename}__vs__{curr_basename}.json"
145150
else:
146-
# Append the user-specified filename to the timestamp
147-
base_name = os.path.splitext(output_file)[0] # Remove extension if present
148-
output_file = f"{timestamp}_diffs_{base_name}.json"
151+
# Prepend the timestamp to the user-specified filename if needed
152+
output_file = f"{timestamp_prefix}diffs_{output_file}"
153+
# Ensure the output file has a .json extension
154+
if not output_file.endswith('.json'):
155+
output_file += '.json'
149156

150157
# Handle output path
151158
if output_path:
@@ -170,6 +177,8 @@ def generate_output_filename(previous: str, current: str, output_file: Optional[
170177
"\n db-diff old.csv new.csv --key=Id\n"
171178
"\n Output to JSON file:\n"
172179
"\n db-diff old.csv new.csv --output=jsonfile --outfilename=diff.json\n"
180+
"\n Output without timestamp in filename:\n"
181+
"\n db-diff old.csv new.csv --output=jsonfile --timestamp=false\n"
173182
"\n Compare only specific fields:\n"
174183
"\n db-diff old.csv new.csv --fields=Id,Name,Email\n"
175184
"\n Ignore specific fields:\n"
@@ -206,7 +215,7 @@ def generate_output_filename(previous: str, current: str, output_file: Optional[
206215
"output_file",
207216
type=click.Path(file_okay=True, dir_okay=False, writable=True, resolve_path=True),
208217
default=None,
209-
help="File to write JSON output to. [default: YYYY-MM-DD_HH-MM-SS_diffs_file1name__VS__file2name.json]",
218+
help="Specify custom filename. [default: diffs_<filename1__vs__filename2>.json]",
210219
)
211220
@click.option(
212221
"--outfilepath",
@@ -264,11 +273,18 @@ def generate_output_filename(previous: str, current: str, output_file: Optional[
264273
is_flag=True,
265274
help="Enable verbose output.",
266275
)
276+
@click.option(
277+
"--timestamp",
278+
type=click.Choice(["true", "false"], case_sensitive=False),
279+
default="false",
280+
show_default=True,
281+
help="Add timestamp to filename: YYYY-MM-DD_HH-MM-SS_diffs_<filename>.json",
282+
)
267283
@click.version_option()
268284
def cli(
269285
previous, current, key, input_format,
270286
show_unchanged, encoding, output, output_file, output_path,
271-
fields, ignorefields, streaming, listfields, verbose
287+
fields, ignorefields, streaming, listfields, verbose, timestamp
272288
):
273289
"""Compare the differences between two CSV or JSON files."""
274290
# Set logging level based on verbosity
@@ -323,7 +339,8 @@ def cli(
323339
# Set default output filename if needed
324340
if output == "jsonfile":
325341
try:
326-
output_file = generate_output_filename(previous, current, output_file, output_path)
342+
use_timestamp = timestamp.lower() == "true"
343+
output_file = generate_output_filename(previous, current, output_file, output_path, use_timestamp=use_timestamp)
327344
except Exception as e:
328345
raise click.ClickException(f"Failed to generate output filename: {e}")
329346

0 commit comments

Comments
 (0)