Add "merge" command (#1)

This commit is contained in:
Ivan R. 2022-12-15 22:25:44 +05:00
parent c58d3d6fd0
commit be72f4f693
No known key found for this signature in database
GPG key ID: 56C7BAAE859B302C
2 changed files with 38 additions and 3 deletions

View file

@ -13,6 +13,8 @@ def main():
edit_note(base_dir, today) edit_note(base_dir, today)
elif sys.argv[1] == "backup": elif sys.argv[1] == "backup":
backup(base_dir, today) backup(base_dir, today)
elif sys.argv[1] == "merge":
merge(base_dir)
else: else:
print('Command not found') print('Command not found')
@ -69,5 +71,38 @@ def backup(base_dir: str, current_date):
print("Archiver returned non-zero exit code") print("Archiver returned non-zero exit code")
def merge(base_dir: str):
"""
This function concatenates all files and prefixes each with the filename.
The result will be printed to stdout.
"""
def read_files(path: str) -> str:
"""
Recursive function to read all files in a directory
"""
strings = []
contents = os.listdir(path)
for entry in contents:
entry_path = os.path.join(path, entry)
# It's a directory
if os.path.isdir(entry_path):
# Read all files in this directory
res = read_files(entry_path)
strings.append(res)
# It's a file
else:
with open(entry_path, 'r') as note:
strings.append(f'## {entry_path}')
strings.append(note.read())
return '\n\n'.join(strings)
res = read_files(base_dir)
print(res)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View file

@ -40,7 +40,7 @@ histd backup
``` ```
## Merge all notes ## Merge all notes
This command concatenates all files and prefixes each with the creation date. This command concatenates all files and prefixes each with the filename.
```sh ```bash
for f in ~/.local/share/histd/**/*.md; do echo $f | sed 's/^.*histd\//# /'; cat "${f}"; echo; done histd merge
``` ```