neatfile 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
neatfile/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """NeatFile."""
2
+
3
+ from .config import settings
4
+
5
+ __all__ = ["settings"]
neatfile/cli.py ADDED
@@ -0,0 +1,537 @@
1
+ """The neatfile cli."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ from pathlib import Path # noqa: TC003
7
+ from typing import Annotated
8
+
9
+ import cappa
10
+ from rich.markdown import Markdown
11
+ from rich.traceback import install
12
+
13
+ from neatfile import settings
14
+ from neatfile.commands import execute_command
15
+ from neatfile.config import SettingsManager
16
+ from neatfile.constants import (
17
+ DEFAULT_CONFIG_PATH,
18
+ USER_CONFIG_PATH,
19
+ PrintLevel,
20
+ Separator,
21
+ TransformCase,
22
+ )
23
+ from neatfile.utils import console, pp
24
+ from neatfile.views import print_debug
25
+
26
+
27
+ def config_subcommand(neatfile: NeatFile) -> None:
28
+ """Configure settings based on the provided command and arguments.
29
+
30
+ Update the global settings object with values from the command line arguments and configuration file. Handle project-specific settings if a project is specified.
31
+
32
+ Args:
33
+ neatfile (NeatFile): The main CLI application object containing command and configuration options.
34
+ """
35
+ pp.configure(
36
+ debug=neatfile.verbosity in {PrintLevel.DEBUG, PrintLevel.TRACE},
37
+ trace=neatfile.verbosity == PrintLevel.TRACE,
38
+ )
39
+
40
+ # Apply command-specific settings
41
+ cli_settings = {
42
+ "subcommand": neatfile.command.__class__.__name__.lower(),
43
+ "confirm_changes": getattr(neatfile.command, "confirm_changes", False),
44
+ "date": getattr(neatfile.command, "date", None),
45
+ "date_format": getattr(neatfile.command, "date_format", None),
46
+ "date_only": getattr(neatfile.command, "date_only", False),
47
+ "dryrun": getattr(neatfile, "dryrun", False),
48
+ "files": getattr(neatfile.command, "files", []),
49
+ "force": getattr(neatfile.command, "force", False),
50
+ "full_tree": getattr(neatfile.command, "full_tree", False),
51
+ "overwrite": getattr(neatfile.command, "overwrite", False),
52
+ "separator": getattr(neatfile.command, "separator", None),
53
+ "transform_case": getattr(neatfile.command, "transform_case", None),
54
+ "user_terms": getattr(neatfile.command, "user_terms", ()),
55
+ "file_search_depth": getattr(neatfile.command, "file_search_depth", None),
56
+ }
57
+
58
+ SettingsManager.apply_cli_settings(cli_settings)
59
+
60
+ # Configure project if specified
61
+ if project_name := getattr(neatfile, "project_name", ""):
62
+ try:
63
+ SettingsManager.apply_project_settings(project_name)
64
+ except ValueError as e:
65
+ pp.error(str(e))
66
+ raise cappa.Exit(code=1) from e
67
+
68
+ if pp.is_trace:
69
+ print_debug(
70
+ custom=[{"Settings": settings.to_dict()}, {"neatfile": neatfile.__dict__}],
71
+ envar_prefix="neatfile",
72
+ packages=["questionary", "cappa", "dynaconf", "rich", "spacy"],
73
+ )
74
+
75
+
76
+ @cappa.command(
77
+ name="neatfile",
78
+ description="""
79
+
80
+ **Filename cleaning and normalization**
81
+
82
+ - Remove special characters
83
+ - Trim multiple separators (`word----word` becomes `word-word`)
84
+ - Normalize to `lowercase`, `uppercase`, `Sentence case`, or `Title Case`
85
+ - Normalize all files to a common word separator (`_`, `-`, ` `, `.`)
86
+ - Enforce lowercase file extensions
87
+ - Remove common English stopwords
88
+ - Split `camelCase` words into separate words (`camel Case`)
89
+
90
+ **Date parsing**
91
+
92
+ - Parse dates in filenames in many different formats
93
+ - Fall back to file creation date if no date is found in the filename
94
+ - Normalize dates in filenames to a preferred format
95
+ - Add the date to the beginning or the end of the filename or remove it entirely
96
+
97
+ **File organization**
98
+
99
+ - Set up projects with directory trees in the config file
100
+ - Match terms in filenames to folder names and move files into the appropriate folders
101
+ - Use vector matching to find similar terms
102
+ - Respect the [Johnny Decimal](https://johnnydecimal.com) system if you use it
103
+ - Optionally, add `.neatfile` files to directories containing a list of words that will match files
104
+
105
+ **Configuration**
106
+
107
+ To set your preferences and create projects, you'll need to create a configuration file. Neatfile will look for a file at `~/.config/neatfile/config.toml` or your `$XDG_CONFIG_HOME/neatfile/config.toml` if set.
108
+ """,
109
+ )
110
+ class NeatFile:
111
+ """A CLI tool that automatically normalizes and organizes your files based on customizable rules."""
112
+
113
+ command: cappa.Subcommands[
114
+ CleanCommand | ConfigCommand | SortCommand | ProcessCommand | TreeCommand
115
+ ]
116
+
117
+ project_name: Annotated[
118
+ str,
119
+ cappa.Arg(
120
+ long="project",
121
+ short="p",
122
+ help="Specify a project from the configuration file.",
123
+ propagate=True,
124
+ ),
125
+ ] = ""
126
+ verbosity: Annotated[
127
+ PrintLevel,
128
+ cappa.Arg(
129
+ short=True,
130
+ count=True,
131
+ help="Verbosity level (`-v` or `-vv`)",
132
+ choices=[],
133
+ show_default=False,
134
+ propagate=True,
135
+ ),
136
+ ] = PrintLevel.INFO
137
+ dryrun: Annotated[
138
+ bool,
139
+ cappa.Arg(
140
+ long="dry-run",
141
+ short="-n",
142
+ help="Preview changes without modifying files",
143
+ show_default=False,
144
+ propagate=True,
145
+ ),
146
+ ] = False
147
+
148
+
149
+ @cappa.command(
150
+ name="clean",
151
+ description="""\
152
+ Perform the following transformations on a filename:
153
+
154
+ - Remove special characters
155
+ - Trim multiple separators (`word----word` becomes `word-word`)
156
+ - Normalize to `lowercase`, `uppercase`, `Sentence case`, or `Title Case`
157
+ - Normalize all word separators to a common one (`_`, `-`, ` `, `.`)
158
+ - Enforce lowercase file extensions
159
+ - Remove common English stopwords
160
+ - Split `camelCase` words into separate words (`camel Case`)
161
+ - Add a date to the filename in your preferred format (removing dates already present in the filename)
162
+
163
+ Learn more [in the README](https://github.com/natelandau/neatfile).
164
+ """,
165
+ )
166
+ class CleanCommand:
167
+ """Clean and normalize filenames."""
168
+
169
+ files: Annotated[
170
+ list[Path],
171
+ cappa.Arg(
172
+ help="The files to clean. If a directory is provided, all files in the directory will be cleaned, not the directory itself.",
173
+ required=True,
174
+ ),
175
+ ]
176
+
177
+ confirm_changes: Annotated[
178
+ bool,
179
+ cappa.Arg(
180
+ long="confirm",
181
+ short="c",
182
+ help="Confirm changes before applying them",
183
+ show_default=False,
184
+ ),
185
+ ] = False
186
+ date: Annotated[
187
+ str | None,
188
+ cappa.Arg(
189
+ long="date",
190
+ short="d",
191
+ help="Specify a date to use for the filename (ignores dates found in filename)",
192
+ show_default=False,
193
+ ),
194
+ ] = None
195
+
196
+ date_format: Annotated[
197
+ str | None,
198
+ cappa.Arg(
199
+ long="date-format",
200
+ short="f",
201
+ help="Specify a date format to use for the filename (e.g. `%Y-%m-%d`)",
202
+ show_default=False,
203
+ ),
204
+ ] = None
205
+ date_only: Annotated[
206
+ bool,
207
+ cappa.Arg(
208
+ help="Add a date to the filename but make no other changes",
209
+ show_default=False,
210
+ ),
211
+ ] = False
212
+ file_search_depth: Annotated[
213
+ int | None,
214
+ cappa.Arg(
215
+ long="depth",
216
+ help="Depth to search for files if using a wildcard",
217
+ show_default=False,
218
+ ),
219
+ ] = None
220
+ force: Annotated[
221
+ bool,
222
+ cappa.Arg(
223
+ help="Do not prompt for confirmation before making changes",
224
+ show_default=False,
225
+ ),
226
+ ] = False
227
+ overwrite: Annotated[
228
+ bool,
229
+ cappa.Arg(
230
+ help="Overwrite existing files",
231
+ show_default=False,
232
+ ),
233
+ ] = False
234
+ transform_case: Annotated[
235
+ str | None,
236
+ cappa.Arg(
237
+ choices=[c.name for c in TransformCase],
238
+ long="case",
239
+ help="Transform the case of the filename",
240
+ show_default=True,
241
+ parse=lambda x: x.upper(),
242
+ ),
243
+ ] = None
244
+ separator: Annotated[
245
+ str | None,
246
+ cappa.Arg(
247
+ choices=[c.name for c in Separator],
248
+ long=["separator", "sep"],
249
+ help="Separator to use for the filename.",
250
+ show_default=False,
251
+ parse=lambda x: x.upper(),
252
+ ),
253
+ ] = None
254
+
255
+ def __call__(self) -> None:
256
+ """Call the command."""
257
+ if settings.date_only and not settings.date_format:
258
+ pp.error("`date_format` is not specified")
259
+ raise cappa.Exit(code=1)
260
+
261
+ execute_command()
262
+
263
+
264
+ @cappa.command(name="config")
265
+ class ConfigCommand:
266
+ """View and create a user configuration file."""
267
+
268
+ create: Annotated[
269
+ bool,
270
+ cappa.Arg(help="Create a user configuration file", show_default=False),
271
+ ] = False
272
+
273
+ def __call__(self) -> None:
274
+ """Call the command."""
275
+ if self.create:
276
+ if USER_CONFIG_PATH.exists():
277
+ pp.info(f"User configuration file already exists: {USER_CONFIG_PATH}")
278
+ raise cappa.Exit(code=1)
279
+
280
+ if settings.dryrun:
281
+ pp.dryrun(f"Would create configuration file: {USER_CONFIG_PATH}")
282
+ raise cappa.Exit(code=0)
283
+
284
+ USER_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
285
+ shutil.copy(DEFAULT_CONFIG_PATH, USER_CONFIG_PATH)
286
+ pp.success(f"User config file created: {USER_CONFIG_PATH}")
287
+ raise cappa.Exit(code=0)
288
+
289
+ current_config = USER_CONFIG_PATH if USER_CONFIG_PATH.exists() else DEFAULT_CONFIG_PATH
290
+
291
+ pp.rule("Current Configuration")
292
+ console.print(Markdown("```toml\n" + current_config.read_text() + "\n```"))
293
+
294
+ if not USER_CONFIG_PATH.exists():
295
+ pp.info("Using default configuration.")
296
+ pp.secondary(f"No user configuration file found: {USER_CONFIG_PATH}")
297
+ pp.secondary("To create a user configuration file, run `neatfile config --create`")
298
+ else:
299
+ pp.info(f"User configuration file found: {USER_CONFIG_PATH}")
300
+
301
+
302
+ @cappa.command(
303
+ name="process",
304
+ description="""\
305
+ Perform the following transformations on a filename:
306
+
307
+ - Remove special characters
308
+ - Trim multiple separators (`word----word` becomes `word-word`)
309
+ - Normalize to `lowercase`, `uppercase`, `Sentence case`, or `Title Case`
310
+ - Normalize all word separators to a common one (`_`, `-`, ` `, `.`)
311
+ - Enforce lowercase file extensions
312
+ - Remove common English stopwords
313
+ - Split `camelCase` words into separate words (`camel Case`)
314
+ - Add a date to the filename in your preferred format (removing dates already present in the filename)
315
+
316
+ Sort files into a project directory:
317
+
318
+ - Specify the project with the `--project` flag
319
+ - Match terms in filenames to directory names and move files into the appropriate directory
320
+ - Use vector matching to find similar terms
321
+
322
+ **Note:** Projects must be defined in the configuration file.
323
+
324
+ Learn more [in the README](https://github.com/natelandau/neatfile).
325
+ """,
326
+ )
327
+ class ProcessCommand:
328
+ """Clean and sort files."""
329
+
330
+ files: Annotated[
331
+ list[Path],
332
+ cappa.Arg(
333
+ help="The files to clean. If a directory is provided, all files in the directory will be cleaned, not the directory itself.",
334
+ required=True,
335
+ ),
336
+ ]
337
+
338
+ confirm_changes: Annotated[
339
+ bool,
340
+ cappa.Arg(
341
+ long="confirm",
342
+ short="c",
343
+ help="Confirm changes before applying them",
344
+ show_default=False,
345
+ ),
346
+ ] = False
347
+ date: Annotated[
348
+ str | None,
349
+ cappa.Arg(
350
+ long="date",
351
+ short="d",
352
+ help="Specify a date to use for the filename (ignores dates found in filename)",
353
+ show_default=False,
354
+ ),
355
+ ] = None
356
+ file_search_depth: Annotated[
357
+ int | None,
358
+ cappa.Arg(
359
+ long="depth",
360
+ help="Depth to search for files if using a wildcard",
361
+ show_default=False,
362
+ ),
363
+ ] = None
364
+ user_terms: Annotated[
365
+ tuple[str, ...],
366
+ cappa.Arg(
367
+ long="term",
368
+ short="t",
369
+ help="Term used to match files to folders. Add multiple terms with additional `--term` flags",
370
+ show_default=False,
371
+ ),
372
+ ] = ()
373
+
374
+ date_format: Annotated[
375
+ str | None,
376
+ cappa.Arg(
377
+ long="date-format",
378
+ short="f",
379
+ help="Specify a date format to use for the filename (e.g. `%Y-%m-%d`)",
380
+ show_default=False,
381
+ ),
382
+ ] = None
383
+ date_only: Annotated[
384
+ bool,
385
+ cappa.Arg(
386
+ help="Add a date to the filename but make no other changes",
387
+ show_default=False,
388
+ ),
389
+ ] = False
390
+ force: Annotated[
391
+ bool,
392
+ cappa.Arg(
393
+ help="Do not prompt for confirmation before making changes",
394
+ show_default=False,
395
+ ),
396
+ ] = False
397
+ overwrite: Annotated[
398
+ bool,
399
+ cappa.Arg(
400
+ help="Overwrite existing files",
401
+ show_default=False,
402
+ ),
403
+ ] = False
404
+ transform_case: Annotated[
405
+ str | None,
406
+ cappa.Arg(
407
+ choices=[c.name for c in TransformCase],
408
+ long="case",
409
+ help="Transform the case of the filename",
410
+ show_default=True,
411
+ parse=lambda x: x.upper(),
412
+ ),
413
+ ] = None
414
+ separator: Annotated[
415
+ str | None,
416
+ cappa.Arg(
417
+ choices=[c.name for c in Separator],
418
+ long=["separator", "sep"],
419
+ help="Separator to use for the filename.",
420
+ show_default=False,
421
+ parse=lambda x: x.upper(),
422
+ ),
423
+ ] = None
424
+
425
+ def __call__(self) -> None:
426
+ """Call the command."""
427
+ if settings.date_only and not settings.date_format:
428
+ pp.error("`date_format` is not specified")
429
+ raise cappa.Exit(code=1)
430
+
431
+ if not settings.get("project", {}):
432
+ pp.error("`project` is not specified")
433
+ raise cappa.Exit(code=1)
434
+
435
+ execute_command()
436
+
437
+
438
+ @cappa.command(
439
+ name="sort",
440
+ description="""\
441
+ Projects must be defined in the configuration file.
442
+
443
+ - Specify the project with the `--project` flag
444
+ - Match terms in filenames to directory names and move files into the appropriate directory
445
+ - Use vector matching to find similar terms
446
+
447
+ Learn more [in the README](https://github.com/natelandau/neatfile/).
448
+ """,
449
+ )
450
+ class SortCommand:
451
+ """Sort files into a project folder."""
452
+
453
+ files: Annotated[
454
+ list[Path],
455
+ cappa.Arg(
456
+ help="The files to clean. If a directory is provided, all files in the directory will be cleaned, not the directory itself.",
457
+ required=True,
458
+ ),
459
+ ]
460
+
461
+ confirm_changes: Annotated[
462
+ bool,
463
+ cappa.Arg(
464
+ long="confirm",
465
+ short="c",
466
+ help="Confirm changes before applying them",
467
+ show_default=False,
468
+ ),
469
+ ] = False
470
+ file_search_depth: Annotated[
471
+ int | None,
472
+ cappa.Arg(
473
+ long="depth",
474
+ help="Depth to search for files if using a wildcard",
475
+ show_default=False,
476
+ ),
477
+ ] = None
478
+ force: Annotated[
479
+ bool,
480
+ cappa.Arg(
481
+ help="Do not prompt for confirmation before making changes",
482
+ show_default=False,
483
+ ),
484
+ ] = False
485
+ overwrite: Annotated[
486
+ bool,
487
+ cappa.Arg(
488
+ help="Overwrite existing files",
489
+ show_default=False,
490
+ ),
491
+ ] = False
492
+
493
+ user_terms: Annotated[
494
+ tuple[str, ...],
495
+ cappa.Arg(
496
+ long="term",
497
+ short="t",
498
+ help="Term used to match files to folders. Add multiple terms with additional `--term` flags",
499
+ show_default=False,
500
+ ),
501
+ ] = ()
502
+
503
+ def __call__(self) -> None:
504
+ """Call the command."""
505
+ if not settings.get("project", {}):
506
+ pp.error("`project` is not specified")
507
+ raise cappa.Exit(code=1)
508
+
509
+ execute_command()
510
+
511
+
512
+ @cappa.command(name="tree")
513
+ class TreeCommand:
514
+ """Print a tree representation of the project folder."""
515
+
516
+ def __call__(self) -> None:
517
+ """Call the command."""
518
+ if settings.get("project"):
519
+ console.print(settings.project.tree())
520
+ else:
521
+ pp.error("You must specify a project name with the `--project` flag.")
522
+ raise cappa.Exit(code=1)
523
+
524
+
525
+ def main() -> None: # pragma: no cover
526
+ """Run the CLI."""
527
+ install(show_locals=False)
528
+
529
+ try:
530
+ cappa.invoke(obj=NeatFile, deps=[config_subcommand])
531
+ except KeyboardInterrupt as e:
532
+ pp.info("Exiting...")
533
+ raise cappa.Exit(code=1) from e
534
+
535
+
536
+ if __name__ == "__main__": # pragma: no cover
537
+ main()
neatfile/commands.py ADDED
@@ -0,0 +1,59 @@
1
+ """Execute CLI commands."""
2
+
3
+ import cappa
4
+ from rich.prompt import Confirm
5
+
6
+ from neatfile import settings
7
+ from neatfile.features import clean_filename, commit_changes, find_processable_files, sort_file
8
+ from neatfile.models import File
9
+ from neatfile.utils import console, pp
10
+ from neatfile.views import confirmation_table
11
+
12
+
13
+ def execute_command() -> None:
14
+ """Execute the current CLI command.
15
+
16
+ Process files based on the current subcommand (clean, sort, or process).
17
+ Handle file operations, confirmations, and commit changes based on settings.
18
+
19
+ Raises:
20
+ cappa.Exit: If no changes were made or if user declines to apply changes.
21
+ """
22
+ files_to_process = [File(f) for f in find_processable_files(settings.files)]
23
+
24
+ files_with_changes = []
25
+ files_without_changes = []
26
+
27
+ for file in files_to_process:
28
+ pp.debug(f"Working on: `{file.display_path}`")
29
+
30
+ if settings.subcommand in {"cleancommand", "processcommand"}:
31
+ clean_filename(file)
32
+
33
+ if settings.subcommand in {"sortcommand", "processcommand"}:
34
+ file.new_parent = sort_file(file)
35
+
36
+ if file.has_changes:
37
+ files_with_changes.append(file)
38
+ else:
39
+ files_without_changes.append(file)
40
+
41
+ if not files_with_changes:
42
+ pp.info("No changes made")
43
+ raise cappa.Exit(code=0)
44
+
45
+ if settings.confirm_changes and not settings.force:
46
+ console.print(
47
+ confirmation_table(
48
+ files_with_changes,
49
+ total_files=len(files_to_process) + len(files_without_changes),
50
+ )
51
+ )
52
+ if not Confirm.ask("Apply changes"):
53
+ pp.info("Changes not applied")
54
+ raise cappa.Exit(code=0)
55
+
56
+ for file in files_with_changes + files_without_changes:
57
+ commit_changes(file)
58
+
59
+ raise cappa.Exit(code=0)