Compare commits

..

No commits in common. "develop" and "v2.8.4-beta2" have entirely different histories.

165 changed files with 3666 additions and 10454 deletions

42
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View file

@ -0,0 +1,42 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ":new:, bug"
assignees: ''
---
## Bug Report
<!--
Hello, and thank you for reporting an issue!
Please fill out the points below, as it will make our process much easier.
-->
<!-- Please tell us about your environment -->
### Environment
- `jrnl --diagnostic` output: <!-- Run the command and paste the output here -->
- Install method: <!-- How did you install jrnl? (pipx, brew, etc) -->
### Current Behavior
<!--
Please put a short description of what is currently happening.
-->
### Expected Behavior
<!--
Please write a short description of what you would expect to happen
(instead of what is currently happening).
-->
### Repro Steps
<!--
Please provide the steps to reproduce the problem. It is important for you to
be as precise as possible here, since more info will let us help you faster.
If applicable, please run jrnl with --debug and paste the output.
-->
### Other Information
<!-- (e.g. more detailed explanation, stacktraces, related
issues, suggestions how to fix, links for us to have context, eg.
stackoverflow, gitter, etc) -->

View file

@ -1,74 +0,0 @@
name: Bug Report
description: Create a report to help us improve
title: "Bug Report"
labels: [ ":new:", "bug" ]
body:
- type: markdown
attributes:
value: |
# Bug Report
Hello, and thank you for reporting an issue!
Please fill out the points below, as it will make our process much easier.
- type: textarea
id: diagnostic
attributes:
label: Diagnostic output
description: Run `jrnl --diagnostic` and paste the output below
placeholder: Paste output here
validations:
required: true
- type: textarea
id: current-behavior
attributes:
label: Current Behavior
description: Please put a short description of what is currently happening.
placeholder: Tell us what is happening
validations:
required: true
- type: textarea
id: expected-behavior
attributes:
label: Expected Behavior
description: Please write a short description of what you would expect to happen
placeholder: Tell us what should be happening
validations:
required: true
- type: textarea
id: repro-steps
attributes:
label: Repro Steps
description: |
Provide the steps to reproduce the problem.
Please be as precise as possible, since more info will let us help you faster.
placeholder: Repro steps
validations:
required: true
- type: textarea
id: debug-output
attributes:
label: Debug output
description: |
Please provide the output of your command with the `--debug` flag on.
placeholder: "example: `jrnl --debug lorem ipsum`"
validations:
required: true
- type: textarea
id: other-info
attributes:
label: Other Information
description: >
Is there anything else we should know?
(e.g. more detailed explanation, stacktraces, related
issues, suggestions how to fix, links for us to have context, eg.
stackoverflow, gitter, etc)
validations:
required: false

31
.github/ISSUE_TEMPLATE/documentation.md vendored Normal file
View file

@ -0,0 +1,31 @@
---
name: Documentation Change
about: Request or report any updates to our documentation (https://jrnl.sh)
title: ''
labels: ":new:, documentation"
assignees: ''
---
## Documentation Change
<!--
Hello, and thank you for reporting an issue!
Please fill out the points below, as it will make our process much easier.
-->
### Affected Page(s)
<!--
Please tell us which page, or pages, from the documentation site (https://jrnl.sh) are
affected in this issue
-->
- <!-- example: https://jrnl.sh/en/stable/overview -->
### What Could Be Better?
<!--
Please write a short description of what you hope can be clarified or further explained.
-->
### Other Information
<!--
Is there anything else we should know that might be helpful?
-->

View file

@ -1,41 +0,0 @@
name: Documentation Change
description: Request or report any updates to our documentation (https://jrnl.sh)
title: Documentation Change
labels: [ ":new:", "documentation" ]
body:
- type: markdown
attributes:
value: |
# Documentation Change
Hello, and thank you for reporting an issue!
Please fill out the points below, as it will make our process much easier.
- type: textarea
id: affected-pages
attributes:
label: Affected Page(s)
description: >
Please tell us which page, or pages, from the documentation site
(https://jrnl.sh) are affected in this issue
placeholder: "example: https://jrnl.sh/en/stable/overview"
validations:
required: true
- type: textarea
id: what-could-be-better
attributes:
label: What Could Be Better?
description: >
Please write a short description of what you hope can be clarified or
further explained.
validations:
required: true
- type: textarea
id: other-info
attributes:
label: Other Information
description: Is there anything else we should know that might be helpful?
validations:
required: false

View file

@ -0,0 +1,31 @@
---
name: Feature request
about: Suggest an idea for jrnl
title: ''
labels: ":new:, enhancement"
assignees: ''
---
## Feature Request
<!--
Hello, and thank you for reporting an issue!
Please fill out the points below, as it will make our process much easier.
-->
### Use Case/Motivation
<!--
What is the motivation / use case for changing the behavior?
-->
### Example Usage
<!--
Please provide examples of the usage you would like to see.
e.g `jrnl --new-flag="super cool new feature"`
-->
### Other information
<!--
Please provide any other relevant info about this request (e.g. stacktraces,
related issues, suggestions how to fix, etc)
-->

View file

@ -1,43 +0,0 @@
name: Feature Request
description: Suggest an idea for jrnl
title: "Feature Report"
labels: [ ":new:", "enhancement" ]
body:
- type: markdown
attributes:
value: |
# Feature Request
Hello, and thank you for reporting an issue!
Please fill out the points below, as it will make our process much easier.
- type: textarea
id: user-case
attributes:
label: Use Case/Motivation
description: What is the motivation / use case for changing the behavior?
placeholder: Tell us about your idea
validations:
required: true
- type: textarea
id: example-usage
attributes:
label: Example Usage
description: Please provide examples of the usage you would like to see.
placeholder: e.g `jrnl --new-flag="super cool new feature"`
validations:
required: true
- type: textarea
id: other-info
attributes:
label: Other Information
description: >
Is there anything else we should know?
(e.g. more detailed explanation, stacktraces, related
issues, suggestions how to fix, links for us to have context, eg.
stackoverflow, gitter, etc)
validations:
required: false

View file

@ -0,0 +1,40 @@
---
name: Support Request
about: Get help with jrnl
title: ''
labels: ":new:, support"
assignees: ''
---
## Support Request
<!--
Hello, and thank you for reporting an issue!
Please fill out the points below, as it will make our process much easier.
-->
### Environment
<!--
Please tell us about your environment
-->
- Jrnl `--diagnostic` output: <!-- Run `jrnl --diagnostic` and paste the output -->
- Install method: <!-- How did you install jrnl? (pipx, brew, etc) -->
### What are you trying to do?
<!--
Please write a short description of what is happening.
-->
### What have you tried?
<!--
Have you tried anything to fix the problem? This can help give us more
information to help you with.
-->
### Other Information
<!--
If applicable, please run jrnl with --debug and paste the output.
Is there anything else we should know that might be helpful?
e.g. detailed explanation, stacktraces, related issues, suggestions how to fix
-->

View file

@ -1,54 +0,0 @@
name: Support Request
description: Get help with jrnl
title: Support Request
labels: [ ":new:", "support" ]
body:
- type: markdown
attributes:
value: |
# Support Request
Hello, and thank you for reporting an issue!
Please fill out the points below, as it will make our process much easier.
- type: textarea
id: diagnostic
attributes:
label: Diagnostic output
description: Run `jrnl --diagnostic` and paste the output below
placeholder: Paste output here
validations:
required: true
- type: textarea
id: current-behavior
attributes:
label: What are you trying to do?
description: Please put a short description of what is happening.
placeholder: Tell us what is happening
validations:
required: true
- type: textarea
id: tried
attributes:
label: What have you tried?
description: >
Have you tried anything to fix the problem? This can help give us more
information to help you with.
placeholder: Tell us what should be happening
validations:
required: true
- type: textarea
id: other-info
attributes:
label: Other Information
description: >
Is there anything else we should know?
(e.g. more detailed explanation, stacktraces, related
issues, suggestions how to fix, links for us to have context, eg.
stackoverflow, gitter, etc)
validations:
required: false

View file

@ -12,13 +12,13 @@ Here are some key points to include in your description:
### Checklist
- [ ] I have read the [contributing doc](https://github.com/jrnl-org/jrnl/blob/develop/docs/contributing.md).
- [ ] I have read the [contributing doc](https://github.com/jrnl-org/jrnl/blob/develop/CONTRIBUTING.md).
- [ ] I have included a link to the relevant issue number.
- [ ] I have checked to ensure there aren't other open [pull requests](../pulls)
for the same issue.
- [ ] I have written new tests for these changes, as needed.
<!--
NOTE: Your PR may not be reviewed if there are any failing tests. You can run
tests locally with `poe test` (see the contributing doc if you need help with
`poe`), or use our automated tests after you submit your PR.
tests locally with `make test` (see the contributing doc if you need help with
`make`), or use our automated tests after you submit your PR.
-->

View file

@ -1,17 +0,0 @@
{
"problemMatcher": [
{
"owner": "actionlint",
"pattern": [
{
"regexp": "^(?:\\x1b\\[\\d+m)?(.+?)(?:\\x1b\\[\\d+m)*:(?:\\x1b\\[\\d+m)*(\\d+)(?:\\x1b\\[\\d+m)*:(?:\\x1b\\[\\d+m)*(\\d+)(?:\\x1b\\[\\d+m)*: (?:\\x1b\\[\\d+m)*(.+?)(?:\\x1b\\[\\d+m)* \\[(.+?)\\]$",
"file": 1,
"line": 2,
"column": 3,
"message": 4,
"code": 5
}
]
}
]
}

View file

@ -11,17 +11,16 @@ runs:
shell: bash
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
allow-prereleases: true
- name: Capture full Python version in env
run: echo "PYTHON_FULL_VERSION=$(python --version)" >> $GITHUB_ENV
shell: bash
- name: poetry cache # Change CACHE_STRING secret to bust the cache
uses: actions/cache@v4
uses: actions/cache@v2
with:
path: .venv
key: ${{ runner.os }}-${{ hashFiles('poetry.lock') }}-${{ env.PYTHON_FULL_VERSION }}-${{ inputs.cache-string }}
@ -34,13 +33,29 @@ runs:
echo '::endgroup::'
echo '::group::Other dependencies'
poetry sync
poetry install --remove-untracked
echo '::endgroup::'
echo 'DEPS_INSTALLED=true' >> $GITHUB_ENV
shell: bash
- name: Linting & Testing
- name: Code formatting (Black)
if: ${{ env.DEPS_INSTALLED == 'true' }}
run: poetry run poe test
run: |
poetry run black --version
poetry run black --check --diff .
shell: bash
- name: Code Style (flake8)
if: >
${{ env.DEPS_INSTALLED == 'true' }}
run: |
poetry run pflake8 --version
poetry run pflake8 jrnl tests
shell: bash
- name: Test with pytest
if: >
${{ env.DEPS_INSTALLED == 'true' }}
run: poetry run pytest --junitxml=reports/pytest/results.xml
shell: bash

12
.github/dependabot.yml vendored Normal file
View file

@ -0,0 +1,12 @@
version: 2
updates:
- package-ecosystem: pip
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10
reviewers:
- wren
- micahellison
labels:
- packaging

14
.github/renovate.json vendored
View file

@ -1,14 +0,0 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:base"
],
"schedule": [ "at any time" ],
"prConcurrentLimit": 10,
"prHourlyLimit": 10,
"reviewers": [
"wren",
"micahellison"
],
"labels": [ "packaging" ]
}

View file

@ -1,6 +1,3 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
name: Changelog
on:
@ -21,7 +18,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v2
with:
token: ${{ secrets.JRNL_BOT_TOKEN }}
@ -52,14 +49,14 @@ jobs:
if [[ ! ${GITHUB_REF##*/} =~ $prerelease_regex ]]; then
echo '::debug::Actual release (not a prerelease)'
TAG_REGEX="$prerelease_regex"
echo "FULL_RELEASE=true" >> "$GITHUB_ENV"
echo "FULL_RELEASE=true" >> $GITHUB_ENV
fi
fi
echo "::debug::TAG_REGEX: $TAG_REGEX"
if [[ "$(git rev-parse "origin/$BRANCH")" != "$GITHUB_SHA" ]]; then
if [[ "$(git rev-parse "origin/$BRANCH")" != $GITHUB_SHA ]]; then
# Normal build on a branch (no tag)
echo "::debug::BRANCH: $BRANCH $(git rev-parse "origin/$BRANCH")"
echo "::debug::BRANCH: $BRANCH $(git rev-parse origin/$BRANCH)"
echo "::debug::GITHUB_SHA: $GITHUB_SHA"
echo "::error::$BRANCH has been updated since build started. Aborting changelog."
exit 1
@ -72,12 +69,10 @@ jobs:
echo "::debug::FILENAME: CHANGELOG.md"
echo "::debug::SINCE_TAG: $SINCE_TAG"
{
echo "BRANCH=$BRANCH"
echo "TAG_REGEX=$TAG_REGEX"
echo "FILENAME=CHANGELOG.md"
echo "SINCE_TAG=$SINCE_TAG"
} >> "$GITHUB_ENV"
echo "BRANCH=$BRANCH" >> $GITHUB_ENV
echo "TAG_REGEX=$TAG_REGEX" >> $GITHUB_ENV
echo "FILENAME=CHANGELOG.md" >> $GITHUB_ENV
echo "SINCE_TAG=$SINCE_TAG" >> $GITHUB_ENV
- name: Prep changelog file (clear out old lines)
run: |
@ -97,7 +92,7 @@ jobs:
exit 1
fi
sed -i "1,$(( tagline - 1 ))d" "$FILENAME"
sed -i "1,$(expr $tagline - 1)d" "$FILENAME"
# delete generated line (or it will be added multiple times)
sed -i '/This Changelog was automatically generated by/d' "$FILENAME"
# delete trailing empty lines
@ -141,30 +136,22 @@ jobs:
SOMETHING_CHANGED=false
git diff --exit-code || SOMETHING_CHANGED=true
echo "::debug::SOMETHING_CHANGED: $SOMETHING_CHANGED"
echo "SOMETHING_CHANGED=$SOMETHING_CHANGED" >> "$GITHUB_ENV"
echo "SOMETHING_CHANGED=$SOMETHING_CHANGED" >> $GITHUB_ENV
- name: Commit
if: env.SOMETHING_CHANGED == 'true'
run: |
git config --global user.name "${{ secrets.JRNL_BOT_NAME }}"
git config --global user.email "${{ secrets.JRNL_BOT_EMAIL }}"
git config user.email "jrnl.bot@gmail.com"
git config user.name "Jrnl Bot"
git add "$FILENAME"
git commit -m "Update changelog [ci skip]"
git push origin "$BRANCH"
- name: Update tag to include changelog
if: startsWith(env.GITHUB_REF, 'refs/tags/')
run: |
# This is a tag build (releases and prereleases)
# update the tag to include the changelog
git tag -fam "$GITHUB_REF_NAME" "$GITHUB_REF_NAME"
git push --tags --force
git push origin $BRANCH
- name: Merge to Release branch
if: env.FULL_RELEASE == 'true'
run: |
git fetch --unshallow origin
git checkout release
git merge --ff-only "$BRANCH"
git merge --ff-only $BRANCH
git push origin release

View file

@ -1,6 +1,3 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
name: Docs
on:
@ -12,8 +9,6 @@ on:
- 'mkdocs.yml'
- 'readthedocs.yml'
- '.github/workflows/docs.yaml'
- 'tasks.py'
- 'pyproject.toml'
pull_request:
branches: [ develop ]
paths:
@ -22,8 +17,6 @@ on:
- 'mkdocs.yml'
- 'readthedocs.yml'
- '.github/workflows/docs.yaml'
- 'tasks.py'
- 'pyproject.toml'
jobs:
accessibility:
@ -32,31 +25,28 @@ jobs:
strategy:
fail-fast: true
matrix:
python-version: [ '3.11' ]
python-version: [ 3.9 ]
os: [ ubuntu-latest ]
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v5
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Setup Node.js environment
uses: actions/setup-node@main
- name: Capture full Python version in env
run: echo "PYTHON_FULL_VERSION=$(python --version)" >> "$GITHUB_ENV"
- name: poetry cache
uses: actions/cache@v4
uses: actions/cache@v2
with:
path: .venv
key: ${{ runner.os }}-${{ hashFiles('poetry.lock') }}-${{ env.PYTHON_FULL_VERSION }}-${{ secrets.CACHE_STRING }}
key: ${{ runner.os }}-${{ hashFiles('poetry.lock') }}-${{ matrix.python-version }}
- name: npm cache
uses: actions/cache@v4
uses: actions/cache@v2
with:
path: node_modules
key: ${{ runner.os }}-pa11y-v3
@ -65,12 +55,27 @@ jobs:
run: |
pip install poetry
poetry config --local virtualenvs.in-project true
poetry sync --no-root
npm install
echo "node_modules/.bin" >> "$GITHUB_PATH"
poetry install --no-root --remove-untracked
npm install pa11y-ci
echo "node_modules/.bin" >> $GITHUB_PATH
- name: Start docs server
run: poetry run poe docs-run &
run: poetry run mkdocs serve &
- name: Generate sitemap
env:
site_url: http://127.0.0.1:8000
run: |
filename='sitemap.xml'
select="{urls: [\"${site_url}/\", \"${site_url}/search.html?q=jrnl\", .urlset.url[].loc]}"
curl -s "${site_url}/${filename}" > $filename
echo "::group::${filename}"
cat $filename
echo '::endgroup::'
poetry run xq "$select" $filename > list.json
- name: Accessibility testing (Pa11y)
run: poetry run poe docs-check
run: pa11y-ci -c list.json

View file

@ -1,22 +1,20 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
name: Release
on:
workflow_dispatch:
inputs:
version:
description: 'Version (e.g. v2.5, v2.5.1-beta, v2.6-beta2)'
type: string
required: true
include_repo_version:
description: 'Update version in repo?'
type: boolean
required: true
description: 'Update version in repo? (true/false)'
require: true
default: true
include_pypi:
description: 'Publish to PyPI?'
type: boolean
description: 'Publish to PyPI? (true/false)'
required: true
default: true
include_brew:
description: 'Publish to Homebrew? (true/false)'
required: true
default: true
@ -58,15 +56,15 @@ jobs:
run: |
JRNL_VERSION="${{ github.event.inputs.version }}"
echo "::debug::version: $JRNL_VERSION"
echo "JRNL_VERSION=$JRNL_VERSION" >> "$GITHUB_ENV"
echo "JRNL_VERSION=$JRNL_VERSION" >> $GITHUB_ENV
- name: Set up Python
uses: actions/setup-python@v5
uses: actions/setup-python@v2
with:
python-version: '3.13'
python-version: 3.9
- name: Checkout repo
uses: actions/checkout@v4
uses: actions/checkout@v2
with:
token: ${{ secrets.JRNL_BOT_TOKEN }}
@ -82,7 +80,7 @@ jobs:
if: ${{ github.event.inputs.include_repo_version == 'true' }}
run: |
poetry version "$JRNL_VERSION"
echo "__version__ = \"$JRNL_VERSION\"" > jrnl/__version__.py
echo __version__ = \"$JRNL_VERSION\" > jrnl/__version__.py
- name: Commit updated files
if: ${{ github.event.inputs.include_repo_version == 'true' && github.repository == env.HOME_REPO }}
@ -105,5 +103,113 @@ jobs:
- name: Get PyPI version
id: pypi-version-getter
run: |
pypi_version="$(find dist/jrnl-*.tar.gz | sed -r 's!dist/jrnl-(.*)\.tar\.gz!\1!')"
echo "pypi_version=$pypi_version" >> "$GITHUB_OUTPUT"
pypi_version="$(ls dist/jrnl-*.tar.gz | sed -r 's!dist/jrnl-(.*)\.tar\.gz!\1!')"
echo "::set-output name=pypi_version::$pypi_version"
release_homebrew:
if: ${{ github.event.inputs.include_brew == 'true' }}
needs: release_pypi
name: "Release to Homebrew"
runs-on: macos-latest
env:
HOMEBREW_NO_AUTO_UPDATE: 1
HOMEBREW_NO_INSTALL_CLEANUP: 1
HOME_REPO: ${{ secrets.HOME_REPO }}
steps:
- name: Get version
run: |
JRNL_VERSION="${{ github.event.inputs.version }}"
PYPI_VERSION="${{ needs.release_pypi.outputs.pypi_version }}"
echo "::debug::jrnl version: $JRNL_VERSION"
echo "::debug::pypi version: $PYPI_VERSION"
echo "JRNL_VERSION=$JRNL_VERSION" >> $GITHUB_ENV
echo "PYPI_VERSION=$PYPI_VERSION" >> $GITHUB_ENV
- name: Set env variables
env:
REPO_OWNER: ${{ github.repository_owner }}
run: |
if [[ $JRNL_VERSION =~ (alpha|beta) ]]; then
echo '::debug::Prerelease (not a full release)'
{
echo "RELEASE_TYPE=pre"
echo "FORMULA_REPO=${REPO_OWNER}/homebrew-prerelease"
echo "BOT_REPO=jrnl-bot/homebrew-prerelease"
echo "FORMULA_NAME=jrnl-beta"
} >> $GITHUB_ENV
else
echo '::debug::Full release (not a prerelease)'
if [[ "${{ github.repository }}" == "${HOME_REPO}" ]]; then
REPO_OWNER="homebrew"
fi
{
echo "RELEASE_TYPE=full"
echo "FORMULA_REPO=${REPO_OWNER}/homebrew-core"
echo "BOT_REPO=jrnl-bot/homebrew-core"
echo "FORMULA_NAME=jrnl"
} >> $GITHUB_ENV
fi
- name: Tap formula
run: |
brew tap ${FORMULA_REPO}
echo '::debug::Set tap directory'
echo "BREW_TAP_DIRECTORY=$(brew --repo ${FORMULA_REPO})" >> $GITHUB_ENV
- name: Install dependencies
run: brew install pipgrip
- name: Query PyPI API
uses: nick-invision/retry@v2
with:
timeout_seconds: 10
max_attempts: 30
retry_wait_seconds: 10
command: |
curl -Ls https://pypi.org/pypi/jrnl/json > api_response.json
# if query doesn't have our version yet, give it some time before trying again
if [[ "null" == "$(jq ".releases[\"${PYPI_VERSION}\"][1].url" -r api_response.json)" ]]; then
echo "::debug::PYPI_VERSION: $PYPI_VERSION"
echo "::debug::JQ VALUE: $(jq ".releases[\"${PYPI_VERSION}\"][1].url" -r api_response.json)"
echo "::group::cat api_response.json"
cat api_response.json
echo "::endgroup::"
exit 1
fi
- name: Update Homebrew Formula
uses: nick-invision/retry@v2
with:
timeout_minutes: 8
max_attempts: 6
retry_wait_seconds: 30
command: >
brew bump-formula-pr "${FORMULA_NAME}"
--url $(jq ".releases[\"${PYPI_VERSION}\"][1].url" -r api_response.json)
--sha256 $(jq ".releases[\"${PYPI_VERSION}\"][1].digests.sha256" -r api_response.json)
--no-audit
--write
--force
- name: Create Pull Request
uses: peter-evans/create-pull-request@v3
with:
path: ${{ env.BREW_TAP_DIRECTORY }}
token: ${{ secrets.JRNL_BOT_TOKEN }}
push-to-fork: ${{ env.BOT_REPO }}
committer: ${{ secrets.JRNL_BOT_NAME }} <${{ secrets.JRNL_BOT_EMAIL }}>
author: ${{ secrets.JRNL_BOT_NAME }} <${{ secrets.JRNL_BOT_EMAIL }}>
title: jrnl ${{ env.JRNL_VERSION }}
body: Created with `brew bump-formula-pr`
branch: jrnl-${{ env.JRNL_VERSION }}--
branch-suffix: random
commit-message: |
jrnl ${{ env.JRNL_VERSION }}
Update jrnl to ${{ env.JRNL_VERSION }}
${{ secrets.RELEASE_COAUTHORS }}

View file

@ -1,35 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
name: Testing Pipeline Files
on:
push:
branches: [ develop, release ]
paths:
- '.github/workflows/**'
- '.github/actions/**'
pull_request:
branches: [ develop ]
paths:
- '.github/workflows/**'
- '.github/actions/**'
schedule:
- cron: '0 0 * * SAT'
jobs:
test:
if: >
! contains(github.event.head_commit.message, '[ci skip]')
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ ubuntu-latest ]
steps:
- run: git config --global core.autocrlf false
- uses: actions/checkout@v4
- name: Check workflow files
uses: docker://rhysd/actionlint:latest
with:
args: -color

View file

@ -1,6 +1,3 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
name: Testing
on:
@ -12,8 +9,7 @@ on:
- 'tests/**'
- 'poetry.lock'
- 'pyproject.toml'
- '.github/workflows/testing_prs.yaml'
- 'tasks.py'
- '.github/workflows/testing.yaml'
pull_request:
branches: [ develop ]
paths:
@ -22,8 +18,7 @@ on:
- 'tests/**'
- 'poetry.lock'
- 'pyproject.toml'
- '.github/workflows/testing_prs.yaml'
- 'tasks.py'
- '.github/workflows/testing.yaml'
defaults:
run:
@ -37,11 +32,11 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: [ '3.10', '3.11', '3.12', '3.13' ]
python-version: [ 3.7, 3.8, 3.9, '3.10' ]
os: [ ubuntu-latest, macos-latest, windows-latest ]
steps:
- run: git config --global core.autocrlf false
- uses: actions/checkout@v4
- uses: actions/checkout@v2
- name: Run tests
uses: ./.github/actions/run_tests
with:

View file

@ -1,6 +1,3 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
name: Testing
on:
@ -17,11 +14,11 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: [ '3.10', '3.11', '3.12', '3.13' ]
python-version: [ 3.7, 3.8, 3.9, '3.10', 3.11-dev ]
os: [ ubuntu-latest, macos-latest, windows-latest ]
steps:
- run: git config --global core.autocrlf false
- uses: actions/checkout@v4
- uses: actions/checkout@v2
- name: Run tests
uses: ./.github/actions/run_tests
with:

75
.gitignore vendored
View file

@ -1,63 +1,64 @@
# Byte-compiled DLL and Shared Library files
*.py[cod]
# C extensions
*.so
# Packages
*.egg
*.egg-info/
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
bin/
build/
develop-eggs/
dist/
eggs/
lib64/
parts/
sdist/
.tox/
var/
node_modules/
__pycache__/
.pytest_cache/
.flakeheaven_cache/
lib64
# Versioning
.python-version
.tool-versions
.tool-version
# Installer logs
pip-log.txt
.DS_Store
.travis-solo
Icon
pip-log.txt
# Documentation
_build
_sources
_static
coverage.xml
exp/
objects.inv
searchindex.js
# virtualenv
.venv*/
# MS Visual Studio (PyTools)
obj
*.pyproj
*.sln
*.suo
# virtaulenv
env/
env*/
venv*/
.venv*/
# Editor and IDE specific files
# Since contributors may want to user a variety of development tools it is
# recommended that editor specific file types be ignored globally by each
# contributor via a global gitignore. Instructions for setting up a global
# ignore file can be found here:
# https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
# (Configuring ignored files for all repositories on your computer)
# Examples of such files are:
# MS Visual Studio (PyTools)
# obj
# *.suo
# PyCharm
# .idea/
# VS Code
# .vscode/settings.json
# PyCharm Project files
.idea/
# export testing directories
exp/
_extras/
*.sublime-*
site/
.vscode/settings.json
coverage.xml
.vscode/launch.json
.coverage
.vscode/tasks.json
todo.txt

View file

@ -2,439 +2,96 @@
## [Unreleased](https://github.com/jrnl-org/jrnl/)
[Full Changelog](https://github.com/jrnl-org/jrnl/compare/v4.2.1...HEAD)
**Fixed bugs:**
- poetry warning - "poetry.dev-dependencies" section is deprecated [\#1975](https://github.com/jrnl-org/jrnl/issues/1975)
- Homebrew autobump error on jrnl release [\#1961](https://github.com/jrnl-org/jrnl/issues/1961)
**Build:**
- Remove release step to publish to Homebrew [\#1994](https://github.com/jrnl-org/jrnl/pull/1994) ([micahellison](https://github.com/micahellison))
**Packaging:**
- Update dependency rich to v14 [\#1989](https://github.com/jrnl-org/jrnl/pull/1989) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency python to 3.13 [\#1988](https://github.com/jrnl-org/jrnl/pull/1988) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency tox to v4.25.0 [\#1986](https://github.com/jrnl-org/jrnl/pull/1986) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency tzlocal to v5.3.1 [\#1984](https://github.com/jrnl-org/jrnl/pull/1984) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency jinja2 to v3.1.6 [\#1983](https://github.com/jrnl-org/jrnl/pull/1983) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency poethepoet to v0.33.1 [\#1982](https://github.com/jrnl-org/jrnl/pull/1982) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency pytest to v8.3.5 [\#1981](https://github.com/jrnl-org/jrnl/pull/1981) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency cryptography to v44.0.2 [\#1980](https://github.com/jrnl-org/jrnl/pull/1980) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency ruff to v0.11.3 [\#1978](https://github.com/jrnl-org/jrnl/pull/1978) ([renovate[bot]](https://github.com/apps/renovate))
## [v4.2.1](https://pypi.org/project/jrnl/v4.2.1/) (2025-02-25)
[Full Changelog](https://github.com/jrnl-org/jrnl/compare/v4.2...v4.2.1)
**Documentation:**
- Typing animation in landing page is broken [\#1969](https://github.com/jrnl-org/jrnl/issues/1969)
**Packaging:**
- Update dependency pytest to \>=8.1.1 [\#1974](https://github.com/jrnl-org/jrnl/pull/1974) ([wren](https://github.com/wren))
- Update dependency black to v25 [\#1973](https://github.com/jrnl-org/jrnl/pull/1973) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency tzlocal to v5.3 [\#1972](https://github.com/jrnl-org/jrnl/pull/1972) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency ruamel.yaml to v0.18.10 [\#1967](https://github.com/jrnl-org/jrnl/pull/1967) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency jinja2 to v3.1.5 [\#1966](https://github.com/jrnl-org/jrnl/pull/1966) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency cryptography to v44 [\#1962](https://github.com/jrnl-org/jrnl/pull/1962) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency pytest-bdd to v8.1.0 [\#1952](https://github.com/jrnl-org/jrnl/pull/1952) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency poethepoet to v0.32.2 [\#1951](https://github.com/jrnl-org/jrnl/pull/1951) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency keyring to v25.6.0 [\#1948](https://github.com/jrnl-org/jrnl/pull/1948) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency ruff to v0.9.7 [\#1947](https://github.com/jrnl-org/jrnl/pull/1947) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency rich to v13.9.4 [\#1946](https://github.com/jrnl-org/jrnl/pull/1946) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency tox to v4.24.1 [\#1945](https://github.com/jrnl-org/jrnl/pull/1945) ([renovate[bot]](https://github.com/apps/renovate))
## [v4.2](https://pypi.org/project/jrnl/v4.2/) (2024-11-17)
[Full Changelog](https://github.com/jrnl-org/jrnl/compare/v4.2-beta...v4.2)
**Implemented enhancements:**
- Add Python 3.13 support [\#1893](https://github.com/jrnl-org/jrnl/issues/1893)
- Add calendar heatmap display format [\#1759](https://github.com/jrnl-org/jrnl/pull/1759) ([alichtman](https://github.com/alichtman))
**Fixed bugs:**
- -contains doesn't accept multiple search terms, doesn't work with -and [\#1877](https://github.com/jrnl-org/jrnl/issues/1877)
- Tests failing on develop branch starting with pytest-bdd 7.1.2 [\#1875](https://github.com/jrnl-org/jrnl/issues/1875)
- Ignore color when used in a pipeline [\#1839](https://github.com/jrnl-org/jrnl/issues/1839)
- Fix -contains to allow multiple terms with "OR" logic unless -and is added [\#1890](https://github.com/jrnl-org/jrnl/pull/1890) ([eigenric](https://github.com/eigenric))
**Documentation:**
- Recommend pipx as default installation method [\#1888](https://github.com/jrnl-org/jrnl/issues/1888)
- Remove documentation recommendation to install pipx through brew or pip [\#1886](https://github.com/jrnl-org/jrnl/issues/1886)
- Document security risks of using a computer that someone else has admin access to [\#1793](https://github.com/jrnl-org/jrnl/issues/1793)
- Recommend pipx as easiest installation method for all OSes and remove warning about apt [\#1889](https://github.com/jrnl-org/jrnl/pull/1889) ([micahellison](https://github.com/micahellison))
- Docs accessibility checker failure - contrast ratio [\#1934](https://github.com/jrnl-org/jrnl/issues/1934)
- Docs accessibility test runner failing [\#1932](https://github.com/jrnl-org/jrnl/issues/1932)
**Packaging:**
- Update actions/cache action to v4 [\#1847](https://github.com/jrnl-org/jrnl/pull/1847) ([renovate[bot]](https://github.com/apps/renovate))
- Update actions/setup-python action to v5 [\#1848](https://github.com/jrnl-org/jrnl/pull/1848) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency black to v24.8.0 [\#1923](https://github.com/jrnl-org/jrnl/pull/1923) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency cryptography to v43.0.3 [\#1942](https://github.com/jrnl-org/jrnl/pull/1942) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency jinja2 to v3.1.4 [\#1892](https://github.com/jrnl-org/jrnl/pull/1892) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency keyring to v25.4.1 [\#1924](https://github.com/jrnl-org/jrnl/pull/1924) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency mkdocs to v1.6.1 [\#1895](https://github.com/jrnl-org/jrnl/pull/1895) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency pa11y-ci to v3.1.0 [\#1831](https://github.com/jrnl-org/jrnl/pull/1831) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency parse-type to v0.6.4 [\#1936](https://github.com/jrnl-org/jrnl/pull/1936) ([renovate[bot]](https://github.com/apps/renovate))
- Update peter-evans/create-pull-request action to v7 [\#1929](https://github.com/jrnl-org/jrnl/pull/1929) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency poethepoet to v0.29.0 [\#1925](https://github.com/jrnl-org/jrnl/pull/1925) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency pytest to v7.4.4 [\#1845](https://github.com/jrnl-org/jrnl/pull/1845) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency pytest-bdd to v7.3.0 [\#1896](https://github.com/jrnl-org/jrnl/pull/1896) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency pytest-xdist to v3.6.1 [\#1897](https://github.com/jrnl-org/jrnl/pull/1897) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency python-dateutil to v2.9.0 [\#1898](https://github.com/jrnl-org/jrnl/pull/1898) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency requests to v2.32.3 [\#1899](https://github.com/jrnl-org/jrnl/pull/1899) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency rich to v13.9.2 [\#1937](https://github.com/jrnl-org/jrnl/pull/1937) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency ruamel.yaml to v0.18.6 [\#1855](https://github.com/jrnl-org/jrnl/pull/1855) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency ruff to v0.7.0 [\#1938](https://github.com/jrnl-org/jrnl/pull/1938) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency tox to v4.23.0 [\#1935](https://github.com/jrnl-org/jrnl/pull/1935) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency typed.js to v2.1.0 [\#1861](https://github.com/jrnl-org/jrnl/pull/1861) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency xmltodict to v0.14.2 [\#1940](https://github.com/jrnl-org/jrnl/pull/1940) ([renovate[bot]](https://github.com/apps/renovate))
- Update nick-invision/retry action to v3 [\#1851](https://github.com/jrnl-org/jrnl/pull/1851) ([renovate[bot]](https://github.com/apps/renovate))
- Update peter-evans/create-pull-request action to v6 [\#1852](https://github.com/jrnl-org/jrnl/pull/1852) ([renovate[bot]](https://github.com/apps/renovate))
## [v4.1](https://pypi.org/project/jrnl/v4.1/) (2023-11-04)
[Full Changelog](https://github.com/jrnl-org/jrnl/compare/v4.1-beta2...v4.1)
**Build:**
- Add Python 3.12 support [\#1761](https://github.com/jrnl-org/jrnl/pull/1761) ([micahellison](https://github.com/micahellison))
- Set new required build fields in the ReadTheDocs config file [\#1803](https://github.com/jrnl-org/jrnl/pull/1803) ([micahellison](https://github.com/micahellison))
- Replace flake8 and isort with ruff linter and add `black --check` to linting step [\#1763](https://github.com/jrnl-org/jrnl/pull/1763) ([micahellison](https://github.com/micahellison))
**Documentation:**
- Add note about messages going to `stderr` and the implication for piping [\#1768](https://github.com/jrnl-org/jrnl/pull/1768) ([micahellison](https://github.com/micahellison))
**Packaging:**
- Drop/replace ansiwrap dependency [\#1191](https://github.com/jrnl-org/jrnl/issues/1191)
- Use rich instead of ansiwrap to wrap text [\#1693](https://github.com/jrnl-org/jrnl/pull/1693) ([micahellison](https://github.com/micahellison))
- Update actions/checkout action to v4 [\#1788](https://github.com/jrnl-org/jrnl/pull/1788) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency black to v23.10.1 [\#1811](https://github.com/jrnl-org/jrnl/pull/1811) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency cryptography to v41.0.5 [\#1815](https://github.com/jrnl-org/jrnl/pull/1815) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency keyring to v24.2.0 [\#1760](https://github.com/jrnl-org/jrnl/pull/1760) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency mkdocs to v1.5.3 [\#1795](https://github.com/jrnl-org/jrnl/pull/1795) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency parse-type to v0.6.2 [\#1762](https://github.com/jrnl-org/jrnl/pull/1762) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency poethepoet to v0.24.1 [\#1806](https://github.com/jrnl-org/jrnl/pull/1806) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency pytest to v7.4.3 [\#1816](https://github.com/jrnl-org/jrnl/pull/1816) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency pytest-bdd to v7 [\#1807](https://github.com/jrnl-org/jrnl/pull/1807) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency rich to v13.6.0 [\#1794](https://github.com/jrnl-org/jrnl/pull/1794) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency ruamel.yaml to v0.18.3 [\#1813](https://github.com/jrnl-org/jrnl/pull/1813) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency ruff to v0.1.3 [\#1810](https://github.com/jrnl-org/jrnl/pull/1810) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency tox to v4.11.3 [\#1782](https://github.com/jrnl-org/jrnl/pull/1782) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency tzlocal to v5.2 [\#1814](https://github.com/jrnl-org/jrnl/pull/1814) ([renovate[bot]](https://github.com/apps/renovate))
**Special thanks:**
- jrnl uses UTC instead of local time for entries in WSL/Ubuntu [\#1607](https://github.com/jrnl-org/jrnl/issues/1607) investigated and reported upstream by [giuseppedandrea](https://github.com/giuseppedandrea)
## [v4.0.1](https://pypi.org/project/jrnl/v4.0.1/) (2023-06-20)
[Full Changelog](https://github.com/jrnl-org/jrnl/compare/v4.0.1-beta...v4.0.1)
**Fixed bugs:**
- jrnl crashes when running `jrnl --list --format json` and `jrnl --list --format yaml` [\#1737](https://github.com/jrnl-org/jrnl/issues/1737)
- Refactor --template code [\#1711](https://github.com/jrnl-org/jrnl/pull/1711) ([micahellison](https://github.com/micahellison))
**Build:**
- Fix linting issue in CI pipeline [\#1743](https://github.com/jrnl-org/jrnl/pull/1743) ([wren](https://github.com/wren))
**Packaging:**
- Update dependency ruamel.yaml to v0.17.28 [\#1749](https://github.com/jrnl-org/jrnl/pull/1749) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency requests to v2.31.0 [\#1748](https://github.com/jrnl-org/jrnl/pull/1748) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency ruamel.yaml to v0.17.26 [\#1746](https://github.com/jrnl-org/jrnl/pull/1746) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency tzlocal to v5 [\#1741](https://github.com/jrnl-org/jrnl/pull/1741) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency pytest-xdist to v3.3.1 [\#1740](https://github.com/jrnl-org/jrnl/pull/1740) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency poethepoet to v0.20.0 [\#1735](https://github.com/jrnl-org/jrnl/pull/1735) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency mkdocs to v1.4.3 [\#1733](https://github.com/jrnl-org/jrnl/pull/1733) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency rich to v13.3.5 [\#1729](https://github.com/jrnl-org/jrnl/pull/1729) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency requests to v2.30.0 [\#1728](https://github.com/jrnl-org/jrnl/pull/1728) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency tox to v4.5.1 [\#1727](https://github.com/jrnl-org/jrnl/pull/1727) ([renovate[bot]](https://github.com/apps/renovate))
- Update peter-evans/create-pull-request action to v5 [\#1719](https://github.com/jrnl-org/jrnl/pull/1719) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency flake8-simplify to v0.20.0 [\#1716](https://github.com/jrnl-org/jrnl/pull/1716) ([renovate[bot]](https://github.com/apps/renovate))
## [v4.0](https://pypi.org/project/jrnl/v4.0/) (2023-05-20)
[Full Changelog](https://github.com/jrnl-org/jrnl/compare/v4.0-beta3...v4.0)
🚨 **BREAKING CHANGES** 🚨
**Deprecated:**
- Drop Python 3.9 and use Python 3.11 official release [\#1611](https://github.com/jrnl-org/jrnl/pull/1611) ([micahellison](https://github.com/micahellison))
**Implemented enhancements:**
- Add message with config location and docs location when installation is complete [\#1695](https://github.com/jrnl-org/jrnl/pull/1695) ([micahellison](https://github.com/micahellison))
- Prompt to include colors in config when first running jrnl [\#1687](https://github.com/jrnl-org/jrnl/pull/1687) ([micahellison](https://github.com/micahellison))
- Add ability to use template with `--template` [\#1667](https://github.com/jrnl-org/jrnl/pull/1667) ([alichtman](https://github.com/alichtman))
- Search for entries with no tags or stars with `-not -starred` and `-not -tagged` [\#1663](https://github.com/jrnl-org/jrnl/pull/1663) ([cjcon90](https://github.com/cjcon90))
- Refactor flow for easier access to some files \(avoid things like `jrnl.Journal.Journal` and `jrnl.jrnl` co-existing\) [\#1662](https://github.com/jrnl-org/jrnl/pull/1662) ([wren](https://github.com/wren))
- Add more type hints [\#1642](https://github.com/jrnl-org/jrnl/pull/1642) ([outa](https://github.com/outa))
- Add `rich` handler to debug logging [\#1627](https://github.com/jrnl-org/jrnl/pull/1627) ([wren](https://github.com/wren))
- Rework Encryption to enable future support of other encryption methods [\#1602](https://github.com/jrnl-org/jrnl/pull/1602) ([wren](https://github.com/wren))
**Fixed bugs:**
- Only read text files that look like entries when opening folder journal [\#1697](https://github.com/jrnl-org/jrnl/pull/1697) ([micahellison](https://github.com/micahellison))
- Save empty journal on install instead of just creating a zero-length file [\#1690](https://github.com/jrnl-org/jrnl/pull/1690) ([micahellison](https://github.com/micahellison))
- Allow combinations of `--change-time`, `--delete`, and `--edit` while correctly counting the number of entries affected [\#1669](https://github.com/jrnl-org/jrnl/pull/1669) ([wren](https://github.com/wren))
- Don't save templated journal entries if the received raw text is the same as the template itself [\#1653](https://github.com/jrnl-org/jrnl/pull/1653) ([Briscoooe](https://github.com/Briscoooe))
- Add tag to XML file when edited DayOne entry and is searchable afterward [\#1648](https://github.com/jrnl-org/jrnl/pull/1648) ([jonakeys](https://github.com/jonakeys))
- Update version key in config file after version changes [\#1646](https://github.com/jrnl-org/jrnl/pull/1646) ([jonakeys](https://github.com/jonakeys))
**Build:**
- Update copyright notices for 2023 [\#1660](https://github.com/jrnl-org/jrnl/pull/1660) ([wren](https://github.com/wren))
- Fix bug where changelog is always slightly out of date on release tags [\#1631](https://github.com/jrnl-org/jrnl/pull/1631) ([wren](https://github.com/wren))
- Add `simplify` plugin to linting checks [\#1630](https://github.com/jrnl-org/jrnl/pull/1630) ([wren](https://github.com/wren))
- Add type hints [\#1614](https://github.com/jrnl-org/jrnl/pull/1614) ([outa](https://github.com/outa))
**Documentation:**
- Update contributing.md links in documentation [\#1726](https://github.com/jrnl-org/jrnl/pull/1726) ([ahosking](https://github.com/ahosking))
- Fix various typos [\#1718](https://github.com/jrnl-org/jrnl/pull/1718) ([hezhizhen](https://github.com/hezhizhen))
- Update documentation front page text [\#1698](https://github.com/jrnl-org/jrnl/pull/1698) ([micahellison](https://github.com/micahellison))
- Support mkdocs 1.4.2 and fix its missing breadcrumb [\#1691](https://github.com/jrnl-org/jrnl/pull/1691) ([micahellison](https://github.com/micahellison))
- Document temporary file extension behavior when using template [\#1686](https://github.com/jrnl-org/jrnl/pull/1686) ([micahellison](https://github.com/micahellison))
- Document `-tagged`, `-not -tagged`, and `-not -starred` [\#1684](https://github.com/jrnl-org/jrnl/pull/1684) ([micahellison](https://github.com/micahellison))
- Update documentation about privacy and security in VSCode [\#1680](https://github.com/jrnl-org/jrnl/pull/1680) ([giuseppedandrea](https://github.com/giuseppedandrea))
- Update documentation on temporary files naming [\#1673](https://github.com/jrnl-org/jrnl/pull/1673) ([giuseppedandrea](https://github.com/giuseppedandrea))
- Update docs to include time and title in arguments with `--edit` [\#1657](https://github.com/jrnl-org/jrnl/pull/1657) ([pconrad-fb](https://github.com/pconrad-fb))
- Fix markup in "Advanced Usage" doc [\#1655](https://github.com/jrnl-org/jrnl/pull/1655) ([multani](https://github.com/multani))
- Remove Windows 7 known issue since Windows 7 is no longer supported [\#1636](https://github.com/jrnl-org/jrnl/pull/1636) ([micahellison](https://github.com/micahellison))
**Packaging:**
- Lock ruamel.yaml version to v0.17.21 until bug is fixed [\#1738](https://github.com/jrnl-org/jrnl/pull/1738) ([wren](https://github.com/wren))
- Update dependency black to v23.3.0 [\#1715](https://github.com/jrnl-org/jrnl/pull/1715) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency cryptography to v40.0.2 [\#1723](https://github.com/jrnl-org/jrnl/pull/1723) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency flake8-type-checking to v2.4.0 [\#1714](https://github.com/jrnl-org/jrnl/pull/1714) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency flakeheaven to v3.3.0 [\#1722](https://github.com/jrnl-org/jrnl/pull/1722) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency ipdb to v0.13.13 [\#1703](https://github.com/jrnl-org/jrnl/pull/1703) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency poethepoet to v0.19.0 [\#1709](https://github.com/jrnl-org/jrnl/pull/1709) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency pytest to v7.3.1 [\#1720](https://github.com/jrnl-org/jrnl/pull/1720) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency pytest-xdist to v3.2.1 [\#1705](https://github.com/jrnl-org/jrnl/pull/1705) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency rich to v13.3.4 [\#1713](https://github.com/jrnl-org/jrnl/pull/1713) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency tox to v4.4.7 [\#1707](https://github.com/jrnl-org/jrnl/pull/1707) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency tzlocal to v4.3 [\#1708](https://github.com/jrnl-org/jrnl/pull/1708) ([renovate[bot]](https://github.com/apps/renovate))
## [v3.3](https://pypi.org/project/jrnl/v3.3/) (2022-10-29)
[Full Changelog](https://github.com/jrnl-org/jrnl/compare/v3.3-beta2...v3.3)
**Implemented enhancements:**
- Change default config to use journal key [\#1594](https://github.com/jrnl-org/jrnl/pull/1594) ([micahellison](https://github.com/micahellison))
- Add machine readable --list output [\#1592](https://github.com/jrnl-org/jrnl/pull/1592) ([apainintheneck](https://github.com/apainintheneck))
**Fixed bugs:**
- Fix bug for new `--list --format` options when no default journal is specified [\#1621](https://github.com/jrnl-org/jrnl/pull/1621) ([wren](https://github.com/wren))
- Don't create empty file when attempting a YAML export to a non-existing folder [\#1600](https://github.com/jrnl-org/jrnl/pull/1600) ([outa](https://github.com/outa))
**Build:**
- Update `.gitignore` [\#1604](https://github.com/jrnl-org/jrnl/pull/1604) ([wren](https://github.com/wren))
- Fix Docs Accessibility Testing [\#1588](https://github.com/jrnl-org/jrnl/pull/1588) ([wren](https://github.com/wren))
- Update to use renamed flag for `brew bump-formula-pr` [\#1587](https://github.com/jrnl-org/jrnl/pull/1587) ([wren](https://github.com/wren))
- Update peter-evans/create-pull-request action to v4 [\#1585](https://github.com/jrnl-org/jrnl/pull/1585) ([renovate[bot]](https://github.com/apps/renovate))
- Update actions/setup-python action to v4 [\#1583](https://github.com/jrnl-org/jrnl/pull/1583) ([renovate[bot]](https://github.com/apps/renovate))
- Update actions/checkout action to v3 [\#1582](https://github.com/jrnl-org/jrnl/pull/1582) ([renovate[bot]](https://github.com/apps/renovate))
- Update actions/cache action to v3 [\#1581](https://github.com/jrnl-org/jrnl/pull/1581) ([renovate[bot]](https://github.com/apps/renovate))
- Replace Dependabot with Renovate [\#1575](https://github.com/jrnl-org/jrnl/pull/1575) ([renovate[bot]](https://github.com/apps/renovate))
**Documentation:**
- Add documentation about how the editor must be a blocking process [\#1456](https://github.com/jrnl-org/jrnl/issues/1456)
- Document that editors must be blocking processes [\#1624](https://github.com/jrnl-org/jrnl/pull/1624) ([micahellison](https://github.com/micahellison))
- Remove wrong option in configuration file reference [\#1618](https://github.com/jrnl-org/jrnl/pull/1618) ([DSiekmeier](https://github.com/DSiekmeier))
- Update YAML export description in docs [\#1591](https://github.com/jrnl-org/jrnl/pull/1591) ([apainintheneck](https://github.com/apainintheneck))
- Update dependency jinja2 to v3.1.2 [\#1579](https://github.com/jrnl-org/jrnl/pull/1579) ([renovate[bot]](https://github.com/apps/renovate))
- Update dependency typed.js to v2.0.12 [\#1578](https://github.com/jrnl-org/jrnl/pull/1578) ([renovate[bot]](https://github.com/apps/renovate))
- Add hint for how to get vi to go to end-of-file [\#1563](https://github.com/jrnl-org/jrnl/pull/1563) ([pjz](https://github.com/pjz))
**Packaging:**
- Pin dependencies [\#1577](https://github.com/jrnl-org/jrnl/pull/1577) ([renovate[bot]](https://github.com/apps/renovate))
## [v3.2](https://pypi.org/project/jrnl/v3.2/) (2022-09-03)
[Full Changelog](https://github.com/jrnl-org/jrnl/compare/v3.2-beta...v3.2)
**Implemented enhancements:**
- Update issue & PR templates to use forms [\#1559](https://github.com/jrnl-org/jrnl/issues/1559)
- Suppress "Entry added" message if using default journal [\#1561](https://github.com/jrnl-org/jrnl/pull/1561) ([micahellison](https://github.com/micahellison))
- Add message showing the number of search results [\#1524](https://github.com/jrnl-org/jrnl/pull/1524) ([apainintheneck](https://github.com/apainintheneck))
**Build:**
- Quick fix follow up for actionlint [\#1565](https://github.com/jrnl-org/jrnl/pull/1565) ([wren](https://github.com/wren))
**Documentation:**
- Remove note in contributing docs about gh-pages branch that we no longer use [\#1566](https://github.com/jrnl-org/jrnl/pull/1566) ([micahellison](https://github.com/micahellison))
## [v3.1](https://pypi.org/project/jrnl/v3.1/) (2022-08-21)
[Full Changelog](https://github.com/jrnl-org/jrnl/compare/v3.1-beta2...v3.1)
**Implemented enhancements:**
- Update tzlocal to v4.x and remove pytz dependency [\#1528](https://github.com/jrnl-org/jrnl/pull/1528) ([outa](https://github.com/outa))
- Add linewrap option 'auto' [\#1507](https://github.com/jrnl-org/jrnl/pull/1507) ([jonakeys](https://github.com/jonakeys))
**Fixed bugs:**
- Update formatting function to better account for indentation [\#1541](https://github.com/jrnl-org/jrnl/pull/1541) ([wren](https://github.com/wren))
- Export to file\(s\) when first line/title of an entry is very long [\#1527](https://github.com/jrnl-org/jrnl/pull/1527) ([jonakeys](https://github.com/jonakeys))
- Fixed index out of range error in fancy exporter [\#1522](https://github.com/jrnl-org/jrnl/pull/1522) ([apainintheneck](https://github.com/apainintheneck))
**Build:**
- Add actionlint to testing pipelines [\#1555](https://github.com/jrnl-org/jrnl/pull/1555) ([wren](https://github.com/wren))
- Fix docs pipeline, make docs tests easier to run locally and on different OSes [\#1554](https://github.com/jrnl-org/jrnl/pull/1554) ([wren](https://github.com/wren))
**Documentation:**
- Reformat contributor appreciation on `--help` screen [\#1556](https://github.com/jrnl-org/jrnl/pull/1556) ([xeruf](https://github.com/xeruf))
- Clean up copyright notices and version screen [\#1553](https://github.com/jrnl-org/jrnl/pull/1553) ([wren](https://github.com/wren))
**Packaging:**
- Bump pyproject-flake8 from 0.0.1a4 to 0.0.1a5 [\#1552](https://github.com/jrnl-org/jrnl/pull/1552) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump keyring from 23.7.0 to 23.8.2 [\#1551](https://github.com/jrnl-org/jrnl/pull/1551) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump yq from 3.0.2 to 3.1.0 [\#1546](https://github.com/jrnl-org/jrnl/pull/1546) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump poethepoet from 0.15.0 to 0.16.0 [\#1542](https://github.com/jrnl-org/jrnl/pull/1542) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump keyring from 23.6.0 to 23.7.0 [\#1539](https://github.com/jrnl-org/jrnl/pull/1539) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump rich from 12.4.4 to 12.5.1 [\#1538](https://github.com/jrnl-org/jrnl/pull/1538) ([dependabot[bot]](https://github.com/apps/dependabot))
## [v3.0](https://pypi.org/project/jrnl/v3.0/) (2022-07-09)
[Full Changelog](https://github.com/jrnl-org/jrnl/compare/v3.0-beta2...v3.0)
🚨 **BREAKING CHANGES** 🚨
**Deprecated:**
- Drop support for Python 3.7 and 3.8 [\#1412](https://github.com/jrnl-org/jrnl/pull/1412) ([micahellison](https://github.com/micahellison))
**Implemented enhancements:**
- Show name of journal when creating a password/encrypting [\#1478](https://github.com/jrnl-org/jrnl/pull/1478) ([jonakeys](https://github.com/jonakeys))
- Rework how all output and messaging works in jrnl [\#1475](https://github.com/jrnl-org/jrnl/pull/1475) ([wren](https://github.com/wren))
- Implement --change-time flag [\#1452](https://github.com/jrnl-org/jrnl/pull/1452) ([richardjs](https://github.com/richardjs))
- Reformat additional messages and finish centralizing exception handling [\#1424](https://github.com/jrnl-org/jrnl/pull/1424) ([wren](https://github.com/wren))
- Reformat messages and add new centralized exception handling [\#1417](https://github.com/jrnl-org/jrnl/pull/1417) ([wren](https://github.com/wren))
**Fixed bugs:**
- Display message when no edits take place [\#1510](https://github.com/jrnl-org/jrnl/pull/1510) ([apainintheneck](https://github.com/apainintheneck))
- Fixed error related to display\_format in config file for some values [\#1495](https://github.com/jrnl-org/jrnl/pull/1495) ([apainintheneck](https://github.com/apainintheneck))
- Create folder if config ends with \(back\)slash [\#1492](https://github.com/jrnl-org/jrnl/pull/1492) ([jonakeys](https://github.com/jonakeys))
- `-not` search parameter no longer opens editor [\#1490](https://github.com/jrnl-org/jrnl/pull/1490) ([apainintheneck](https://github.com/apainintheneck))
- Fix TypeError when using debug flag [\#1484](https://github.com/jrnl-org/jrnl/pull/1484) ([jonakeys](https://github.com/jonakeys))
- Prompt for password change when using 'jrnl --encrypt' on already encrypted journal [\#1477](https://github.com/jrnl-org/jrnl/pull/1477) ([jonakeys](https://github.com/jonakeys))
- Always expand all paths \(journals, templates, etc\) [\#1468](https://github.com/jrnl-org/jrnl/pull/1468) ([apainintheneck](https://github.com/apainintheneck))
- The `-not` option with no arguments now outputs error instead of stack trace [\#1466](https://github.com/jrnl-org/jrnl/pull/1466) ([apainintheneck](https://github.com/apainintheneck))
- Give a proper message when trying to use an empty config file [\#1461](https://github.com/jrnl-org/jrnl/pull/1461) ([jonakeys](https://github.com/jonakeys))
- Display "No entry to save, because no text was received" after empty entry on cmdline [\#1459](https://github.com/jrnl-org/jrnl/pull/1459) ([apainintheneck](https://github.com/apainintheneck))
- Yaml export errors now don't show stack trace [\#1449](https://github.com/jrnl-org/jrnl/pull/1449) ([apainintheneck](https://github.com/apainintheneck))
**Build:**
- Pin `pytest-bdd` to \<6.0 to temporarily avoid breaking changes [\#1536](https://github.com/jrnl-org/jrnl/pull/1536) ([wren](https://github.com/wren))
- Reduce difference between local and CI environments [\#1518](https://github.com/jrnl-org/jrnl/pull/1518) ([wren](https://github.com/wren))
- Add bdd tests for jrnl installation [\#1513](https://github.com/jrnl-org/jrnl/pull/1513) ([apainintheneck](https://github.com/apainintheneck))
- Stop hardcoding bot info in changelog pipeline [\#1506](https://github.com/jrnl-org/jrnl/pull/1506) ([wren](https://github.com/wren))
- Fix Poetry caching for accessibility tests [\#1505](https://github.com/jrnl-org/jrnl/pull/1505) ([wren](https://github.com/wren))
- Implement Tox for testing [\#1504](https://github.com/jrnl-org/jrnl/pull/1504) ([wren](https://github.com/wren))
- Replace `make` with python alternative \(`poe`\) [\#1503](https://github.com/jrnl-org/jrnl/pull/1503) ([wren](https://github.com/wren))
- Update copyright year [\#1502](https://github.com/jrnl-org/jrnl/pull/1502) ([wren](https://github.com/wren))
- Add Python 3.11 to PR tests [\#1500](https://github.com/jrnl-org/jrnl/pull/1500) ([micahellison](https://github.com/micahellison))
- Pin jinja2 in docs requirements to keep readthedocs builds from failing [\#1439](https://github.com/jrnl-org/jrnl/pull/1439) ([micahellison](https://github.com/micahellison))
- Tidy up git ignore [\#1414](https://github.com/jrnl-org/jrnl/pull/1414) ([nelnog](https://github.com/nelnog))
**Documentation:**
- Document --change-time in web-based docs' command line reference [\#1471](https://github.com/jrnl-org/jrnl/pull/1471) ([micahellison](https://github.com/micahellison))
**Packaging:**
- Bump cryptography from 37.0.2 to 37.0.3 [\#1516](https://github.com/jrnl-org/jrnl/pull/1516) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump poethepoet from 0.13.1 to 0.14.0 [\#1514](https://github.com/jrnl-org/jrnl/pull/1514) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump keyring from 23.5.1 to 23.6.0 [\#1499](https://github.com/jrnl-org/jrnl/pull/1499) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump pyxdg from 0.27 to 0.28 [\#1497](https://github.com/jrnl-org/jrnl/pull/1497) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump keyring from 23.5.0 to 23.5.1 [\#1487](https://github.com/jrnl-org/jrnl/pull/1487) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump cryptography from 37.0.1 to 37.0.2 [\#1467](https://github.com/jrnl-org/jrnl/pull/1467) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump cryptography from 36.0.2 to 37.0.1 [\#1462](https://github.com/jrnl-org/jrnl/pull/1462) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump pytest from 7.1.1 to 7.1.2 [\#1458](https://github.com/jrnl-org/jrnl/pull/1458) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump pyproject-flake8 from 0.0.1a3 to 0.0.1a4 [\#1447](https://github.com/jrnl-org/jrnl/pull/1447) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump black from 22.1.0 to 22.3.0 [\#1442](https://github.com/jrnl-org/jrnl/pull/1442) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump mkdocs from 1.2.3 to 1.3.0 [\#1441](https://github.com/jrnl-org/jrnl/pull/1441) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump pyproject-flake8 from 0.0.1a2 to 0.0.1a3 [\#1440](https://github.com/jrnl-org/jrnl/pull/1440) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump pytz from 2021.3 to 2022.1 [\#1438](https://github.com/jrnl-org/jrnl/pull/1438) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump pytest from 7.0.1 to 7.1.1 [\#1430](https://github.com/jrnl-org/jrnl/pull/1430) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump cryptography from 36.0.1 to 36.0.2 [\#1427](https://github.com/jrnl-org/jrnl/pull/1427) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump yq from 2.13.0 to 2.14.0 [\#1418](https://github.com/jrnl-org/jrnl/pull/1418) ([dependabot[bot]](https://github.com/apps/dependabot))
- Replace PyYAML with ruamel.yaml [\#1416](https://github.com/jrnl-org/jrnl/pull/1416) ([micahellison](https://github.com/micahellison))
- Bump pytest from 6.2.5 to 7.0.0 [\#1407](https://github.com/jrnl-org/jrnl/pull/1407) ([dependabot[bot]](https://github.com/apps/dependabot))
## [v2.8.4](https://pypi.org/project/jrnl/v2.8.4/) (2022-02-12)
[Full Changelog](https://github.com/jrnl-org/jrnl/compare/v2.8.4-beta2...v2.8.4)
[Full Changelog](https://github.com/jrnl-org/jrnl/compare/v2.8.4-beta1...HEAD)
**Implemented enhancements:**
- Add --co alias for --config-override [\#1394](https://github.com/jrnl-org/jrnl/issues/1394)
- Support Python 3.11 [\#1371](https://github.com/jrnl-org/jrnl/issues/1371)
- Add hash as a default tag symbol for new jrnl config file [\#1398](https://github.com/jrnl-org/jrnl/pull/1398) ([micahellison](https://github.com/micahellison))
- Add --config-file argument to use alternate config file at runtime [\#1290](https://github.com/jrnl-org/jrnl/pull/1290) ([samuelgregorovic](https://github.com/samuelgregorovic))
**Fixed bugs:**
- Certs broken on website [\#1408](https://github.com/jrnl-org/jrnl/issues/1408)
- Specifying 'today' does not filter by year, also returns entries from same date in prior years [\#1391](https://github.com/jrnl-org/jrnl/issues/1391)
**Documentation:**
- Fix nested navigation styling on docs site [\#1349](https://github.com/jrnl-org/jrnl/issues/1349)
- Separate out reference documentation for command line arguments and config file [\#1300](https://github.com/jrnl-org/jrnl/issues/1300)
- Fix styling on documentation sidebar [\#1395](https://github.com/jrnl-org/jrnl/pull/1395) ([wren](https://github.com/wren))
- Add reference documentation to docs site and separate out "Tips and Tricks" and "External Editors" from "Recipes" [\#1332](https://github.com/jrnl-org/jrnl/pull/1332) ([micahellison](https://github.com/micahellison))
**Packaging:**
- Bump black from 21.12b0 to 22.1.0 [\#1404](https://github.com/jrnl-org/jrnl/pull/1404) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump ipython from 7.28.0 to 7.31.1 [\#1401](https://github.com/jrnl-org/jrnl/pull/1401) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump asteval from 0.9.25 to 0.9.26 [\#1400](https://github.com/jrnl-org/jrnl/pull/1400) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump keyring from 23.4.0 to 23.5.0 [\#1392](https://github.com/jrnl-org/jrnl/pull/1392) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump cryptography from 36.0.0 to 36.0.1 [\#1389](https://github.com/jrnl-org/jrnl/pull/1389) ([dependabot[bot]](https://github.com/apps/dependabot))
## [v2.8.4-beta1](https://pypi.org/project/jrnl/v2.8.4-beta1/) (2021-12-11)
[Full Changelog](https://github.com/jrnl-org/jrnl/compare/v2.8.4-beta...v2.8.4-beta1)
**Fixed bugs:**
- Wrong delete count when manually changing entries [\#1198](https://github.com/jrnl-org/jrnl/issues/1198)
- Add added option to \_print\_edited\_summary [\#1366](https://github.com/jrnl-org/jrnl/pull/1366) ([piero-vic](https://github.com/piero-vic))
**Build:**
- Pytest BDD follow-up tasks [\#1287](https://github.com/jrnl-org/jrnl/issues/1287)
- Improve handling of mocking logic in pytest [\#1382](https://github.com/jrnl-org/jrnl/pull/1382) ([wren](https://github.com/wren))
- Use full Python version for GitHub Actions cache key [\#1373](https://github.com/jrnl-org/jrnl/pull/1373) ([micahellison](https://github.com/micahellison))
**Packaging:**
- Bump yq from 2.12.2 to 2.13.0 [\#1385](https://github.com/jrnl-org/jrnl/pull/1385) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump black from 21.11b1 to 21.12b0 [\#1384](https://github.com/jrnl-org/jrnl/pull/1384) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump keyring from 23.3.0 to 23.4.0 [\#1383](https://github.com/jrnl-org/jrnl/pull/1383) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump keyring from 23.2.1 to 23.3.0 [\#1381](https://github.com/jrnl-org/jrnl/pull/1381) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump cryptography from 35.0.0 to 36.0.0 [\#1379](https://github.com/jrnl-org/jrnl/pull/1379) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump black from 21.10b0 to 21.11b1 [\#1375](https://github.com/jrnl-org/jrnl/pull/1375) ([dependabot[bot]](https://github.com/apps/dependabot))
## [v2.8.4-beta](https://pypi.org/project/jrnl/v2.8.4-beta/) (2021-11-06)
[Full Changelog](https://github.com/jrnl-org/jrnl/compare/v2.8.3...v2.8.4-beta)
**Implemented enhancements:**
- Specify an alternate config file in the command line [\#1170](https://github.com/jrnl-org/jrnl/issues/1170)
- Add --config-file argument to use alternate config file at runtime [\#1290](https://github.com/jrnl-org/jrnl/pull/1290) ([samuelgregorovic](https://github.com/samuelgregorovic))
**Fixed bugs:**
- Support pytest-bdd 5 [\#1364](https://github.com/jrnl-org/jrnl/issues/1364)
**Build:**
- Use Python 3.10 stable in CI [\#1362](https://github.com/jrnl-org/jrnl/pull/1362) ([micahellison](https://github.com/micahellison))
- Switch from poetry to poetry-core [\#1359](https://github.com/jrnl-org/jrnl/pull/1359) ([fabaff](https://github.com/fabaff))
- Add more steps to `pytest`, fully remove `behave` [\#1347](https://github.com/jrnl-org/jrnl/pull/1347) ([wren](https://github.com/wren))
**Documentation:**
- Fix styling on documentation sidebar [\#1395](https://github.com/jrnl-org/jrnl/pull/1395) ([wren](https://github.com/wren))
- Document folder journal and DayOne journal types [\#1326](https://github.com/jrnl-org/jrnl/issues/1326)
- Move and expand contributing.md content into docs site [\#1180](https://github.com/jrnl-org/jrnl/issues/1180)
- Added Recipe for visualizing Markdown in the CLI [\#1354](https://github.com/jrnl-org/jrnl/pull/1354) ([viegasfh](https://github.com/viegasfh))
- Fix recipe 'Launch a terminal for rapid logging' [\#1351](https://github.com/jrnl-org/jrnl/pull/1351) ([zapateo](https://github.com/zapateo))
- Fix readme splash and add changelog link to readme [\#1339](https://github.com/jrnl-org/jrnl/pull/1339) ([micahellison](https://github.com/micahellison))
- Add reference documentation to docs site and separate out "Tips and Tricks" and "External Editors" from "Recipes" [\#1332](https://github.com/jrnl-org/jrnl/pull/1332) ([micahellison](https://github.com/micahellison))
- Document journal types [\#1331](https://github.com/jrnl-org/jrnl/pull/1331) ([micahellison](https://github.com/micahellison))
**Packaging:**
- Bump asteval from 0.9.25 to 0.9.26 [\#1400](https://github.com/jrnl-org/jrnl/pull/1400) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump black from 21.7b0 to 22.1.0 [\#1404](https://github.com/jrnl-org/jrnl/pull/1404) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump cryptography from 3.4.8 to 36.0.1 [\#1389](https://github.com/jrnl-org/jrnl/pull/1389) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump ipython from 7.28.0 to 7.31.1 [\#1401](https://github.com/jrnl-org/jrnl/pull/1401) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump keyring from 23.1.0 to 23.5.0 [\#1392](https://github.com/jrnl-org/jrnl/pull/1392) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump mkdocs from 1.2.2 to 1.2.3 [\#1355](https://github.com/jrnl-org/jrnl/pull/1355) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump pytest from 6.2.4 to 6.2.5 [\#1334](https://github.com/jrnl-org/jrnl/pull/1334) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump black from 21.9b0 to 21.10b0 [\#1370](https://github.com/jrnl-org/jrnl/pull/1370) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump pytest-bdd from 4.1.0 to 5.0.0 [\#1368](https://github.com/jrnl-org/jrnl/pull/1368) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump mkdocs from 1.2.2 to 1.2.3 [\#1355](https://github.com/jrnl-org/jrnl/pull/1355) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump pytz from 2021.1 to 2021.3 [\#1348](https://github.com/jrnl-org/jrnl/pull/1348) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump yq from 2.12.2 to 2.13.0 [\#1385](https://github.com/jrnl-org/jrnl/pull/1385) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump cryptography from 3.4.8 to 35.0.0 [\#1345](https://github.com/jrnl-org/jrnl/pull/1345) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump black from 21.8b0 to 21.9b0 [\#1343](https://github.com/jrnl-org/jrnl/pull/1343) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump keyring from 23.1.0 to 23.2.1 [\#1342](https://github.com/jrnl-org/jrnl/pull/1342) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump pytest from 6.2.4 to 6.2.5 [\#1334](https://github.com/jrnl-org/jrnl/pull/1334) ([dependabot[bot]](https://github.com/apps/dependabot))
- Bump black from 21.7b0 to 21.8b0 [\#1333](https://github.com/jrnl-org/jrnl/pull/1333) ([dependabot[bot]](https://github.com/apps/dependabot))
## [v2.8.3](https://pypi.org/project/jrnl/v2.8.3/) (2021-09-06)

View file

@ -59,7 +59,7 @@ representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by [emailing the maintainers](mailto:maintainers@jrnl.sh).
reported by [emailing the maintainers](mailto:jrnl-sh@googlegroups.com).
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the

View file

@ -1,8 +1,5 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
<!-- Copyright (C) 2012-2021 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html -->
# Contributing
See "[Contributing](docs/contributing.md)" in the `docs` directory.

39
Makefile Normal file
View file

@ -0,0 +1,39 @@
# A Makefile for commands I run frequently:
clean:
rm -rf dist
rm -rf _static
rm -rf jrnl.egg-info
rm -rf _build
rm -rf _sources
rm -rf _static
rm -rf site/
rm -f *.html
html:
poetry run mkdocs serve
format: ## Format files to match style
poetry run black .
lint: ## Check style with various tools
poetry check
poetry run pflake8 jrnl tests
poetry run black --check --diff .
unit: # unit tests
poetry run pytest tests/unit
bdd: # bdd tests
poetry run pytest tests/bdd --gherkin-terminal-reporter --tb=native
bdd-debug: # bdd tests
poetry run pytest tests/bdd --gherkin-terminal-reporter --tb=native -x -vv
test: lint unit bdd
build:
poetry build
install: clean ## install the package to the active Python's site-packages
poetry install

View file

@ -1,8 +1,3 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
<p align="center">
<a href="https://jrnl.sh">
<img align="center" src="https://raw.githubusercontent.com/jrnl-org/jrnl/develop/docs_theme/assets/readme-header.png"/>
@ -19,7 +14,7 @@ jrnl
====
_To get help, [submit an issue](https://github.com/jrnl-org/jrnl/issues/new/choose) on
GitHub._
Github._
`jrnl` is a simple journal application for the command line.
@ -70,7 +65,7 @@ src="https://opencollective.com/jrnl/contributors.svg?width=890&button=false"
/></a>
If you'd also like to help make `jrnl` better, please see our [contributing
documentation](docs/contributing.md).
documentation](CONTRIBUTING.md).
### Financial Backers

View file

@ -1,6 +1,6 @@
# Security
If you've discovered a potential security issue in jrnl, please contact the maintainers at [maintainers@jrnl.sh](mailto:maintainers@jrnl.sh).
If you've discovered a potential security issue in jrnl, please contact the maintainers at [jrnl-sh@googlegroups.com](mailto:jrnl-sh@googlegroups.com).
You can also feel free to [open an issue](https://github.com/jrnl-org/jrnl/issues/new/choose) (but please don't disclose the vulnerability) in case the email goes to spam.

View file

@ -1,7 +1,5 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
<!-- Copyright (C) 2012-2021 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html -->
# Advanced Usage
@ -20,8 +18,8 @@ for example:
``` yaml
journals:
default: ~/journal.txt
work: ~/work.txt
default: ~\journal.txt
work: ~\work.txt
```
The `default` journal gets created the first time you start `jrnl`
@ -42,11 +40,11 @@ If your `jrnl.yaml` looks like this:
``` yaml
encrypt: false
journals:
default: ~/journal.txt
work:
journal: ~/work.txt
encrypt: true
food: ~/my_recipes.txt
default: ~/journal.txt
work:
journal: ~/work.txt
encrypt: true
food: ~/my_recipes.txt
```
Your `default` and your `food` journals won't be encrypted, however your
@ -59,7 +57,7 @@ that journal.
Consider the following example configuration
``` yaml
```yaml
editor: vi -c startinsert
journals:
default: ~/journal.txt
@ -80,22 +78,22 @@ The `work` journal is encrypted, prints to `json` by default, and is edited usin
You can override a configuration field for the current instance of `jrnl` using `--config-override CONFIG_KEY CONFIG_VALUE` where `CONFIG_KEY` is a valid configuration field, specified in dot notation and `CONFIG_VALUE` is the (valid) desired override value. The dot notation can be used to change config keys within other keys, such as `colors.title` for the `title` key within the `colors` key.
You can specify multiple overrides as multiple calls to `--config-override`.
!!! note
These overrides allow you to modify ***any*** field of your jrnl configuration. We trust that you know what you are doing.
#### Examples:
``` sh
# Create an entry using the `stdin` prompt, for rapid logging
#Create an entry using the `stdin` prompt, for rapid logging
jrnl --config-override editor ""
# Populate a project's log
#Populate a project's log
jrnl --config-override journals.todo "$(git rev-parse --show-toplevel)/todo.txt" todo find my towel
# Pass multiple overrides
#Pass multiple overrides
jrnl --config-override display_format fancy --config-override linewrap 20 \
--config-override colors.title green
```
### Using an alternate config
@ -105,7 +103,7 @@ You can specify an alternate configuration file for the current instance of `jrn
#### Examples:
``` sh
```
# Use personalised configuration file for personal journal entries
jrnl --config-file ~/foo/jrnl/personal-config.yaml
@ -115,3 +113,12 @@ jrnl --config-file ~/foo/jrnl/work-config.yaml
# Use default configuration file (created on first run)
jrnl
```
## Known Issues
### Unicode on Windows
The Windows shell prior to Windows 7 has issues with unicode encoding.
To use non-ascii characters, first tweak Python to recognize the encoding by adding `'cp65001': 'utf_8'`, to `Lib/encoding/aliases.py`. Then, change the codepage with `chcp 1252` before using `jrnl`.
(Related issue: [#486](https://github.com/jrnl-org/jrnl/issues/486))

View file

@ -1,8 +1,5 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
<!-- Copyright (C) 2012-2021 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html -->
# Contributing to jrnl
We welcome contributions to jrnl, whether it's through reporting bugs, improving the documentation, testing releases, engaging in discussion on features and bugs, or writing code.
@ -27,7 +24,9 @@ Please report bugs by [opening a new issue](https://github.com/jrnl-org/jrnl/iss
If you find a typo or a mistake in the docs, please fix it right away and send a pull request. If you're unsure what to change but still see a problem, you can [open a new issue](https://github.com/jrnl-org/jrnl/issues/new/choose) with the "Documentation change" type.
To edit the documentation, edit the `docs/*.md` files on the **develop** branch. You can see the result by running `poe docs-run` inside the project's root directory, then navigating your browser to [localhost:8000](http://localhost:8000).
To edit the documentation, edit the `docs/*.md` files on the **develop** branch. You can see the result by running `make html` (or `poetry run mkdocs serve` if on Windows) inside the project's root directory, then navigating your browser to [localhost:8000](http://localhost:8000).
The `gh-pages` branch is automatically maintained and generated after your changes are merged. You should never have to edit that branch.
### External editors and tips and tricks
@ -83,20 +82,16 @@ In general, pull requests should be made on the `develop` branch.
### Common development commands
You can find an inventory of commands in the `pyproject.toml`. Users can run the commands by typing `poe` followed by the name of the command ([Poe the Poet](https://github.com/nat-n/poethepoet) can be installed on its own, or as part of `poetry install`).
You can find an inventory of commands in the `makefile`. \*nix users can run the commands by typing `make` followed by the name of the command; however, Windows users will need to type out the commands directly, or install a third-party make tool such as [GNU Make for Windows](http://gnuwin32.sourceforge.net/packages/make.htm).
A typical development workflow includes:
* Installing dependencies:
* `poetry install`
* Activate virtual environment:
* `poetry shell`
* Installing dependencies: `poetry install`
* Running tests: `make test`
* Running the source in a virtual environment:
* `poetry shell`
* `jrnl` (with or without arguments as necessary)
* Running tests:
* `poe test`
* Formatting the code to standardize its style:
* `poe format`
* Linting the code to standardize its style: `make lint`
### Updating automated tests

View file

@ -1,8 +1,5 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
<!-- Copyright (C) 2012-2021 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html -->
# Encryption
## A Note on Security
@ -100,16 +97,16 @@ something like `pip3 install crytography`)
import base64
import getpass
from pathlib import Path
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
filepath = input("journal file path: ")
password = getpass.getpass("Password: ")
with open(Path(filepath), "rb") as f:
with open(Path(filepath),"rb") as f:
ciphertext = f.read()
password = password.encode("utf-8")
@ -123,7 +120,7 @@ kdf = PBKDF2HMAC(
key = base64.urlsafe_b64encode(kdf.derive(password))
print(Fernet(key).decrypt(ciphertext).decode("utf-8"))
print(Fernet(key).decrypt(ciphertext).decode('utf-8'))
```
**Example for jrnl v1 files**:
@ -137,19 +134,19 @@ like `pip3 install pycrypto`)
"""
import argparse
from Crypto.Cipher import AES
import getpass
import hashlib
from Crypto.Cipher import AES
import sys
parser = argparse.ArgumentParser()
parser.add_argument("filepath", help="journal file to decrypt")
args = parser.parse_args()
pwd = getpass.getpass()
key = hashlib.sha256(pwd.encode("utf-8")).digest()
key = hashlib.sha256(pwd.encode('utf-8')).digest()
with open(args.filepath, "rb") as f:
with open(args.filepath, 'rb') as f:
ciphertext = f.read()
crypto = AES.new(key, AES.MODE_CBC, ciphertext[:16])

View file

@ -1,44 +1,13 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
# External editors
Configure your preferred external editor by updating the `editor` option
in your [configuration file](./reference-config-file.md#editor). If your editor is not
in your operating system's `PATH` environment variable, then you will have to
enter the full path of your editor.
Once it's configured, you can create an entry as a new document in your editor using the `jrnl`
command by itself:
``` text
jrnl
```
You can specify the time and title of the entry as usual on the first line of the document.
If you want, you can skip the editor by including a quick entry with the `jrnl` command:
``` text
jrnl yesterday: All my troubles seemed so far away.
```
If you want to start the entry on the command line and continue writing in your chosen editor,
use the `--edit` flag. For example:
``` text
jrnl yesterday: All my troubles seemed so far away. --edit
```
in your [configuration file](./reference-config-file.md#editor)
!!! note
To save and log any entry edits, save and close the file.
All editors must be [blocking processes](https://en.wikipedia.org/wiki/Blocking_(computing)) to work with jrnl. Some editors, such as [micro](https://micro-editor.github.io/), are blocking by default, though others can be made to block with additional arguments, such as many of those documented below. If jrnl opens your editor but finishes running immediately, then your editor is not a blocking process, and you may be able to correct that with one of the suggestions below.
Please see [this section](./privacy-and-security.md#editor-history) about how
your editor might leak sensitive information and how to mitigate that risk.
If your editor is not in your operating system's `PATH` environment variable,
then you will have to enter in the full path of your editor.
## Sublime Text
@ -74,17 +43,6 @@ back to journal. In the case of MacVim, this is `-f`:
editor: "mvim -f"
```
## Vim/Neovim
To use any of the Vim derivatives as editor in Linux, simply set the `editor`
to the executable:
```yaml
editor: "vim"
# or
editor: "nvim"
```
## iA Writer
On OS X, you can use the fabulous [iA

View file

@ -1,8 +1,5 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
<!-- Copyright (C) 2012-2021 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html -->
# Formats
`jrnl` supports a variety of alternate formats. These can be used to display your
@ -117,11 +114,6 @@ These formats are mainly intended for piping or exporting your journal to other
programs. Even so, they can still be used in the same way as any other format (like
written to a file, or displayed in your terminal, if you want).
!!! note
You may see boxed messages like "2 entries found" when using these formats, but
those messages are written to `stderr` instead of `stdout`, and won't be piped when
using the `|` operator.
### JSON
``` sh
@ -276,14 +268,13 @@ supported by many programs and programming languages.
### YAML
``` sh
jrnl --format yaml --file 'my_directory/'
jrnl --format yaml
```
This outputs your journal into YAML format. YAML is a commonly used data format and is
supported by many programs and programming languages. [Exporting to directories](#exporting-to-directories) is the
only supported YAML export option and each entry will be written to a separate file.
supported by many programs and programming languages.
**Example file**:
**Example output**:
``` yaml
title: This is the second sample entry
date: 2020-07-01 20:00
@ -341,14 +332,14 @@ jrnl --format json > myjournal.json
If the `--file` argument is a directory, jrnl will export each entry into an individual file:
``` sh
jrnl --format yaml --file my_entries/
jrnl --format json --file my_entries/
```
The contents of `my_entries/` will then look like this:
``` output
my_entries/
|- 2013_06_03_a-beautiful-day.yaml
|- 2013_06_07_dinner-with-gabriel.yaml
|- 2013_06_03_a-beautiful-day.json
|- 2013_06_07_dinner-with-gabriel.json
|- ...
```

View file

@ -1,20 +1,27 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
<!-- Copyright (C) 2012-2021 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html -->
# Getting started
## Installation
The easiest way to install `jrnl` is using
[pipx](https://pipx.pypa.io/stable/installation/)
with [Python](https://www.python.org/) 3.10+:
On Mac and Linux, the easiest way to install `jrnl` is using
[Homebrew](http://brew.sh/):
``` sh
brew install jrnl
```
On other platforms, install `jrnl` using [Python](https://www.python.org/) 3.6+ and [pipx](https://pipxproject.github.io/pipx/):
``` sh
pipx install jrnl
```
!!! note
`pipx` should be installed through either `brew` or `pip`. Missing dependencies and other issues
may occur when installing `pipx` through `apt` or another package manager. Further installation
instructions can be found in [pipx's documentation](https://pipxproject.github.io/pipx/installation/).
!!! tip
Do not use `sudo` while installing `jrnl`. This may lead to path issues.

View file

@ -1,8 +1,5 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
<!-- Copyright (C) 2012-2021 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html -->
# Journal Types
`jrnl` can store your journal in a few different ways:
@ -31,10 +28,9 @@ you have an entry on May 5th, 2021 in a folder journal at `~/folderjournal`, it
be located in: `~/folderjournal/2021/05/05.txt`
!!! note
Creating a new folder journal can be done in two ways:
* Create a folder with the name of the journal before running `jrnl`. Otherwise, when you run `jrnl` for the first time, it will assume that you are creating a single file journal instead, and it will create a file at that path.
* Create a new journal in your [config_file](advanced.md) and end the path with a ``/`` (on a POSIX system like Linux or MacOSX) or a ``\`` (on a Windows system). The folder will be created automatically if it doesn't exist.
When creating a new folder journal, you will need to create the folder before running
`jrnl`. Otherwise, when you run `jrnl` for the first time, it will assume that you
are creating a single file journal instead, and it will create a file at that path.
!!! note
Folder journals can't be encrypted.

View file

@ -1,8 +1,5 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
<!-- Copyright (C) 2012-2021 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html -->
# Overview
`jrnl` is a simple journal application for the command line.
@ -39,7 +36,7 @@ read them or edit them.
`jrnl` plays nicely with your favorite text editor. You may prefer to write
journal entries in an editor. Or you may want to make changes that require a
more comprehensive application. `jrnl` can filter specific entries and pass them
to the [external editor](./external-editors.md) of your choice.
to the external editor of your choice.
## Encryption

View file

@ -1,8 +1,5 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
<!-- Copyright (C) 2012-2021 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html -->
# Privacy and Security
`jrnl` is designed with privacy and security in mind, but like any other
@ -14,35 +11,6 @@ program there are some limitations to be aware of.
passwords can be easily circumvented by someone with basic security skills
to access to your encrypted `jrnl` file.
## Plausible deniability
You may be able to hide the contents of your journal behind a layer of encryption,
but if someone has access to your configuration file, then they can figure out that
you have a journal, where that journal file is, and when you last edited it.
With a sufficient power imbalance, someone may be able to force you to unencrypt
it through non-technical means.
## Spying
While `jrnl` can protect against unauthorized access to your journal entries while
it isn't open, it cannot protect you against an unsafe computer/location.
For example:
- Someone installs a keylogger, tracking what you type into your journal.
- Someone watches your screen while you write your entry.
- Someone installs a backdoor into `jrnl` or poisons your journal into revealing your entries.
## Saved Passwords
When creating an encrypted journal, you'll be prompted as to whether or not you
want to "store the password in your keychain." This keychain is accessed using
the [Python keyring library](https://pypi.org/project/keyring/), which has different
behavior depending on your operating system.
In Windows, the keychain is the Windows Credential Manager (WCM), which can't be locked
and can be accessed by any other application running under your username. If this is
a concern for you, you may not want to store your password.
## Shell history
Since you can enter entries from the command line, any tool that logs command
@ -107,125 +75,28 @@ unencrypted temporary remains on your disk. If your computer were to shut off
during this time, or the `jrnl` process were killed unexpectedly, then the
unencrypted temporary file will remain on your disk. You can mitigate this
issue by only saving with your editor right before closing it. You can also
manually delete these files from your temporary folder. By default, they
are named `jrnl*.jrnl`, but if you use a
[template](reference-config-file.md#template), they will have the same
extension as the template.
manually delete these files (i.e. files named `jrnl_*.txt`) from your temporary
folder.
## Editor history
## Plausible deniability
Some editors keep usage history stored on disk for future use. This can be a
security risk in the sense that sensitive information can leak via recent
search patterns or editor commands.
You may be able to hide the contents of your journal behind a layer of encryption,
but if someone has access to your configuration file, then they can figure out that
you have a journal, where that journal file is, and when you last edited it.
With a sufficient power imbalance, someone may be able to force you to unencrypt
it through non-technical means.
### Visual Studio Code
## Saved Passwords
Visual Studio Code stores the contents of saved files to allow you to restore or
review the contents later. You can disable this feature for all files by unchecking
the `workbench.localHistory.enabled` setting in the
[Settings editor](https://code.visualstudio.com/docs/getstarted/settings#_settings-editor).
When creating an encrypted journal, you'll be prompted as to whether or not you
want to "store the password in your keychain." This keychain is accessed using
the [Python keyring library](https://pypi.org/project/keyring/), which has different
behavior depending on your operating system.
Alternatively, you can disable this feature for specific files by configuring a
[pattern](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options)
in the `workbench.localHistory.exclude` setting. To exclude unencrypted temporary files generated
by `jrnl`, you can set the `**/jrnl*.jrnl` (unless you are using a
[template](reference-config-file.md#template)) pattern for the `workbench.localHistory.exclude` setting
in the [Settings editor](https://code.visualstudio.com/docs/getstarted/settings#_settings-editor).
In Windows, the keychain is the Windows Credential Manager (WCM), which can't be locked
and can be accessed by any other application running under your username. If this is
a concern for you, you may not want to store your password.
!!! note
On Windows, the history location is typically found at
`%APPDATA%\Code\User\History`.
Visual Studio Code also creates a copy of all unsaved files that are open.
It stores these copies in a backup location that's automatically cleaned when
you save the file. However, if your computer shuts off before you save the file,
or the Visual Studio Code process stops unexpectedly, then an unencrypted
temporary file may remain on your disk. You can manually delete these files
from the backup location.
!!! note
On Windows, the backup location is typically found at
`%APPDATA%\Code\Backups`.
### Vim
Vim stores progress data in a so called Viminfo file located at `~/.viminfo`
which contains all sorts of user data including command line history, search
string history, search/substitute patterns, contents of register etc. Also to
be able to recover opened files after an unexpected application close Vim uses
swap files.
These options as well as other leaky features can be disabled by setting the
`editor` key in the Jrnl settings like this:
``` yaml
editor: "vim -c 'set viminfo= noswapfile noundofile nobackup nowritebackup noshelltemp history=0 nomodeline secure'"
```
To disable all plugins and custom configurations and start Vim with the default
configuration `-u NONE` can be passed on the command line as well. This will
ensure that any rogue plugins or other difficult to catch information leaks are
eliminated. The downside to this is that the editor experience will decrease
quite a bit.
To instead let Vim automatically detect when a Jrnl file is being edited an
autocommand can be used. Place this in your `~/.vimrc`:
``` vim
autocmd BufNewFile,BufReadPre *.jrnl setlocal viminfo= noswapfile noundofile nobackup nowritebackup noshelltemp history=0 nomodeline secure
```
!!! note
If you're using a [template](reference-config-file.md#template), you will
have to use the template's file extension instead of `.jrnl`.
See `:h <option>` in Vim for more information about the options mentioned.
### Neovim
Neovim strives to be mostly compatible with Vim and has therefore similar
functionality as Vim. One difference in Neovim is that the Viminfo file is
instead called the ShaDa ("shared data") file which resides in
`~/.local/state/nvim` (`~/.local/share/nvim` pre Neovim v0.8.0). The ShaDa file
can be disabled in the same way as for Vim.
``` yaml
editor: "nvim -c 'set shada= noswapfile noundofile nobackup nowritebackup noshelltemp history=0 nomodeline secure'"
```
`-u NONE` can be passed here as well to start a session with the default configs.
As for Vim above we can create an autocommand in Vimscript:
``` vim
autocmd BufNewFile,BufReadPre *.jrnl setlocal shada= noswapfile noundofile nobackup nowritebackup noshelltemp history=0 nomodeline secure
```
or the same but in Lua:
``` lua
vim.api.nvim_create_autocmd( {"BufNewFile","BufReadPre" }, {
group = vim.api.nvim_create_augroup("PrivateJrnl", {}),
pattern = "*.jrnl",
callback = function()
vim.o.shada = ""
vim.o.swapfile = false
vim.o.undofile = false
vim.o.backup = false
vim.o.writebackup = false
vim.o.shelltemp = false
vim.o.history = 0
vim.o.modeline = false
vim.o.secure = true
end,
})
```
!!! note
If you're using a [template](reference-config-file.md#template), you will
have to use the template's file extension instead of `.jrnl`.
Please see `:h <option>` in Neovim for more information about the options mentioned.
## Notice any other risks?

View file

@ -1,8 +1,3 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
# Command Line Reference
## Synopsis
@ -76,11 +71,8 @@ entries, such as `yesterday`, `today`, `Tuesday`, or `2021-08-01`.
| -contains TEXT | Show entries containing specific text (put quotes around text with spaces) |
| -and | Show only entries that match all conditions, like saying "x AND y" (default: OR) |
| -starred | Show only starred entries (marked with *) |
| -tagged | Show only tagged entries (marked with the [configured tagsymbols](reference-config-file.md#tagsymbols)) |
| -n [NUMBER] | Show a maximum of NUMBER entries (note: '-n 3' and '-3' have the same effect) |
| -not [TAG] | Exclude entries with this tag |
| -not -starred | Exclude entries that are starred |
| -not -tagged | Exclude entries that are tagged |
## Searching Options
These help you do various tasks with the selected entries from your search.
@ -98,11 +90,6 @@ the temporary file you were editing and makes the changes to your journal.
Interactively deletes selected entries. You'll be asked to confirm deletion of
each entry.
### --change-time DATE
Interactively changes the time of the selected entries to the date specified,
or to right now if no date is specified. You'll be asked to confirm each entry,
unless you are using this with `--edit` on a single entry.
### --format TYPE
Display selected entries in an alternate format. See [formats](formats.md).

View file

@ -1,8 +1,3 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
# Configuration File Reference
`jrnl` stores its information in a YAML configuration file.
@ -47,11 +42,10 @@ key will be used instead.
If set, executes this command to launch an external editor for
writing and editing your entries. The path to a temporary file
is passed after it, and `jrnl` processes the file once
the editor returns control to `jrnl`.
the editor is closed.
Some editors require special options to work properly, since they must be
blocking processes to work with `jrnl`. See [External Editors](external-editors.md)
for details.
Some editors require special options to work properly. See
[External Editors](external-editors.md) for details.
### encrypt
If `true`, encrypts your journal using AES. Do not change this
@ -59,9 +53,7 @@ value for journals that already have data in them.
### template
The path to a text file to use as a template for new entries. Only works when you
have the `editor` field configured. If you use a template, the editor's
[temporary files](privacy-and-security.md#files-in-transit-from-editor-to-jrnl)
will have the same extension as the template.
have the `editor` field configured.
### tagsymbols
Symbols to be interpreted as tags.
@ -93,6 +85,9 @@ See the [python docs](http://docs.python.org/library/time.html#time.strftime) fo
Do not change this for an existing journal, since that might lead
to data loss.
If you would just like to change how `jrnl` displays dates,
use display_format instead.
!!! note
`jrnl` doesn't support the `%z` or `%Z` time zone identifiers.
@ -101,8 +96,7 @@ If `true`, tags will be highlighted in cyan.
### linewrap
Controls the width of the output. Set to `false` if you don't want to
wrap long lines. Set to `auto` to let `jrnl` automatically determine
the terminal width.
wrap long lines.
### colors
A dictionary that controls the colors used to display journal entries.

View file

@ -1,8 +1,5 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
<!-- Copyright (C) 2012-2021 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html -->
# Tips and Tricks
This page contains tips and tricks for using `jrnl`, often in conjunction
@ -74,45 +71,39 @@ jrnlimport () {
}
```
## Using Templates
## Using templates
!!! note
Templates require an [external editor](./advanced.md) be configured.
Templates are text files that are used for creating structured journals.
There are three ways you can use templates:
A template is a code snippet that makes it easier to use repeated text
each time a new journal entry is started. There are two ways you can utilize
templates in your entries.
### 1. Use the `--template` command line argument and the default $XDG_DATA_HOME/jrnl/templates directory
### 1. Command line arguments
`$XDG_DATA_HOME/jrnl/templates` is created by default to store your templates! Create a template (like `default.md`) in this directory and pass `--template FILE_IN_DIR`.
If you had a `template.txt` file with the following contents:
```sh
jrnl --template default.md
```
### 2. Use the `--template` command line argument with a local / absolute path
You can create a template file with any text. Here is an example:
```sh
# /tmp/template.txt
My Personal Journal
Title:
Body:
```
Then, pass the absolute or relative path to the template file as an argument, and your external
editor will open and have your template pre-populated.
The `template.txt` file could be used to create a new entry with these
command line arguments:
```sh
jrnl --template /tmp/template.md
jrnl < template.txt # Imports template.txt as the most recent entry
jrnl -1 --edit # Opens the most recent entry in the editor
```
### 3. Set a default template file in `jrnl.yaml`
### 2. Include the template file in `jrnl.yaml`
If you want a template by default, change the value of `template` in the [config file](./reference-config-file.md)
from `false` to the template file's path, wrapped in double quotes:
A more efficient way to work with a template file is to declare the file
in your [config file](./reference-config-file.md) by changing the `template`
setting from `false` to the template file's path in double quotes:
```sh
...
@ -120,6 +111,9 @@ template: "/path/to/template.txt"
...
```
Changes can be saved as you continue writing the journal entry and will be
logged as a new entry in the journal you specified in the original argument.
!!! tip
To read your journal entry or to verify the entry saved, you can use this
command: `jrnl -n 1` (Check out [Formats](./formats.md) for more options).
@ -214,11 +208,3 @@ display_format: markdown
For more information on how `jrnl` outputs your entries in Markdown, please visit the [Formats](./formats.md) section.
## Jump to end of buffer (with vi)
To cause vi to jump to the end of the last line of the entry you edit, in your config file set:
```yaml
editor: vi + -c "call cursor('.',strwidth(getline('.')))"
```

View file

@ -1,8 +1,5 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
<!-- Copyright (C) 2012-2021 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html -->
# Basic Usage #
`jrnl` has two modes: **composing** and **viewing**. Whenever you don't enter

View file

@ -1,7 +1,5 @@
/*
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
*/
/* Copyright (C) 2012-2021 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html */
:root {
/* For dark bg */

View file

@ -1,7 +1,4 @@
/*
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
Atom One Dark With support for ReasonML by Gidi Morris, based off work by
Daniel Gamage
@ -139,9 +136,3 @@ Original One Dark Syntax theme from https://github.com/atom/one-dark-syntax
.rst-content .tip .admonition {
background: var(--light-blue);
}
/* hack to bypass a11y issue with conflicting highlight.css files */
code.language-xml span.hljs-meta span.hljs-string {
color: var(--green) !important;
}

View file

@ -1,8 +1,5 @@
/*
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
*/
/* Copyright (C) 2012-2021 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html */
/* reset */article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,video{display:inline-block}audio:not([controls]){display:none;height:0}[hidden]{display:none}html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}a:focus{outline:thin dotted}a:active,a:hover{outline:0}h1{font-size:2em;margin:.67em 0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}mark{background:#ff0;color:#000}code,kbd,pre,samp{font-family:monospace,serif;font-size:1em}pre{white-space:pre-wrap}q{quotes:"\201C" "\201D" "\2018" "\2019"}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:0}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0}button,input,select,textarea{font-family:inherit;font-size:100%;margin:0}button,input{line-height:normal}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0}
body {

View file

@ -1,7 +1,5 @@
/*
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
*/
/* Copyright (C) 2012-2021 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html */
/* ------------------------------------------------------------ */
/* Overrides for jrnl theme */
@ -118,7 +116,7 @@ div.rst-content {
background-size: 100%;
}
.wy-side-nav-search a.icon-home:before {
a.icon-home:before {
display: block;
width: 84px;
height: 70px;

View file

@ -1,49 +0,0 @@
<!--
Copied from https://github.com/mkdocs/mkdocs/blob/master/mkdocs/themes/readthedocs/breadcrumbs.html
Then lightly modified for accessibility
-->
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="{{ nav.homepage.url|url }}" class="icon icon-home" aria-label="{% trans %}Docs{% endtrans %}"></a> &raquo;</li>
{%- if page %}
{%- for doc in page.ancestors[::-1] %}
{%- if doc.link %}
<li><a href="{{ doc.link|e }}">{{ doc.title }}</a> &raquo;</li>
{%- else %}
<li>{{ doc.title }} &raquo;</li>
{%- endif %}
{%- endfor %}
<li>{{ page.title }}</li>
{%- endif %}
<li class="wy-breadcrumbs-aside">
{%- block repo %}
{%- if page and page.edit_url %}
{%- if config.repo_name|lower == 'github' %}
<a href="{{ page.edit_url }}" class="icon icon-github"> {% trans repo_name=config.repo_name %}Edit on {{ repo_name }}{% endtrans %}</a>
{%- elif config.repo_name|lower == 'bitbucket' %}
<a href="{{ page.edit_url }}" class="icon icon-bitbucket"> {% trans repo_name=config.repo_name %}Edit on {{ repo_name }}{% endtrans %}</a>
{%- elif config.repo_name|lower == 'gitlab' %}
<a href="{{ page.edit_url }}" class="icon icon-gitlab"> {% trans repo_name=config.repo_name %}Edit on {{ repo_name }}{% endtrans %}</a>
{%- elif config.repo_name %}
<a href="{{ page.edit_url }}">{% trans repo_name=config.repo_name %}Edit on {{ repo_name }}{% endtrans %}</a>
{%- else %}
<a href="{{ page.edit_url }}">{% trans %}Edit{% endtrans %}</a>
{%- endif %}
{%- endif %}
{%- endblock %}
</li>
</ul>
{%- if config.theme.prev_next_buttons_location|lower in ['top', 'both']
and page and (page.next_page or page.previous_page) %}
<div class="rst-breadcrumbs-buttons" role="navigation" aria-label="{% trans %}Breadcrumb Navigation{% endtrans %}">
{%- if page.previous_page %}
<a href="{{ page.previous_page.url|url }}" class="btn btn-neutral float-left" title="{{ page.previous_page.title }}"><span class="icon icon-circle-arrow-left" aria-hidden="true"></span> {% trans %}Previous{% endtrans %}</a>
{%- endif %}
{%- if page.next_page %}
<a href="{{ page.next_page.url|url }}" class="btn btn-neutral float-right" title="{{ page.next_page.title }}">{% trans %}Next{% endtrans %} <span class="icon icon-circle-arrow-right" aria-hidden="true"></span></a>
{%- endif %}
</div>
{%- endif %}
<hr/>
</div>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Before After
Before After

View file

@ -1,8 +1,5 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
<!-- Copyright (C) 2012-2021 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html -->
<!DOCTYPE html>
<html lang="en">
@ -65,7 +62,7 @@ License: https://www.gnu.org/licenses/gpl-3.0.html
<a href="overview">Documentation</a>
<a href="installation" class="cta">Get Started</a>
<a href="http://github.com/jrnl-org/jrnl" title="View on Github">Fork on GitHub</a>
<a id="twitter-nav" href="https://twitter.com/intent/tweet?text=Collect+your+thoughts+and+notes+without+leaving+the+command+line.+https%3A%2F%2Fjrnl.sh+via+@JrnlSh">Tell your friends on X</a>
<a id="twitter-nav" href="https://twitter.com/intent/tweet?text=Collect+your+thoughts+and+notes+without+leaving+the+command+line.+https%3A%2F%2Fjrnl.sh+via+@JrnlSh"><i class="icon twitter"></i>Tell your friends on Twitter</a>
</nav>
<div class="flex">
<section>
@ -76,22 +73,22 @@ License: https://www.gnu.org/licenses/gpl-3.0.html
<section>
<i class="icon future"></i>
<h3>Future-proof.</h3>
<p>Your journals are stored in plain-text files that will still be readable in 50 years when your fancy proprietary apps will have gone the way of the dodo.</p>
<p>Your journals are stored in plain-text files that will still be readable in 50 years when all your fancy iPad apps will have gone the way of the Dodo.</p>
</section>
<section>
<i class="icon secure"></i>
<h3>Secure.</h3>
<p>Encrypt your journals with industry-strength AES encryption. Nobody will be able to read your dirty secrets&mdash;not even you, if you lose your password!</p>
<p>Encrypt your journals with industry-strength AES encryption. The NSA won't be able to read your dirty secrets.</p>
</section>
<section>
<i class="icon sync"></i>
<h3>Accessible anywhere.</h3>
<p>Sync your journal files with other tools like Dropbox to capture your thoughts wherever you are.</p>
<p>Sync your journals with Dropbox and capture your thoughts where ever you are.</p>
</section>
<section>
<i class="icon github"></i>
<h3>Free &amp; Open Source.</h3>
<p>jrnl is made by a bunch of really friendly and remarkably amazing people. Maybe even <a href="https://www.github.com/jrnl-org/jrnl" title="Fork jrnl on GitHub">you</a>?</p>
<p>jrnl is made by a bunch of really friendly and remarkably attractive people. Maybe even <a href="https://www.github.com/jrnl-org/jrnl" title="Fork jrnl on GitHub">you</a>?</p>
</section>
<section>
<i class="icon folders"></i>
@ -103,21 +100,21 @@ License: https://www.gnu.org/licenses/gpl-3.0.html
<footer>
jrnl is made with love by <a href="https://github.com/jrnl-org/jrnl/graphs/contributors" title="Contributors">many fabulous people</a>. If you need help, <a href="https://github.com/jrnl-org/jrnl/issues/new/choose" title="Open a new issue on Github">submit an issue</a> on Github.
</footer>
<script src="https://unpkg.com/typed.js@2.1.0/dist/typed.umd.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/typed.js/2.0.10/typed.min.js"></script>
<script>
new Typed("#typed", {
strings: [
"jrnl Started writing my memoirs on the command line. 🎉🔥💻🔥🎉",
"jrnl today: Started writing my memoirs. On the command line. Like a boss.",
"jrnl yesterday 2pm: used jrnl to keep track of accomplished tasks. The done.txt for my todo.txt",
"jrnl <b>-from</b> 2019 <b>-until</b> may<br /><i>`(displays all entries from January 2019 to last May)`</i>",
"jrnl A day on the beach with @beth and @frank. Tagging them so I can easily look this up later.",
"jrnl <b>--tags</b><br /><i>`@frank 7<br />@beth 5</i>`",
"jrnl <b>-from</b> 2009 <b>-until</b> may<br /><i>`(Displays all entries from January 2009 to last may)`</i>",
"jrnl A day on the beach with @beth and @frank. Taggidy-tag-tag.",
"jrnl <b>--tags</b><br /><i>`@idea 7<br />@beth 5</i>`",
"jrnl <b>--format</b> json<br /><i>`(Outputs your entire journal as json)</i>`",
"jrnl <b>--encrypt</b><br /><i>`(AES encryption. Don't lose your password!)</i>`"
"jrnl <b>--encrypt</b><br /><i>`(AES encryption. Crack this, NSA)</i>`"
],
typeSpeed: 20, // less is faster
backSpeed: 10,
backDelay: 2500,
typeSpeed: 35,
backSpeed: 15,
backDelay: 2000,
loop: true,
showCursor: false
});

View file

@ -1,8 +1,3 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
{% extends "base.html" %}
{%- block search_button %}

View file

@ -1,2 +1 @@
mkdocs>=1.4
jinja2==3.1.6
mkdocs==1.2.3

View file

@ -1,8 +1,3 @@
<!--
Copyright © 2012-2023 jrnl contributors
License: https://www.gnu.org/licenses/gpl-3.0.html
-->
{% extends "main.html" %}
{% block content %}

View file

@ -1,30 +1,25 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import contextlib
import datetime
import fnmatch
import os
from pathlib import Path
import platform
import plistlib
import re
import socket
import time
import uuid
import zoneinfo
from pathlib import Path
from xml.parsers.expat import ExpatError
import pytz
import tzlocal
from jrnl import __title__
from jrnl import __version__
from .Entry import Entry
from .Journal import Journal
from . import Entry
from . import Journal
from . import __title__
from . import __version__
class DayOne(Journal):
class DayOne(Journal.Journal):
"""A special Journal handling DayOne files"""
# InvalidFileException was added to plistlib in Python3.4
@ -40,7 +35,11 @@ class DayOne(Journal):
self.can_be_encrypted = False
super().__init__(**kwargs)
def open(self) -> "DayOne":
def open(self):
filenames = [
os.path.join(self.config["journal"], "entries", f)
for f in os.listdir(os.path.join(self.config["journal"], "entries"))
]
filenames = []
for root, dirnames, f in os.walk(self.config["journal"]):
for filename in fnmatch.filter(f, "*.doentry"):
@ -54,17 +53,16 @@ class DayOne(Journal):
pass
else:
try:
timezone = zoneinfo.ZoneInfo(dict_entry["Time Zone"])
except KeyError:
timezone_name = str(tzlocal.get_localzone())
timezone = zoneinfo.ZoneInfo(timezone_name)
timezone = pytz.timezone(dict_entry["Time Zone"])
except (KeyError, pytz.exceptions.UnknownTimeZoneError):
timezone = tzlocal.get_localzone()
date = dict_entry["Creation Date"]
# convert the date to UTC rather than keep messing with
# timezones
if timezone.key != "UTC":
date = date.replace(fold=1) + timezone.utcoffset(date)
if timezone.zone != "UTC":
date = date + timezone.utcoffset(date, is_dst=False)
entry = Entry(
entry = Entry.Entry(
self,
date,
text=dict_entry["Entry Text"],
@ -75,32 +73,47 @@ class DayOne(Journal):
self.config["tagsymbols"][0] + tag.lower()
for tag in dict_entry.get("Tags", [])
]
if entry._tags:
entry._tags.sort()
"""Extended DayOne attributes"""
# just ignore it if the keys don't exist
with contextlib.suppress(KeyError):
try:
entry.creator_device_agent = dict_entry["Creator"][
"Device Agent"
]
except: # noqa: E722
pass
try:
entry.creator_generation_date = dict_entry["Creator"][
"Generation Date"
]
except: # noqa: E722
entry.creator_generation_date = date
try:
entry.creator_host_name = dict_entry["Creator"]["Host Name"]
except: # noqa: E722
pass
try:
entry.creator_os_agent = dict_entry["Creator"]["OS Agent"]
except: # noqa: E722
pass
try:
entry.creator_software_agent = dict_entry["Creator"][
"Software Agent"
]
except: # noqa: E722
pass
try:
entry.location = dict_entry["Location"]
except: # noqa: E722
pass
try:
entry.weather = dict_entry["Weather"]
entry.creator_generation_date = dict_entry.get("Creator", {}).get(
"Generation Date", date
)
except: # noqa: E722
pass
self.entries.append(entry)
self.sort()
return self
def write(self) -> None:
def write(self):
"""Writes only the entries that have been modified into plist files."""
for entry in self.entries:
if entry.modified:
@ -164,20 +177,20 @@ class DayOne(Journal):
)
os.remove(filename)
def editable_str(self) -> str:
def editable_str(self):
"""Turns the journal into a string of entries that can be edited
manually and later be parsed with eslf.parse_editable_str."""
return "\n".join([f"{str(e)}\n# {e.uuid}\n" for e in self.entries])
def _update_old_entry(self, entry: Entry, new_entry: Entry) -> None:
for attr in ("title", "body", "date", "tags"):
def _update_old_entry(self, entry, new_entry):
for attr in ("title", "body", "date"):
old_attr = getattr(entry, attr)
new_attr = getattr(new_entry, attr)
if old_attr != new_attr:
entry.modified = True
setattr(entry, attr, new_attr)
def _get_and_remove_uuid_from_entry(self, entry: Entry) -> Entry:
def _get_and_remove_uuid_from_entry(self, entry):
uuid_regex = "^ *?# ([a-zA-Z0-9]+) *?$"
m = re.search(uuid_regex, entry.body, re.MULTILINE)
entry.uuid = m.group(1) if m else None
@ -188,7 +201,7 @@ class DayOne(Journal):
return entry
def parse_editable_str(self, edited: str) -> None:
def parse_editable_str(self, edited):
"""Parses the output of self.editable_str and updates its entries."""
# Method: create a new list of entries from the edited text, then match
# UUIDs of the new entries against self.entries, updating the entries
@ -198,8 +211,6 @@ class DayOne(Journal):
for entry in entries_from_editor:
entry = self._get_and_remove_uuid_from_entry(entry)
if entry._tags:
entry._tags.sort()
# Remove deleted entries
edited_uuids = [e.uuid for e in entries_from_editor]
@ -209,11 +220,5 @@ class DayOne(Journal):
for entry in entries_from_editor:
for old_entry in self.entries:
if entry.uuid == old_entry.uuid:
if old_entry._tags:
tags_not_in_body = [
tag for tag in old_entry._tags if (tag not in entry._body)
]
if tags_not_in_body:
entry._tags.extend(tags_not_in_body.sort())
self._update_old_entry(old_entry, entry)
break

203
jrnl/EncryptedJournal.py Normal file
View file

@ -0,0 +1,203 @@
import base64
import getpass
import hashlib
import logging
import os
import sys
from typing import Callable
from typing import Optional
from cryptography.fernet import Fernet
from cryptography.fernet import InvalidToken
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers import algorithms
from cryptography.hazmat.primitives.ciphers import modes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from .Journal import Journal
from .Journal import LegacyJournal
from .prompt import create_password
def make_key(password):
password = password.encode("utf-8")
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
# Salt is hard-coded
salt=b"\xf2\xd5q\x0e\xc1\x8d.\xde\xdc\x8e6t\x89\x04\xce\xf8",
iterations=100_000,
backend=default_backend(),
)
key = kdf.derive(password)
return base64.urlsafe_b64encode(key)
def decrypt_content(
decrypt_func: Callable[[str], Optional[str]],
keychain: str = None,
max_attempts: int = 3,
) -> str:
pwd_from_keychain = keychain and get_keychain(keychain)
password = pwd_from_keychain or getpass.getpass()
result = decrypt_func(password)
# Password is bad:
if result is None and pwd_from_keychain:
set_keychain(keychain, None)
attempt = 1
while result is None and attempt < max_attempts:
print("Wrong password, try again.", file=sys.stderr)
password = getpass.getpass()
result = decrypt_func(password)
attempt += 1
if result is not None:
return result
else:
print("Extremely wrong password.", file=sys.stderr)
sys.exit(1)
class EncryptedJournal(Journal):
def __init__(self, name="default", **kwargs):
super().__init__(name, **kwargs)
self.config["encrypt"] = True
self.password = None
def open(self, filename=None):
"""Opens the journal file defined in the config and parses it into a list of Entries.
Entries have the form (date, title, body)."""
filename = filename or self.config["journal"]
dirname = os.path.dirname(filename)
if not os.path.exists(filename):
if not os.path.isdir(dirname):
os.makedirs(dirname)
print(f"[Directory {dirname} created]", file=sys.stderr)
self.create_file(filename)
self.password = create_password(self.name)
print(
f"Encrypted journal '{self.name}' created at {filename}",
file=sys.stderr,
)
text = self._load(filename)
self.entries = self._parse(text)
self.sort()
logging.debug("opened %s with %d entries", self.__class__.__name__, len(self))
return self
def _load(self, filename):
"""Loads an encrypted journal from a file and tries to decrypt it.
If password is not provided, will look for password in the keychain
and otherwise ask the user to enter a password up to three times.
If the password is provided but wrong (or corrupt), this will simply
return None."""
with open(filename, "rb") as f:
journal_encrypted = f.read()
def decrypt_journal(password):
key = make_key(password)
try:
plain = Fernet(key).decrypt(journal_encrypted).decode("utf-8")
self.password = password
return plain
except (InvalidToken, IndexError):
return None
if self.password:
return decrypt_journal(self.password)
return decrypt_content(keychain=self.name, decrypt_func=decrypt_journal)
def _store(self, filename, text):
key = make_key(self.password)
journal = Fernet(key).encrypt(text.encode("utf-8"))
with open(filename, "wb") as f:
f.write(journal)
@classmethod
def from_journal(cls, other: Journal):
new_journal = super().from_journal(other)
try:
new_journal.password = (
other.password
if hasattr(other, "password")
else create_password(other.name)
)
except KeyboardInterrupt:
print("[Interrupted while creating new journal]", file=sys.stderr)
sys.exit(1)
return new_journal
class LegacyEncryptedJournal(LegacyJournal):
"""Legacy class to support opening journals encrypted with the jrnl 1.x
standard. You'll not be able to save these journals anymore."""
def __init__(self, name="default", **kwargs):
super().__init__(name, **kwargs)
self.config["encrypt"] = True
self.password = None
def _load(self, filename):
with open(filename, "rb") as f:
journal_encrypted = f.read()
iv, cipher = journal_encrypted[:16], journal_encrypted[16:]
def decrypt_journal(password):
decryption_key = hashlib.sha256(password.encode("utf-8")).digest()
decryptor = Cipher(
algorithms.AES(decryption_key), modes.CBC(iv), default_backend()
).decryptor()
try:
plain_padded = decryptor.update(cipher) + decryptor.finalize()
self.password = password
if plain_padded[-1] in (" ", 32):
# Ancient versions of jrnl. Do not judge me.
return plain_padded.decode("utf-8").rstrip(" ")
else:
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
plain = unpadder.update(plain_padded) + unpadder.finalize()
return plain.decode("utf-8")
except ValueError:
return None
if self.password:
return decrypt_journal(self.password)
return decrypt_content(keychain=self.name, decrypt_func=decrypt_journal)
def get_keychain(journal_name):
import keyring
try:
return keyring.get_password("jrnl", journal_name)
except keyring.errors.KeyringError as e:
if not isinstance(e, keyring.errors.NoKeyringError):
print("Failed to retrieve keyring", file=sys.stderr)
return ""
def set_keychain(journal_name, password):
import keyring
if password is None:
try:
keyring.delete_password("jrnl", journal_name)
except keyring.errors.KeyringError:
pass
else:
try:
keyring.set_password("jrnl", journal_name, password)
except keyring.errors.KeyringError as e:
if isinstance(e, keyring.errors.NoKeyringError):
print(
"Keyring backend not found. Please install one of the supported backends by visiting: https://pypi.org/project/keyring/",
file=sys.stderr,
)
else:
print("Failed to retrieve keyring", file=sys.stderr)

View file

@ -1,28 +1,18 @@
# Copyright © 2012-2023 jrnl contributors
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import datetime
import logging
import os
import re
from typing import TYPE_CHECKING
from jrnl.color import colorize
from jrnl.color import highlight_tags_with_background_color
from jrnl.output import wrap_with_ansi_colors
import ansiwrap
if TYPE_CHECKING:
from .Journal import Journal
from .color import colorize
from .color import highlight_tags_with_background_color
class Entry:
def __init__(
self,
journal: "Journal",
date: datetime.datetime | None = None,
text: str = "",
starred: bool = False,
):
def __init__(self, journal, date=None, text="", starred=False):
self.journal = journal # Reference to journal mainly to access its config
self.date = date or datetime.datetime.now()
self.text = text
@ -33,7 +23,7 @@ class Entry:
self.modified = False
@property
def fulltext(self) -> str:
def fulltext(self):
return self.title + " " + self.body
def _parse_text(self):
@ -47,48 +37,48 @@ class Entry:
self._tags = list(self._parse_tags())
@property
def title(self) -> str:
def title(self):
if self._title is None:
self._parse_text()
return self._title
@title.setter
def title(self, x: str):
def title(self, x):
self._title = x
@property
def body(self) -> str:
def body(self):
if self._body is None:
self._parse_text()
return self._body
@body.setter
def body(self, x: str):
def body(self, x):
self._body = x
@property
def tags(self) -> list[str]:
def tags(self):
if self._tags is None:
self._parse_text()
return self._tags
@tags.setter
def tags(self, x: list[str]):
def tags(self, x):
self._tags = x
@staticmethod
def tag_regex(tagsymbols: str) -> re.Pattern:
def tag_regex(tagsymbols):
pattern = rf"(?<!\S)([{tagsymbols}][-+*#/\w]+)"
return re.compile(pattern)
def _parse_tags(self) -> set[str]:
def _parse_tags(self):
tagsymbols = self.journal.config["tagsymbols"]
return {
tag.lower() for tag in re.findall(Entry.tag_regex(tagsymbols), self.text)
}
def __str__(self):
"""Returns string representation of the entry to be written to journal file."""
"""Returns a string representation of the entry to be written into a journal file."""
date_str = self.date.strftime(self.journal.config["timeformat"])
title = "[{}] {}".format(date_str, self.title.rstrip("\n "))
if self.starred:
@ -99,7 +89,7 @@ class Entry:
body=self.body.rstrip("\n "),
)
def pprint(self, short: bool = False) -> str:
def pprint(self, short=False):
"""Returns a pretty-printed version of the entry.
If short is true, only print the title."""
# Handle indentation
@ -115,20 +105,8 @@ class Entry:
)
if not short and self.journal.config["linewrap"]:
columns = self.journal.config["linewrap"]
if columns == "auto":
try:
columns = os.get_terminal_size().columns
except OSError:
logging.debug(
"Can't determine terminal size automatically 'linewrap': '%s'",
self.journal.config["linewrap"],
)
columns = 79
# Color date / title and bold title
title = wrap_with_ansi_colors(
title = ansiwrap.fill(
date_str
+ " "
+ highlight_tags_with_background_color(
@ -137,22 +115,40 @@ class Entry:
self.journal.config["colors"]["title"],
is_title=True,
),
columns,
self.journal.config["linewrap"],
)
body = highlight_tags_with_background_color(
self, self.body.rstrip(" \n"), self.journal.config["colors"]["body"]
)
body = wrap_with_ansi_colors(body, columns - len(indent))
if indent:
# Without explicitly colorizing the indent character, it will lose its
# color after a tag appears.
body = "\n".join(
colorize(indent, self.journal.config["colors"]["body"]) + line
for line in body.splitlines()
body_text = [
colorize(
ansiwrap.fill(
line,
self.journal.config["linewrap"],
initial_indent=indent,
subsequent_indent=indent,
drop_whitespace=True,
),
self.journal.config["colors"]["body"],
)
or indent
for line in body.rstrip(" \n").splitlines()
]
body = colorize(body, self.journal.config["colors"]["body"])
# ansiwrap doesn't handle lines with only the "\n" character and some
# ANSI escapes properly, so we have this hack here to make sure the
# beginning of each line has the indent character and it's colored
# properly. textwrap doesn't have this issue, however, it doesn't wrap
# the strings properly as it counts ANSI escapes as literal characters.
# TL;DR: I'm sorry.
body = "\n".join(
[
colorize(indent, self.journal.config["colors"]["body"]) + line
if not ansiwrap.strip_color(line).startswith(indent)
else line
for line in body_text
]
)
else:
title = (
date_str
@ -188,7 +184,7 @@ class Entry:
def __hash__(self):
return hash(self.__repr__())
def __eq__(self, other: "Entry"):
def __eq__(self, other):
if (
not isinstance(other, Entry)
or self.title.strip() != other.title.strip()
@ -199,7 +195,7 @@ class Entry:
return False
return True
def __ne__(self, other: "Entry"):
def __ne__(self, other):
return not self.__eq__(other)
@ -214,14 +210,14 @@ SENTENCE_SPLITTER = re.compile(
\s+ # AND a sequence of required spaces.
)
|[\uFF01\uFF0E\uFF1F\uFF61\u3002] # CJK full/half width terminals usually do not have following spaces.
""", # noqa: E501
""",
re.VERBOSE,
)
SENTENCE_SPLITTER_ONLY_NEWLINE = re.compile("\n")
def split_title(text: str) -> tuple[str, str]:
def split_title(text):
"""Splits the first sentence off from a text."""
sep = SENTENCE_SPLITTER_ONLY_NEWLINE.search(text.lstrip())
if not sep:

103
jrnl/FolderJournal.py Normal file
View file

@ -0,0 +1,103 @@
# encoding: utf-8
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import codecs
import fnmatch
import os
from . import Journal
def get_files(journal_config):
"""Searches through sub directories starting with journal_config and find all text files"""
filenames = []
for root, dirnames, f in os.walk(journal_config):
for filename in fnmatch.filter(f, "*.txt"):
filenames.append(os.path.join(root, filename))
return filenames
class Folder(Journal.Journal):
"""A Journal handling multiple files in a folder"""
def __init__(self, name="default", **kwargs):
self.entries = []
self._diff_entry_dates = []
self.can_be_encrypted = False
super().__init__(name, **kwargs)
def open(self):
filenames = []
self.entries = []
filenames = get_files(self.config["journal"])
for filename in filenames:
with codecs.open(filename, "r", "utf-8") as f:
journal = f.read()
self.entries.extend(self._parse(journal))
self.sort()
return self
def write(self):
"""Writes only the entries that have been modified into proper files."""
# Create a list of dates of modified entries. Start with diff_entry_dates
modified_dates = self._diff_entry_dates
seen_dates = set(self._diff_entry_dates)
for e in self.entries:
if e.modified:
if e.date not in modified_dates:
modified_dates.append(e.date)
if e.date not in seen_dates:
seen_dates.add(e.date)
# For every date that had a modified entry, write to a file
for d in modified_dates:
write_entries = []
filename = os.path.join(
self.config["journal"],
d.strftime("%Y"),
d.strftime("%m"),
d.strftime("%d") + ".txt",
)
dirname = os.path.dirname(filename)
# create directory if it doesn't exist
if not os.path.exists(dirname):
os.makedirs(dirname)
for e in self.entries:
if (
e.date.year == d.year
and e.date.month == d.month
and e.date.day == d.day
):
write_entries.append(e)
journal = "\n".join([e.__str__() for e in write_entries])
with codecs.open(filename, "w", "utf-8") as journal_file:
journal_file.write(journal)
# look for and delete empty files
filenames = []
filenames = get_files(self.config["journal"])
for filename in filenames:
if os.stat(filename).st_size <= 0:
# print("empty file: {}".format(filename))
os.remove(filename)
def delete_entries(self, entries_to_delete):
"""Deletes specific entries from a journal."""
for entry in entries_to_delete:
self.entries.remove(entry)
self._diff_entry_dates.append(entry.date)
def parse_editable_str(self, edited):
"""Parses the output of self.editable_str and updates its entries."""
mod_entries = self._parse(edited)
diff_entries = set(self.entries) - set(mod_entries)
for e in diff_entries:
self._diff_entry_dates.append(e.date)
# Match those entries that can be found in self.entries and set
# these to modified, so we can get a count of how many entries got
# modified and how many got deleted later.
for entry in mod_entries:
entry.modified = not any(entry == old_entry for old_entry in self.entries)
self.entries = mod_entries

View file

@ -1,22 +1,16 @@
# Copyright © 2012-2023 jrnl contributors
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import datetime
import logging
import os
import re
import sys
from jrnl import time
from jrnl.config import validate_journal_name
from jrnl.encryption import determine_encryption_method
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
from jrnl.output import print_msg
from jrnl.path import expand_path
from jrnl.prompt import yesno
from .Entry import Entry
from . import Entry
from . import time
from .prompt import yesno
class Tag:
@ -49,11 +43,6 @@ class Journal:
self.search_tags = None # Store tags we're highlighting
self.name = name
self.entries = []
self.encryption_method = None
# Track changes to journal in session. Modified is tracked in Entry
self.added_entry_count = 0
self.deleted_entry_count = 0
def __len__(self):
"""Returns the number of entries"""
@ -64,7 +53,7 @@ class Journal:
return (entry for entry in self.entries)
@classmethod
def from_journal(cls, other: "Journal") -> "Journal":
def from_journal(cls, other):
"""Creates a new journal by copying configuration and entries from
another journal object"""
new_journal = cls(other.name, **other.config)
@ -77,7 +66,7 @@ class Journal:
)
return new_journal
def import_(self, other_journal_txt: str) -> None:
def import_(self, other_journal_txt):
imported_entries = self._parse(other_journal_txt)
for entry in imported_entries:
entry.modified = True
@ -85,86 +74,54 @@ class Journal:
self.entries = list(frozenset(self.entries) | frozenset(imported_entries))
self.sort()
def _get_encryption_method(self) -> None:
encryption_method = determine_encryption_method(self.config["encrypt"])
self.encryption_method = encryption_method(self.name, self.config)
def _decrypt(self, text: bytes) -> str:
if self.encryption_method is None:
self._get_encryption_method()
return self.encryption_method.decrypt(text)
def _encrypt(self, text: str) -> bytes:
if self.encryption_method is None:
self._get_encryption_method()
return self.encryption_method.encrypt(text)
def open(self, filename: str | None = None) -> "Journal":
"""Opens the journal file and parses it into a list of Entries
def open(self, filename=None):
"""Opens the journal file defined in the config and parses it into a list of Entries.
Entries have the form (date, title, body)."""
filename = filename or self.config["journal"]
dirname = os.path.dirname(filename)
if not os.path.exists(filename):
if not os.path.isdir(dirname):
os.makedirs(dirname)
print_msg(
Message(
MsgText.DirectoryCreated,
MsgStyle.NORMAL,
{"directory_name": dirname},
)
)
print(f"[Directory {dirname} created]", file=sys.stderr)
self.create_file(filename)
print_msg(
Message(
MsgText.JournalCreated,
MsgStyle.NORMAL,
{
"journal_name": self.name,
"filename": filename,
},
)
)
self.write()
print(f"[Journal '{self.name}' created at {filename}]", file=sys.stderr)
text = self._load(filename)
text = self._decrypt(text)
self.entries = self._parse(text)
self.sort()
logging.debug("opened %s with %d entries", self.__class__.__name__, len(self))
return self
def write(self, filename: str | None = None) -> None:
def write(self, filename=None):
"""Dumps the journal into the config file, overwriting it"""
filename = filename or self.config["journal"]
text = self._to_text()
text = self._encrypt(text)
self._store(filename, text)
def validate_parsing(self) -> bool:
"""Confirms that the jrnl is still parsed correctly after conversion to text."""
def validate_parsing(self):
"""Confirms that the jrnl is still parsed correctly after being dumped to text."""
new_entries = self._parse(self._to_text())
return all(entry == new_entries[i] for i, entry in enumerate(self.entries))
for i, entry in enumerate(self.entries):
if entry != new_entries[i]:
return False
return True
@staticmethod
def create_file(filename: str) -> None:
def create_file(filename):
with open(filename, "w"):
pass
def _to_text(self) -> str:
def _to_text(self):
return "\n".join([str(e) for e in self.entries])
def _load(self, filename: str) -> bytes:
with open(filename, "rb") as f:
return f.read()
def _load(self, filename):
raise NotImplementedError
def _store(self, filename: str, text: bytes) -> None:
with open(filename, "wb") as f:
f.write(text)
@classmethod
def _store(filename, text):
raise NotImplementedError
def _parse(self, journal_txt: str) -> list[Entry]:
def _parse(self, journal_txt):
"""Parses a journal that's stored in a string and returns a list of entries"""
# Return empty array if the journal is blank
@ -190,11 +147,11 @@ class Journal:
if entries:
entries[-1].text = journal_txt[last_entry_pos : match.start()]
last_entry_pos = match.end()
entries.append(Entry(self, date=new_date))
entries.append(Entry.Entry(self, date=new_date))
# If no entries were found, treat all the existing text as an entry made now
if not entries:
entries.append(Entry(self, date=time.parse("now")))
entries.append(Entry.Entry(self, date=time.parse("now")))
# Fill in the text of the last entry
entries[-1].text = journal_txt[last_entry_pos:]
@ -203,7 +160,7 @@ class Journal:
entry._parse_text()
return entries
def pprint(self, short: bool = False) -> str:
def pprint(self, short=False):
"""Prettyprints the journal's entries"""
return "\n".join([e.pprint(short=short) for e in self.entries])
@ -213,21 +170,20 @@ class Journal:
def __repr__(self):
return f"<Journal with {len(self.entries)} entries>"
def sort(self) -> None:
def sort(self):
"""Sorts the Journal's entries by date"""
self.entries = sorted(self.entries, key=lambda entry: entry.date)
def limit(self, n: int | None = None) -> None:
def limit(self, n=None):
"""Removes all but the last n entries"""
if n:
self.entries = self.entries[-n:]
@property
def tags(self) -> list[Tag]:
def tags(self):
"""Returns a set of tuples (count, tag) for all tags present in the journal."""
# Astute reader: should the following line leave you as puzzled as me the first
# time I came across this construction, worry not and embrace the ensuing moment
# of enlightment.
# Astute reader: should the following line leave you as puzzled as me the first time
# I came across this construction, worry not and embrace the ensuing moment of enlightment.
tags = [tag for entry in self.entries for tag in set(entry.tags)]
# To be read: [for entry in journal.entries: for tag in set(entry.tags): tag]
tag_counts = {(tags.count(tag), tag) for tag in tags}
@ -242,11 +198,8 @@ class Journal:
start_date=None,
end_date=None,
starred=False,
tagged=False,
exclude_starred=False,
exclude_tagged=False,
strict=False,
contains=[],
contains=None,
exclude=[],
):
"""Removes all entries from the journal that don't match the filter.
@ -268,15 +221,13 @@ class Journal:
start_date = time.parse(start_date)
# If strict mode is on, all tags have to be present in entry
has_tags = (
self.search_tags.issubset if strict else self.search_tags.intersection
)
tagged = self.search_tags.issubset if strict else self.search_tags.intersection
def excluded(tags):
return 0 < len([tag for tag in tags if tag in excluded_tags])
if contains:
contains_lower = [substring.casefold() for substring in contains]
contains_lower = contains.casefold()
# Create datetime object for comparison below
# this approach allows various formats
@ -286,9 +237,8 @@ class Journal:
result = [
entry
for entry in self.entries
if (not tags or has_tags(entry.tags))
and (not (starred or exclude_starred) or entry.starred == starred)
and (not (tagged or exclude_tagged) or bool(entry.tags) == tagged)
if (not tags or tagged(entry.tags))
and (not starred or entry.starred)
and (not month or entry.date.month == compare_d.month)
and (not day or entry.date.day == compare_d.day)
and (not year or entry.date.year == compare_d.year)
@ -298,67 +248,40 @@ class Journal:
and (
not contains
or (
strict
and all(
substring in entry.title.casefold()
or substring in entry.body.casefold()
for substring in contains_lower
)
)
or (
not strict
and any(
substring in entry.title.casefold()
or substring in entry.body.casefold()
for substring in contains_lower
)
contains_lower in entry.title.casefold()
or contains_lower in entry.body.casefold()
)
)
]
self.entries = result
def delete_entries(self, entries_to_delete: list[Entry]) -> None:
def delete_entries(self, entries_to_delete):
"""Deletes specific entries from a journal."""
for entry in entries_to_delete:
self.entries.remove(entry)
self.deleted_entry_count += 1
def change_date_entries(
self, date: datetime.datetime, entries_to_change: list[Entry]
) -> None:
"""Changes entry dates to given date."""
date = time.parse(date)
def prompt_delete_entries(self):
"""Prompts for deletion of each of the entries in a journal.
Returns the entries the user wishes to delete."""
for entry in entries_to_change:
entry.date = date
entry.modified = True
to_delete = []
def prompt_action_entries(self, msg: MsgText) -> list[Entry]:
"""Prompts for action for each entry in a journal, using given message.
Returns the entries the user wishes to apply the action on."""
to_act = []
def ask_action(entry):
def ask_delete(entry):
return yesno(
Message(
msg,
params={"entry_title": entry.pprint(short=True)},
),
f"Delete entry '{entry.pprint(short=True)}'?",
default=False,
)
for entry in self.entries:
if ask_action(entry):
to_act.append(entry)
if ask_delete(entry):
to_delete.append(entry)
return to_act
return to_delete
def new_entry(self, raw: str, date=None, sort: bool = True) -> Entry:
def new_entry(self, raw, date=None, sort=True):
"""Constructs a new entry from some raw text input.
If a date is given, it will parse and use this, otherwise scan for a date in
the input first.
"""
If a date is given, it will parse and use this, otherwise scan for a date in the input first."""
raw = raw.replace("\\n ", "\n").replace("\\n", "\n")
# Split raw text into title and body
@ -385,19 +308,19 @@ class Journal:
)
if not date: # Still nothing? Meh, just live in the moment.
date = time.parse("now")
entry = Entry(self, date, raw, starred=starred)
entry = Entry.Entry(self, date, raw, starred=starred)
entry.modified = True
self.entries.append(entry)
if sort:
self.sort()
return entry
def editable_str(self) -> str:
def editable_str(self):
"""Turns the journal into a string of entries that can be edited
manually and later be parsed with self.parse_editable_str."""
manually and later be parsed with eslf.parse_editable_str."""
return "\n".join([str(e) for e in self.entries])
def parse_editable_str(self, edited: str) -> None:
def parse_editable_str(self, edited):
"""Parses the output of self.editable_str and updates it's entries."""
mod_entries = self._parse(edited)
# Match those entries that can be found in self.entries and set
@ -405,23 +328,17 @@ class Journal:
# modified and how many got deleted later.
for entry in mod_entries:
entry.modified = not any(entry == old_entry for old_entry in self.entries)
self.increment_change_counts_by_edit(mod_entries)
self.entries = mod_entries
def increment_change_counts_by_edit(self, mod_entries: Entry) -> None:
if len(mod_entries) > len(self.entries):
self.added_entry_count += len(mod_entries) - len(self.entries)
else:
self.deleted_entry_count += len(self.entries) - len(mod_entries)
def get_change_counts(self) -> dict:
return {
"added": self.added_entry_count,
"deleted": self.deleted_entry_count,
"modified": len([e for e in self.entries if e.modified]),
}
class PlainJournal(Journal):
def _load(self, filename):
with open(filename, "r", encoding="utf-8") as f:
return f.read()
def _store(self, filename, text):
with open(filename, "w", encoding="utf-8") as f:
f.write(text)
class LegacyJournal(Journal):
@ -429,7 +346,11 @@ class LegacyJournal(Journal):
standard. Main difference here is that in 1.x, timestamps were not cuddled
by square brackets. You'll not be able to save these journals anymore."""
def _parse(self, journal_txt: str) -> list[Entry]:
def _load(self, filename):
with open(filename, "r", encoding="utf-8") as f:
return f.read()
def _parse(self, journal_txt):
"""Parses a journal that's stored in a string and returns a list of entries"""
# Entries start with a line that looks like 'date title' - let's figure out how
# long the date will be by constructing one
@ -457,7 +378,7 @@ class LegacyJournal(Journal):
else:
starred = False
current_entry = Entry(
current_entry = Entry.Entry(
self, date=new_date, text=line[date_length + 1 :], starred=starred
)
except ValueError:
@ -476,50 +397,47 @@ class LegacyJournal(Journal):
return entries
def open_journal(journal_name: str, config: dict, legacy: bool = False) -> Journal:
def open_journal(journal_name, config, legacy=False):
"""
Creates a normal, encrypted or DayOne journal based on the passed config.
If legacy is True, it will open Journals with legacy classes build for
backwards compatibility with jrnl 1.x
"""
logging.debug(f"open_journal '{journal_name}'")
validate_journal_name(journal_name, config)
config = config.copy()
config["journal"] = expand_path(config["journal"])
config["journal"] = os.path.expanduser(os.path.expandvars(config["journal"]))
if os.path.isdir(config["journal"]):
if config["encrypt"]:
print_msg(
Message(
MsgText.ConfigEncryptedForUnencryptableJournalType,
MsgStyle.WARNING,
{
"journal_name": journal_name,
},
)
print(
"Warning: This journal's config has 'encrypt' set to true, but this type of journal can't be encrypted.",
file=sys.stderr,
)
if config["journal"].strip("/").endswith(".dayone") or "entries" in os.listdir(
config["journal"]
):
from jrnl.journals import DayOne
from . import DayOneJournal
return DayOne(**config).open()
return DayOneJournal.DayOne(**config).open()
else:
from jrnl.journals import Folder
from . import FolderJournal
return Folder(journal_name, **config).open()
return FolderJournal.Folder(journal_name, **config).open()
if not config["encrypt"]:
if legacy:
return LegacyJournal(journal_name, **config).open()
if config["journal"].endswith(os.sep):
from jrnl.journals import Folder
return PlainJournal(journal_name, **config).open()
return Folder(journal_name, **config).open()
return Journal(journal_name, **config).open()
from . import EncryptedJournal
if legacy:
config["encrypt"] = "jrnlv1"
return LegacyJournal(journal_name, **config).open()
return Journal(journal_name, **config).open()
try:
if legacy:
return EncryptedJournal.LegacyEncryptedJournal(
journal_name, **config
).open()
return EncryptedJournal.EncryptedJournal(journal_name, **config).open()
except KeyboardInterrupt:
# Since encrypted journals prompt for a password, it's easy for a user to ctrl+c out
print("[Interrupted while opening journal]", file=sys.stderr)
sys.exit(1)

View file

@ -1,8 +1,8 @@
# Copyright © 2012-2023 jrnl contributors
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
try:
from jrnl.__version__ import __version__
from .__version__ import __version__
except ImportError:
__version__ = "source"
__title__ = "jrnl"

View file

@ -1,9 +1,9 @@
# Copyright © 2012-2023 jrnl contributors
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import sys
from jrnl.main import run
from .cli import cli
if __name__ == "__main__":
sys.exit(run())
sys.exit(cli())

View file

@ -1 +1 @@
__version__ = "v4.2.1"
__version__ = "v2.8.4-beta2"

View file

@ -1,26 +1,26 @@
# Copyright © 2012-2023 jrnl contributors
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import argparse
import re
import textwrap
from jrnl.commands import postconfig_decrypt
from jrnl.commands import postconfig_encrypt
from jrnl.commands import postconfig_import
from jrnl.commands import postconfig_list
from jrnl.commands import preconfig_diagnostic
from jrnl.commands import preconfig_version
from jrnl.output import deprecated_cmd
from jrnl.plugins import EXPORT_FORMATS
from jrnl.plugins import IMPORT_FORMATS
from jrnl.plugins import util
from .commands import postconfig_decrypt
from .commands import postconfig_encrypt
from .commands import postconfig_import
from .commands import postconfig_list
from .commands import preconfig_diagnostic
from .commands import preconfig_version
from .output import deprecated_cmd
from .plugins import EXPORT_FORMATS
from .plugins import IMPORT_FORMATS
from .plugins import util
class WrappingFormatter(argparse.RawTextHelpFormatter):
"""Used in help screen"""
def _split_lines(self, text: str, width: int) -> list[str]:
def _split_lines(self, text, width):
text = text.split("\n\n")
text = map(lambda t: self._whitespace_matcher.sub(" ", t).strip(), text)
text = map(lambda t: textwrap.wrap(t, width=56), text)
@ -28,44 +28,7 @@ class WrappingFormatter(argparse.RawTextHelpFormatter):
return text
class IgnoreNoneAppendAction(argparse._AppendAction):
"""
Pass -not without a following string and avoid appending
a None value to the excluded list
"""
def __call__(self, parser, namespace, values, option_string=None):
if values is not None:
super().__call__(parser, namespace, values, option_string)
def parse_not_arg(
args: list[str], parsed_args: argparse.Namespace, parser: argparse.ArgumentParser
) -> argparse.Namespace:
"""
It's possible to use -not as a precursor to -starred and -tagged
to reverse their behaviour, however this requires some extra logic
to parse, and to ensure we still do not allow passing an empty -not
"""
parsed_args.exclude_starred = False
parsed_args.exclude_tagged = False
if "-not-starred" in "".join(args):
parsed_args.starred = False
parsed_args.exclude_starred = True
if "-not-tagged" in "".join(args):
parsed_args.tagged = False
parsed_args.exclude_tagged = True
if "-not" in args and not any(
[parsed_args.exclude_starred, parsed_args.exclude_tagged, parsed_args.excluded]
):
parser.error("argument -not: expected 1 argument")
return parsed_args
def parse_args(args: list[str] = []) -> argparse.Namespace:
def parse_args(args=[]):
"""
Argument parsing that is doable before the config is available.
Everything else goes into "text" for later parsing.
@ -76,9 +39,9 @@ def parse_args(args: list[str] = []) -> argparse.Namespace:
description="Collect your thoughts and notes without leaving the command line",
epilog=textwrap.dedent(
"""
We gratefully thank all contributors!
Come see the whole list of code and financial contributors at https://github.com/jrnl-org/jrnl
And special thanks to Bad Lip Reading for the Yoda joke in the Writing section above :)""" # noqa: E501
Thank you to all of our contributors! Come see the whole list of code and
financial contributors at https://github.com/jrnl-org/jrnl. And special
thanks to Bad Lip Reading for the Yoda joke in the Writing section above."""
),
)
@ -122,13 +85,7 @@ def parse_args(args: list[str] = []) -> argparse.Namespace:
action="store_const",
const=postconfig_list,
dest="postconfig_cmd",
help="""
List all configured journals.
Optional parameters:
--format [json or yaml]
""",
help="List all configured journals",
)
standalone.add_argument(
"--ls",
@ -211,12 +168,6 @@ def parse_args(args: list[str] = []) -> argparse.Namespace:
"Writing", textwrap.dedent(compose_msg).strip()
)
composing.add_argument("text", metavar="", nargs="*")
composing.add_argument(
"--template",
dest="template",
help="Path to template file. Can be a local path, absolute path, or a path "
"relative to $XDG_DATA_HOME/jrnl/templates/",
)
read_msg = (
"To find entries from your journal, use any combination of the below filters."
@ -265,17 +216,14 @@ def parse_args(args: list[str] = []) -> argparse.Namespace:
reading.add_argument(
"-contains",
dest="contains",
action="append",
metavar="TEXT",
help="Show entries containing specific text (put quotes around text with "
"spaces)",
help="Show entries containing specific text (put quotes around text with spaces)",
)
reading.add_argument(
"-and",
dest="strict",
action="store_true",
help='Show only entries that match all conditions, like saying "x AND y" '
"(default: OR)",
help='Show only entries that match all conditions, like saying "x AND y" (default: OR)',
)
reading.add_argument(
"-starred",
@ -283,19 +231,12 @@ def parse_args(args: list[str] = []) -> argparse.Namespace:
action="store_true",
help="Show only starred entries (marked with *)",
)
reading.add_argument(
"-tagged",
dest="tagged",
action="store_true",
help="Show only entries that have at least one tag",
)
reading.add_argument(
"-n",
dest="limit",
default=None,
metavar="NUMBER",
help="Show a maximum of NUMBER entries (note: '-n 3' and '-3' have the same "
"effect)",
help="Show a maximum of NUMBER entries (note: '-n 3' and '-3' have the same effect)",
nargs="?",
type=int,
)
@ -304,21 +245,13 @@ def parse_args(args: list[str] = []) -> argparse.Namespace:
dest="excluded",
nargs="?",
default=[],
metavar="TAG/FLAG",
action=IgnoreNoneAppendAction,
help=(
"If passed a string, will exclude entries with that tag. "
"Can be also used before -starred or -tagged flags, to exclude "
"starred or tagged entries respectively."
),
metavar="TAG",
action="append",
help="Exclude entries with this tag",
)
search_options_msg = (
" " # Preserves indentation
"""
These help you do various tasks with the selected entries from your search.
If used on their own (with no search), they will act on your entire journal"""
)
search_options_msg = """ These help you do various tasks with the selected entries from your search.
If used on their own (with no search), they will act on your entire journal"""
exporting = parser.add_argument_group(
"Searching Options", textwrap.dedent(search_options_msg)
)
@ -334,14 +267,6 @@ def parse_args(args: list[str] = []) -> argparse.Namespace:
action="store_true",
help="Interactively deletes selected entries",
)
exporting.add_argument(
"--change-time",
dest="change_time",
nargs="?",
metavar="DATE",
const="now",
help="Change timestamp for selected entries (default: now)",
)
exporting.add_argument(
"--format",
metavar="TYPE",
@ -369,8 +294,7 @@ def parse_args(args: list[str] = []) -> argparse.Namespace:
"--tags",
dest="tags",
action="store_true",
help="Alias for '--format tags'. Returns a list of all tags and number of "
"occurrences",
help="Alias for '--format tags'. Returns a list of all tags and number of occurences",
)
exporting.add_argument(
"--short",
@ -410,7 +334,7 @@ def parse_args(args: list[str] = []) -> argparse.Namespace:
\t jrnl --config-override editor "nano" \n
\t - Override color selections\n
\t jrnl --config-override colors.body blue --config-override colors.title green
""", # noqa: E501
""",
)
config_overrides.add_argument(
"--co",
@ -440,7 +364,7 @@ def parse_args(args: list[str] = []) -> argparse.Namespace:
\t jrnl --config-file /home/user1/work_config.yaml
\t - Use a personal config file stored on a thumb drive: \n
\t jrnl --config-file /media/user1/my-thumb-drive/personal_config.yaml
""", # noqa: E501
""",
)
alternate_config.add_argument(
@ -450,7 +374,5 @@ def parse_args(args: list[str] = []) -> argparse.Namespace:
# Handle '-123' as a shortcut for '-n 123'
num = re.compile(r"^-(\d+)$")
args = [num.sub(r"-n \1", arg) for arg in args]
parsed_args = parser.parse_intermixed_args(args)
parsed_args = parse_not_arg(args, parsed_args, parser)
return parsed_args
return parser.parse_intermixed_args(args)

41
jrnl/cli.py Normal file
View file

@ -0,0 +1,41 @@
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import logging
import sys
from .jrnl import run
from .args import parse_args
from .exception import JrnlError
def configure_logger(debug=False):
if not debug:
logging.disable()
return
logging.basicConfig(
level=logging.DEBUG,
format="%(levelname)-8s %(name)-12s %(message)s",
)
logging.getLogger("parsedatetime").setLevel(logging.INFO)
logging.getLogger("keyring.backend").setLevel(logging.ERROR)
def cli(manual_args=None):
try:
if manual_args is None:
manual_args = sys.argv[1:]
args = parse_args(manual_args)
configure_logger(args.debug)
logging.debug("Parsed args: %s", args)
return run(args)
except JrnlError as e:
print(e.message, file=sys.stderr)
return 1
except KeyboardInterrupt:
return 1

View file

@ -1,23 +1,20 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import re
from string import punctuation
from string import whitespace
from typing import TYPE_CHECKING
import colorama
from jrnl.os_compat import on_windows
if TYPE_CHECKING:
from jrnl.journals import Entry
from .os_compat import on_windows
if on_windows():
colorama.init()
WARNING_COLOR = colorama.Fore.YELLOW
ERROR_COLOR = colorama.Fore.RED
RESET_COLOR = colorama.Fore.RESET
def colorize(string: str, color: str, bold: bool = False) -> str:
def colorize(string, color, bold=False):
"""Returns the string colored with colorama.Fore.color. If the color set by
the user is "NONE" or the color doesn't exist in the colorama.Fore attributes,
it returns the string without any modification."""
@ -30,9 +27,7 @@ def colorize(string: str, color: str, bold: bool = False) -> str:
return colorama.Style.BRIGHT + color_escape + string + colorama.Style.RESET_ALL
def highlight_tags_with_background_color(
entry: "Entry", text: str, color: str, is_title: bool = False
) -> str:
def highlight_tags_with_background_color(entry, text, color, is_title=False):
"""
Takes a string and colorizes the tags in it based upon the config value for
color.tags, while colorizing the rest of the text based on `color`.
@ -51,9 +46,9 @@ def highlight_tags_with_background_color(
:returns [(colorized_str, original_str)]"""
for part in fragments:
if part and part[0] not in config["tagsymbols"]:
yield colorize(part, color, bold=is_title), part
yield (colorize(part, color, bold=is_title), part)
elif part:
yield colorize(part, config["colors"]["tags"], bold=True), part
yield (colorize(part, config["colors"]["tags"], bold=True), part)
config = entry.journal.config
if config["highlight"]: # highlight tags

View file

@ -1,6 +1,3 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
"""
Functions in this file are standalone commands. All standalone commands are split into
two categories depending on whether they require the config to be loaded to be able to
@ -14,128 +11,79 @@ run.
Also, please note that all (non-builtin) imports should be scoped to each function to
avoid any possible overhead for these standalone commands.
"""
import argparse
import logging
import platform
import sys
from jrnl.config import cmd_requires_valid_journal_name
from jrnl.exception import JrnlException
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
from jrnl.output import print_msg
from .exception import JrnlError
def preconfig_diagnostic(_) -> None:
from jrnl import __title__
def preconfig_diagnostic(_):
from jrnl import __version__
print(
f"{__title__}: {__version__}\n"
f"jrnl: {__version__}\n"
f"Python: {sys.version}\n"
f"OS: {platform.system()} {platform.release()}"
)
def preconfig_version(_) -> None:
import textwrap
def preconfig_version(_):
from jrnl import __title__
from jrnl import __version__
output = f"""
{__title__} {__version__}
version_str = f"""{__title__} version {__version__}
Copyright © 2012-2023 jrnl contributors
Copyright (C) 2012-2021 jrnl contributors
This is free software, and you are welcome to redistribute it under certain
conditions; for details, see: https://www.gnu.org/licenses/gpl-3.0.html
"""
This is free software, and you are welcome to redistribute it under certain
conditions; for details, see: https://www.gnu.org/licenses/gpl-3.0.html"""
output = textwrap.dedent(output).strip()
print(output)
print(version_str)
def postconfig_list(args: argparse.Namespace, config: dict, **_) -> int:
from jrnl.output import list_journals
def postconfig_list(config, **kwargs):
from .output import list_journals
print(list_journals(config, args.export))
return 0
print(list_journals(config))
@cmd_requires_valid_journal_name
def postconfig_import(args: argparse.Namespace, config: dict, **_) -> int:
from jrnl.journals import open_journal
from jrnl.plugins import get_importer
def postconfig_import(args, config, **kwargs):
from .Journal import open_journal
from .plugins import get_importer
# Requires opening the journal
journal = open_journal(args.journal_name, config)
format = args.export if args.export else "jrnl"
if (importer := get_importer(format)) is None:
raise JrnlException(
Message(
MsgText.ImporterNotFound,
MsgStyle.ERROR,
{"format": format},
)
)
importer.import_(journal, args.filename)
return 0
get_importer(format).import_(journal, args.filename)
@cmd_requires_valid_journal_name
def postconfig_encrypt(
args: argparse.Namespace, config: dict, original_config: dict
) -> int:
def postconfig_encrypt(args, config, original_config, **kwargs):
"""
Encrypt a journal in place, or optionally to a new file
"""
from jrnl.config import update_config
from jrnl.install import save_config
from jrnl.journals import open_journal
from .EncryptedJournal import EncryptedJournal
from .Journal import open_journal
from .config import update_config
from .install import save_config
# Open the journal
journal = open_journal(args.journal_name, config)
if hasattr(journal, "can_be_encrypted") and not journal.can_be_encrypted:
raise JrnlException(
Message(
MsgText.CannotEncryptJournalType,
MsgStyle.ERROR,
{
"journal_name": args.journal_name,
"journal_type": journal.__class__.__name__,
},
)
raise JrnlError(
"CannotEncryptJournalType",
journal_name=args.journal_name,
journal_type=journal.__class__.__name__,
)
# If journal is encrypted, create new password
logging.debug("Clearing encryption method...")
journal.config["encrypt"] = True
if journal.config["encrypt"] is True:
logging.debug("Journal already encrypted. Re-encrypting...")
print(f"Journal {journal.name} is already encrypted. Create a new password.")
journal.encryption_method.clear()
else:
journal.config["encrypt"] = True
journal.encryption_method = None
new_journal = EncryptedJournal.from_journal(journal)
new_journal.write(args.filename)
journal.write(args.filename)
print_msg(
Message(
MsgText.JournalEncryptedTo,
MsgStyle.NORMAL,
{"path": args.filename or journal.config["journal"]},
)
print(
f"Journal encrypted to {args.filename or new_journal.config['journal']}.",
file=sys.stderr,
)
# Update the config, if we encrypted in place
@ -145,31 +93,22 @@ def postconfig_encrypt(
)
save_config(original_config)
return 0
@cmd_requires_valid_journal_name
def postconfig_decrypt(
args: argparse.Namespace, config: dict, original_config: dict
) -> int:
"""Decrypts to file. If filename is not set, we encrypt the journal file itself."""
from jrnl.config import update_config
from jrnl.install import save_config
from jrnl.journals import open_journal
def postconfig_decrypt(args, config, original_config, **kwargs):
"""Decrypts into new file. If filename is not set, we encrypt the journal file itself."""
from .Journal import PlainJournal
from .Journal import open_journal
from .config import update_config
from .install import save_config
journal = open_journal(args.journal_name, config)
logging.debug("Clearing encryption method...")
journal.config["encrypt"] = False
journal.encryption_method = None
journal.write(args.filename)
print_msg(
Message(
MsgText.JournalDecryptedTo,
MsgStyle.NORMAL,
{"path": args.filename or journal.config["journal"]},
)
new_journal = PlainJournal.from_journal(journal)
new_journal.write(args.filename)
print(
f"Journal decrypted to {args.filename or new_journal.config['journal']}.",
file=sys.stderr,
)
# Update the config, if we decrypted in place
@ -178,5 +117,3 @@ def postconfig_decrypt(
original_config, {"encrypt": False}, args.journal_name, force_local=True
)
save_config(original_config)
return 0

View file

@ -1,28 +1,22 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import argparse
import logging
import os
from typing import Any
from typing import Callable
import sys
import colorama
from rich.pretty import pretty_repr
from ruamel.yaml import YAML
from ruamel.yaml import constructor
import yaml
import xdg.BaseDirectory
from jrnl import __version__
from jrnl.exception import JrnlException
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
from jrnl.output import list_journals
from jrnl.output import print_msg
from jrnl.path import get_config_path
from jrnl.path import get_default_journal_path
from . import __version__
from .exception import JrnlError
from .color import ERROR_COLOR
from .color import RESET_COLOR
from .output import list_journals
# Constants
DEFAULT_CONFIG_NAME = "jrnl.yaml"
XDG_RESOURCE = "jrnl"
DEFAULT_JOURNAL_NAME = "journal.txt"
DEFAULT_JOURNAL_KEY = "default"
YAML_SEPARATOR = ": "
@ -30,6 +24,7 @@ YAML_FILE_ENCODING = "utf-8"
def make_yaml_valid_dict(input: list) -> dict:
"""
Convert a two-element list of configuration key-value pair into a flat dict.
@ -37,10 +32,9 @@ def make_yaml_valid_dict(input: list) -> dict:
The dict is created through the yaml loader, with the assumption that
"input[0]: input[1]" is valid yaml.
:param input: list of configuration keys in dot-notation and their respective values
:param input: list of configuration keys in dot-notation and their respective values.
:type input: list
:return: A single level dict of the configuration keys in dot-notation and their
respective desired values
:return: A single level dict of the configuration keys in dot-notation and their respective desired values
:rtype: dict
"""
@ -48,80 +42,91 @@ def make_yaml_valid_dict(input: list) -> dict:
# yaml compatible strings are of the form Key:Value
yamlstr = YAML_SEPARATOR.join(input)
runtime_modifications = YAML(typ="safe").load(yamlstr)
runtime_modifications = yaml.load(yamlstr, Loader=yaml.SafeLoader)
return runtime_modifications
def save_config(config: dict, alt_config_path: str | None = None) -> None:
def save_config(config, alt_config_path=None):
"""Supply alt_config_path if using an alternate config through --config-file."""
config["version"] = __version__
yaml = YAML(typ="safe")
yaml.default_flow_style = False # prevents collapsing of tree structure
with open(
alt_config_path if alt_config_path else get_config_path(),
"w",
encoding=YAML_FILE_ENCODING,
) as f:
yaml.dump(config, f)
yaml.safe_dump(
config,
f,
encoding=YAML_FILE_ENCODING,
allow_unicode=True,
default_flow_style=False,
)
def get_default_config() -> dict[str, Any]:
def get_config_path():
try:
config_directory_path = xdg.BaseDirectory.save_config_path(XDG_RESOURCE)
except FileExistsError:
raise JrnlError(
"ConfigDirectoryIsFile",
config_directory_path=os.path.join(
xdg.BaseDirectory.xdg_config_home, XDG_RESOURCE
),
)
return os.path.join(
config_directory_path or os.path.expanduser("~"), DEFAULT_CONFIG_NAME
)
def get_default_config():
return {
"version": __version__,
"journals": {"default": {"journal": get_default_journal_path()}},
"journals": {"default": get_default_journal_path()},
"editor": os.getenv("VISUAL") or os.getenv("EDITOR") or "",
"encrypt": False,
"template": False,
"default_hour": 9,
"default_minute": 0,
"timeformat": "%F %r",
"timeformat": "%Y-%m-%d %H:%M",
"tagsymbols": "#@",
"highlight": True,
"linewrap": 79,
"indent_character": "|",
"colors": {
"body": "none",
"date": "none",
"tags": "none",
"title": "none",
"body": "none",
"tags": "none",
},
}
def get_default_colors() -> dict[str, Any]:
return {
"body": "none",
"date": "black",
"tags": "yellow",
"title": "cyan",
}
def get_default_journal_path():
journal_data_path = xdg.BaseDirectory.save_data_path(
XDG_RESOURCE
) or os.path.expanduser("~")
return os.path.join(journal_data_path, DEFAULT_JOURNAL_NAME)
def scope_config(config: dict, journal_name: str) -> dict:
def scope_config(config, journal_name):
if journal_name not in config["journals"]:
return config
config = config.copy()
journal_conf = config["journals"].get(journal_name)
if isinstance(journal_conf, dict):
if type(journal_conf) is dict:
# We can override the default config on a by-journal basis
logging.debug(
"Updating configuration with specific journal overrides:\n%s",
pretty_repr(journal_conf),
"Updating configuration with specific journal overrides %s", journal_conf
)
config.update(journal_conf)
else:
# But also just give them a string to point to the journal file
config["journal"] = journal_conf
logging.debug("Scoped config:\n%s", pretty_repr(config))
return config
def verify_config_colors(config: dict) -> bool:
def verify_config_colors(config):
"""
Ensures the keys set for colors are valid colorama.Fore attributes, or "None"
:return: True if all keys are set correctly, False otherwise
@ -132,56 +137,33 @@ def verify_config_colors(config: dict) -> bool:
if upper_color == "NONE":
continue
if not getattr(colorama.Fore, upper_color, None):
print_msg(
Message(
MsgText.InvalidColor,
MsgStyle.NORMAL,
{
"key": key,
"color": color,
},
)
print(
"[{2}ERROR{3}: {0} set to invalid color: {1}]".format(
key, color, ERROR_COLOR, RESET_COLOR
),
file=sys.stderr,
)
all_valid_colors = False
return all_valid_colors
def load_config(config_path: str) -> dict:
def load_config(config_path):
"""Tries to load a config file from YAML."""
try:
with open(config_path, encoding=YAML_FILE_ENCODING) as f:
yaml = YAML(typ="safe")
yaml.allow_duplicate_keys = False
return yaml.load(f)
except constructor.DuplicateKeyError as e:
print_msg(
Message(
MsgText.ConfigDoubleKeys,
MsgStyle.WARNING,
{
"error_message": e,
},
)
)
with open(config_path, encoding=YAML_FILE_ENCODING) as f:
yaml = YAML(typ="safe")
yaml.allow_duplicate_keys = True
return yaml.load(f)
with open(config_path, encoding=YAML_FILE_ENCODING) as f:
return yaml.load(f, Loader=yaml.SafeLoader)
def is_config_json(config_path: str) -> bool:
def is_config_json(config_path):
with open(config_path, "r", encoding="utf-8") as f:
config_file = f.read()
return config_file.strip().startswith("{")
def update_config(
config: dict, new_config: dict, scope: str | None, force_local: bool = False
) -> None:
def update_config(config, new_config, scope, force_local=False):
"""Updates a config dict with new values - either global if scope is None
or config['journals'][scope] is just a string pointing to a journal file,
or within the scope"""
if scope and isinstance(config["journals"][scope], dict):
if scope and type(config["journals"][scope]) is dict: # Update to journal specific
config["journals"][scope].update(new_config)
elif scope and force_local: # Convert to dict
config["journals"][scope] = {"journal": config["journals"][scope]}
@ -190,7 +172,7 @@ def update_config(
config.update(new_config)
def get_journal_name(args: argparse.Namespace, config: dict) -> argparse.Namespace:
def get_journal_name(args, config):
args.journal_name = DEFAULT_JOURNAL_KEY
# The first arg might be a journal name
@ -203,27 +185,10 @@ def get_journal_name(args: argparse.Namespace, config: dict) -> argparse.Namespa
args.journal_name = potential_journal_name
args.text = args.text[1:]
if args.journal_name not in config["journals"]:
print("No default journal configured.", file=sys.stderr)
print(list_journals(config), file=sys.stderr)
sys.exit(1)
logging.debug("Using journal name: %s", args.journal_name)
return args
def cmd_requires_valid_journal_name(func: Callable) -> Callable:
def wrapper(args: argparse.Namespace, config: dict, original_config: dict):
validate_journal_name(args.journal_name, config)
func(args=args, config=config, original_config=original_config)
return wrapper
def validate_journal_name(journal_name: str, config: dict) -> None:
if journal_name not in config["journals"]:
raise JrnlException(
Message(
MsgText.NoNamedJournal,
MsgStyle.ERROR,
{
"journal_name": journal_name,
"journals": list_journals(config),
},
),
)

View file

@ -1,455 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import logging
import sys
from typing import TYPE_CHECKING
from jrnl import install
from jrnl import plugins
from jrnl import time
from jrnl.config import DEFAULT_JOURNAL_KEY
from jrnl.config import get_config_path
from jrnl.config import get_journal_name
from jrnl.config import scope_config
from jrnl.editor import get_text_from_editor
from jrnl.editor import get_text_from_stdin
from jrnl.editor import read_template_file
from jrnl.exception import JrnlException
from jrnl.journals import open_journal
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
from jrnl.output import print_msg
from jrnl.output import print_msgs
from jrnl.override import apply_overrides
if TYPE_CHECKING:
from argparse import Namespace
from jrnl.journals import Entry
from jrnl.journals import Journal
def run(args: "Namespace"):
"""
Flow:
1. Run standalone command if it doesn't need config (help, version, etc), then exit
2. Load config
3. Run standalone command if it does need config (encrypt, decrypt, etc), then exit
4. Load specified journal
5. Start append mode, or search mode
6. Perform actions with results from search mode (if needed)
7. Profit
"""
# Run command if possible before config is available
if callable(args.preconfig_cmd):
return args.preconfig_cmd(args)
# Load the config, and extract journal name
config = install.load_or_install_jrnl(args.config_file_path)
original_config = config.copy()
# Apply config overrides
config = apply_overrides(args, config)
args = get_journal_name(args, config)
config = scope_config(config, args.journal_name)
# Run post-config command now that config is ready
if callable(args.postconfig_cmd):
return args.postconfig_cmd(
args=args, config=config, original_config=original_config
)
# --- All the standalone commands are now done --- #
# Get the journal we're going to be working with
journal = open_journal(args.journal_name, config)
kwargs = {
"args": args,
"config": config,
"journal": journal,
"old_entries": journal.entries,
}
if _is_append_mode(**kwargs):
append_mode(**kwargs)
return
# If not append mode, then we're in search mode (only 2 modes exist)
search_mode(**kwargs)
entries_found_count = len(journal)
_print_entries_found_count(entries_found_count, args)
# Actions
_perform_actions_on_search_results(**kwargs)
if entries_found_count != 0 and _has_action_args(args):
_print_changed_counts(journal)
else:
# display only occurs if no other action occurs
_display_search_results(**kwargs)
def _perform_actions_on_search_results(**kwargs):
args = kwargs["args"]
# Perform actions (if needed)
if args.change_time:
_change_time_search_results(**kwargs)
if args.delete:
_delete_search_results(**kwargs)
# open results in editor (if `--edit` was used)
if args.edit:
_edit_search_results(**kwargs)
def _is_append_mode(args: "Namespace", config: dict, **kwargs) -> bool:
"""Determines if we are in append mode (as opposed to search mode)"""
# Are any search filters present? If so, then search mode.
append_mode = (
not _has_search_args(args)
and not _has_action_args(args)
and not _has_display_args(args)
)
# Might be writing and want to move to editor part of the way through
if args.edit and args.text:
append_mode = True
# If the text is entirely tags, then we are also searching (not writing)
if append_mode and args.text and _has_only_tags(config["tagsymbols"], args.text):
append_mode = False
return append_mode
def append_mode(args: "Namespace", config: dict, journal: "Journal", **kwargs) -> None:
"""
Gets input from the user to write to the journal
0. Check for a template passed as an argument, or in the global config
1. Check for input from cli
2. Check input being piped in
3. Open editor if configured (prepopulated with template if available)
4. Use stdin.read as last resort
6. Write any found text to journal, or exit
"""
logging.debug("Append mode: starting")
template_text = _get_template(args, config)
if args.text:
logging.debug(f"Append mode: cli text detected: {args.text}")
raw = " ".join(args.text).strip()
if args.edit:
raw = _write_in_editor(config, raw)
elif not sys.stdin.isatty():
logging.debug("Append mode: receiving piped text")
raw = sys.stdin.read()
else:
raw = _write_in_editor(config, template_text)
if template_text is not None and raw == template_text:
logging.error("Append mode: raw text was the same as the template")
raise JrnlException(Message(MsgText.NoChangesToTemplate, MsgStyle.NORMAL))
if not raw or raw.isspace():
logging.error("Append mode: couldn't get raw text or entry was empty")
raise JrnlException(Message(MsgText.NoTextReceived, MsgStyle.NORMAL))
logging.debug(
f"Append mode: appending raw text to journal '{args.journal_name}': {raw}"
)
journal.new_entry(raw)
if args.journal_name != DEFAULT_JOURNAL_KEY:
print_msg(
Message(
MsgText.JournalEntryAdded,
MsgStyle.NORMAL,
{"journal_name": args.journal_name},
)
)
journal.write()
logging.debug("Append mode: completed journal.write()")
def _get_template(args, config) -> str:
# Read template file and pass as raw text into the composer
logging.debug(
"Get template:\n"
f"--template: {args.template}\n"
f"from config: {config.get('template')}"
)
template_path = args.template or config.get("template")
template_text = None
if template_path:
template_text = read_template_file(template_path)
return template_text
def search_mode(args: "Namespace", journal: "Journal", **kwargs) -> None:
"""
Search for entries in a journal, and return the
results. If no search args, then return all results
"""
logging.debug("Search mode: starting")
# If no search args, then return all results (don't filter anything)
if not _has_search_args(args) and not _has_display_args(args) and not args.text:
logging.debug("Search mode: has no search args")
return
logging.debug("Search mode: has search args")
_filter_journal_entries(args, journal)
def _write_in_editor(config: dict, prepopulated_text: str | None = None) -> str:
if config["editor"]:
logging.debug("Append mode: opening editor")
raw = get_text_from_editor(config, prepopulated_text)
else:
raw = get_text_from_stdin()
return raw
def _filter_journal_entries(args: "Namespace", journal: "Journal", **kwargs) -> None:
"""Filter journal entries in-place based upon search args"""
if args.on_date:
args.start_date = args.end_date = args.on_date
if args.today_in_history:
now = time.parse("now")
args.day = now.day
args.month = now.month
journal.filter(
tags=args.text,
month=args.month,
day=args.day,
year=args.year,
start_date=args.start_date,
end_date=args.end_date,
strict=args.strict,
starred=args.starred,
tagged=args.tagged,
exclude=args.excluded,
exclude_starred=args.exclude_starred,
exclude_tagged=args.exclude_tagged,
contains=args.contains,
)
journal.limit(args.limit)
def _print_entries_found_count(count: int, args: "Namespace") -> None:
logging.debug(f"count: {count}")
if count == 0:
if args.edit or args.change_time:
print_msg(Message(MsgText.NothingToModify, MsgStyle.WARNING))
elif args.delete:
print_msg(Message(MsgText.NothingToDelete, MsgStyle.WARNING))
else:
print_msg(Message(MsgText.NoEntriesFound, MsgStyle.NORMAL))
return
elif args.limit and args.limit == count:
# Don't show count if the user expects a limited number of results
logging.debug("args.limit is true-ish")
return
logging.debug("Printing general summary")
my_msg = (
MsgText.EntryFoundCountSingular if count == 1 else MsgText.EntryFoundCountPlural
)
print_msg(Message(my_msg, MsgStyle.NORMAL, {"num": count}))
def _other_entries(journal: "Journal", entries: list["Entry"]) -> list["Entry"]:
"""Find entries that are not in journal"""
return [e for e in entries if e not in journal.entries]
def _edit_search_results(
config: dict, journal: "Journal", old_entries: list["Entry"], **kwargs
) -> None:
"""
1. Send the given journal entries to the user-configured editor
2. Print out stats on any modifications to journal
3. Write modifications to journal
"""
if not config["editor"]:
raise JrnlException(
Message(
MsgText.EditorNotConfigured,
MsgStyle.ERROR,
{"config_file": get_config_path()},
)
)
# separate entries we are not editing
other_entries = _other_entries(journal, old_entries)
# Send user to the editor
try:
edited = get_text_from_editor(config, journal.editable_str())
except JrnlException as e:
if e.has_message_text(MsgText.NoTextReceived):
raise JrnlException(
Message(MsgText.NoEditsReceivedJournalNotDeleted, MsgStyle.WARNING)
)
else:
raise e
journal.parse_editable_str(edited)
# Put back entries we separated earlier, sort, and write the journal
journal.entries += other_entries
journal.sort()
journal.write()
def _print_changed_counts(journal: "Journal", **kwargs) -> None:
stats = journal.get_change_counts()
msgs = []
if stats["added"] > 0:
my_msg = (
MsgText.JournalCountAddedSingular
if stats["added"] == 1
else MsgText.JournalCountAddedPlural
)
msgs.append(Message(my_msg, MsgStyle.NORMAL, {"num": stats["added"]}))
if stats["deleted"] > 0:
my_msg = (
MsgText.JournalCountDeletedSingular
if stats["deleted"] == 1
else MsgText.JournalCountDeletedPlural
)
msgs.append(Message(my_msg, MsgStyle.NORMAL, {"num": stats["deleted"]}))
if stats["modified"] > 0:
my_msg = (
MsgText.JournalCountModifiedSingular
if stats["modified"] == 1
else MsgText.JournalCountModifiedPlural
)
msgs.append(Message(my_msg, MsgStyle.NORMAL, {"num": stats["modified"]}))
if not msgs:
msgs.append(Message(MsgText.NoEditsReceived, MsgStyle.NORMAL))
print_msgs(msgs)
def _get_predit_stats(journal: "Journal") -> dict[str, int]:
return {"count": len(journal)}
def _delete_search_results(
journal: "Journal", old_entries: list["Entry"], **kwargs
) -> None:
entries_to_delete = journal.prompt_action_entries(MsgText.DeleteEntryQuestion)
journal.entries = old_entries
if entries_to_delete:
journal.delete_entries(entries_to_delete)
journal.write()
def _change_time_search_results(
args: "Namespace",
journal: "Journal",
old_entries: list["Entry"],
no_prompt: bool = False,
**kwargs,
) -> None:
# separate entries we are not editing
# @todo if there's only 1, don't prompt
entries_to_change = journal.prompt_action_entries(MsgText.ChangeTimeEntryQuestion)
if entries_to_change:
date = time.parse(args.change_time)
journal.entries = old_entries
journal.change_date_entries(date, entries_to_change)
journal.write()
def _display_search_results(args: "Namespace", journal: "Journal", **kwargs) -> None:
if len(journal) == 0:
return
# Get export format from config file if not provided at the command line
args.export = args.export or kwargs["config"].get("display_format")
if args.tags:
print(plugins.get_exporter("tags").export(journal))
elif args.short or args.export == "short":
print(journal.pprint(short=True))
elif args.export == "pretty":
print(journal.pprint())
elif args.export:
exporter = plugins.get_exporter(args.export)
print(exporter.export(journal, args.filename))
else:
print(journal.pprint())
def _has_search_args(args: "Namespace") -> bool:
"""Looking for arguments that filter a journal"""
return any(
(
args.contains,
args.tagged,
args.excluded,
args.exclude_starred,
args.exclude_tagged,
args.end_date,
args.today_in_history,
args.month,
args.day,
args.year,
args.limit,
args.on_date,
args.starred,
args.start_date,
args.strict, # -and
)
)
def _has_action_args(args: "Namespace") -> bool:
return any(
(
args.change_time,
args.delete,
args.edit,
)
)
def _has_display_args(args: "Namespace") -> bool:
return any(
(
args.tags,
args.short,
args.export, # --format
)
)
def _has_only_tags(tag_symbols: str, args_text: str) -> bool:
return all(word[0] in tag_symbols for word in " ".join(args_text).split())

View file

@ -1,25 +1,18 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import logging
import os
import subprocess
import sys
import tempfile
import textwrap
from pathlib import Path
from jrnl.exception import JrnlException
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
from jrnl.os_compat import on_windows
from jrnl.os_compat import split_args
from jrnl.output import print_msg
from jrnl.path import absolute_path
from jrnl.path import get_templates_path
from .color import ERROR_COLOR
from .color import RESET_COLOR
from .os_compat import on_windows
from .os_compat import split_args
def get_text_from_editor(config: dict, template: str = "") -> str:
def get_text_from_editor(config, template=""):
suffix = ".jrnl"
if config["template"]:
template_filename = Path(config["template"]).name
@ -33,89 +26,37 @@ def get_text_from_editor(config: dict, template: str = "") -> str:
try:
subprocess.call(split_args(config["editor"]) + [tmpfile])
except FileNotFoundError:
raise JrnlException(
Message(
MsgText.EditorMisconfigured,
MsgStyle.ERROR,
{"editor_key": config["editor"]},
)
)
except FileNotFoundError as e:
error_msg = f"""
{ERROR_COLOR}{str(e)}{RESET_COLOR}
Please check the 'editor' key in your config file for errors:
{repr(config['editor'])}
"""
print(textwrap.dedent(error_msg).strip(), file=sys.stderr)
exit(1)
with open(tmpfile, "r", encoding="utf-8") as f:
raw = f.read()
os.remove(tmpfile)
if not raw:
raise JrnlException(Message(MsgText.NoTextReceived, MsgStyle.NORMAL))
print("[Nothing saved to file]", file=sys.stderr)
return raw
def get_text_from_stdin() -> str:
print_msg(
Message(
MsgText.WritingEntryStart,
MsgStyle.TITLE,
{
"how_to_quit": (
MsgText.HowToQuitWindows if on_windows() else MsgText.HowToQuitLinux
)
},
)
def get_text_from_stdin():
_how_to_quit = "Ctrl+z and then Enter" if on_windows() else "Ctrl+d"
print(
f"[Writing Entry; on a blank line, press {_how_to_quit} to finish writing]\n",
file=sys.stderr,
)
try:
raw = sys.stdin.read()
except KeyboardInterrupt:
logging.error("Append mode: keyboard interrupt")
raise JrnlException(
Message(MsgText.KeyboardInterruptMsg, MsgStyle.ERROR_ON_NEW_LINE),
Message(MsgText.JournalNotSaved, MsgStyle.WARNING),
)
logging.error("Write mode: keyboard interrupt")
print("[Entry NOT saved to journal]", file=sys.stderr)
sys.exit(0)
return raw
def get_template_path(template_path: str, jrnl_template_dir: str) -> str:
actual_template_path = os.path.join(jrnl_template_dir, template_path)
if not os.path.exists(actual_template_path):
logging.debug(
f"Couldn't open {actual_template_path}. "
"Treating template path like a local / abs path."
)
actual_template_path = absolute_path(template_path)
return actual_template_path
def read_template_file(template_path: str) -> str:
"""
Reads the template file given a template path in this order:
* Check $XDG_DATA_HOME/jrnl/templates/template_path.
* Check template_arg as an absolute / relative path.
If a file is found, its contents are returned as a string.
If not, a JrnlException is raised.
"""
jrnl_template_dir = get_templates_path()
actual_template_path = get_template_path(template_path, jrnl_template_dir)
try:
with open(actual_template_path, encoding="utf-8") as f:
template_data = f.read()
return template_data
except FileNotFoundError:
raise JrnlException(
Message(
MsgText.CantReadTemplate,
MsgStyle.ERROR,
{
"template_path": template_path,
"actual_template_path": actual_template_path,
"jrnl_template_dir": str(jrnl_template_dir) + os.sep,
},
)
)

View file

@ -1,53 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import logging
from abc import ABC
from abc import abstractmethod
from jrnl.exception import JrnlException
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
class BaseEncryption(ABC):
def __init__(self, journal_name: str, config: dict):
logging.debug("start")
self._encoding: str = "utf-8"
self._journal_name: str = journal_name
self._config: dict = config
def clear(self) -> None:
pass
def encrypt(self, text: str) -> bytes:
logging.debug("encrypting")
return self._encrypt(text)
def decrypt(self, text: bytes) -> str:
logging.debug("decrypting")
if (result := self._decrypt(text)) is None:
raise JrnlException(
Message(MsgText.DecryptionFailedGeneric, MsgStyle.ERROR)
)
return result
@abstractmethod
def _encrypt(self, text: str) -> bytes:
"""
This is needed because self.decrypt might need
to perform actions (e.g. prompt for password)
before actually encrypting.
"""
pass
@abstractmethod
def _decrypt(self, text: bytes) -> str | None:
"""
This is needed because self.decrypt might need
to perform actions (e.g. prompt for password)
before actually decrypting.
"""
pass

View file

@ -1,8 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
from .BaseEncryption import BaseEncryption
class BaseKeyEncryption(BaseEncryption):
pass

View file

@ -1,82 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import logging
from jrnl.encryption.BaseEncryption import BaseEncryption
from jrnl.exception import JrnlException
from jrnl.keyring import get_keyring_password
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
from jrnl.prompt import create_password
from jrnl.prompt import prompt_password
class BasePasswordEncryption(BaseEncryption):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
logging.debug("start")
self._attempts: int = 0
self._max_attempts: int = 3
self._password: str = ""
self._check_keyring: bool = True
@property
def check_keyring(self) -> bool:
return self._check_keyring
@check_keyring.setter
def check_keyring(self, value: bool) -> None:
self._check_keyring = value
@property
def password(self) -> str | None:
return self._password
@password.setter
def password(self, value: str) -> None:
self._password = value
def clear(self):
self.password = None
self.check_keyring = False
def encrypt(self, text: str) -> bytes:
logging.debug("encrypting")
if not self.password:
if self.check_keyring and (
keyring_pw := get_keyring_password(self._journal_name)
):
self.password = keyring_pw
if not self.password:
self.password = create_password(self._journal_name)
return self._encrypt(text)
def decrypt(self, text: bytes) -> str:
logging.debug("decrypting")
if not self.password:
if self.check_keyring and (
keyring_pw := get_keyring_password(self._journal_name)
):
self.password = keyring_pw
if not self.password:
self._prompt_password()
while (result := self._decrypt(text)) is None:
self._prompt_password()
return result
def _prompt_password(self) -> None:
if self._attempts >= self._max_attempts:
raise JrnlException(
Message(MsgText.PasswordMaxTriesExceeded, MsgStyle.ERROR)
)
first_try = self._attempts == 0
self.password = prompt_password(first_try=first_try)
self._attempts += 1

View file

@ -1,42 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import hashlib
import logging
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers import algorithms
from cryptography.hazmat.primitives.ciphers import modes
from jrnl.encryption.BasePasswordEncryption import BasePasswordEncryption
class Jrnlv1Encryption(BasePasswordEncryption):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
logging.debug("start")
def _encrypt(self, _: str) -> bytes:
raise NotImplementedError
def _decrypt(self, text: bytes) -> str | None:
logging.debug("decrypting")
iv, cipher = text[:16], text[16:]
password = self._password or ""
decryption_key = hashlib.sha256(password.encode(self._encoding)).digest()
decryptor = Cipher(
algorithms.AES(decryption_key), modes.CBC(iv), default_backend()
).decryptor()
try:
plain_padded = decryptor.update(cipher) + decryptor.finalize()
if plain_padded[-1] in (" ", 32):
# Ancient versions of jrnl. Do not judge me.
return plain_padded.decode(self._encoding).rstrip(" ")
else:
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
plain = unpadder.update(plain_padded) + unpadder.finalize()
return plain.decode(self._encoding)
except ValueError:
return None

View file

@ -1,59 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import base64
import logging
from cryptography.fernet import Fernet
from cryptography.fernet import InvalidToken
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from .BasePasswordEncryption import BasePasswordEncryption
class Jrnlv2Encryption(BasePasswordEncryption):
def __init__(self, *args, **kwargs) -> None:
# Salt is hard-coded
self._salt: bytes = b"\xf2\xd5q\x0e\xc1\x8d.\xde\xdc\x8e6t\x89\x04\xce\xf8"
self._key: bytes = b""
super().__init__(*args, **kwargs)
logging.debug("start")
@property
def password(self):
return self._password
@password.setter
def password(self, value: str | None):
self._password = value
self._make_key()
def _make_key(self) -> None:
if self._password is None:
# Password was removed after being set
self._key = None
return
password = self.password.encode(self._encoding)
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=self._salt,
iterations=100_000,
backend=default_backend(),
)
key = kdf.derive(password)
self._key = base64.urlsafe_b64encode(key)
def _encrypt(self, text: str) -> bytes:
logging.debug("encrypting")
return Fernet(self._key).encrypt(text.encode(self._encoding))
def _decrypt(self, text: bytes) -> str | None:
logging.debug("decrypting")
try:
return Fernet(self._key).decrypt(text).decode(self._encoding)
except (InvalidToken, IndexError):
return None

View file

@ -1,20 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import logging
from jrnl.encryption.BaseEncryption import BaseEncryption
class NoEncryption(BaseEncryption):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
logging.debug("start")
def _encrypt(self, text: str) -> bytes:
logging.debug("encrypting")
return text.encode(self._encoding)
def _decrypt(self, text: bytes) -> str:
logging.debug("decrypting")
return text.decode(self._encoding)

View file

@ -1,36 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
from enum import Enum
from importlib import import_module
from typing import TYPE_CHECKING
from typing import Type
if TYPE_CHECKING:
from .BaseEncryption import BaseEncryption
class EncryptionMethods(str, Enum):
def __str__(self) -> str:
return self.value
NONE = "NoEncryption"
JRNLV1 = "Jrnlv1Encryption"
JRNLV2 = "Jrnlv2Encryption"
def determine_encryption_method(config: str | bool) -> Type["BaseEncryption"]:
ENCRYPTION_METHODS = {
True: EncryptionMethods.JRNLV2, # the default
False: EncryptionMethods.NONE,
"jrnlv1": EncryptionMethods.JRNLV1,
"jrnlv2": EncryptionMethods.JRNLV2,
}
key = config
if isinstance(config, str):
key = config.lower()
my_class = ENCRYPTION_METHODS[key]
return getattr(import_module(f"jrnl.encryption.{my_class}"), my_class)

View file

@ -1,24 +1,52 @@
# Copyright © 2012-2023 jrnl contributors
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
from typing import TYPE_CHECKING
from jrnl.output import print_msg
if TYPE_CHECKING:
from jrnl.messages import Message
from jrnl.messages import MsgText
import textwrap
class JrnlException(Exception):
class UserAbort(Exception):
pass
class UpgradeValidationException(Exception):
"""Raised when the contents of an upgraded journal do not match the old journal"""
pass
class JrnlError(Exception):
"""Common exceptions raised by jrnl."""
def __init__(self, *messages: "Message"):
self.messages = messages
def __init__(self, error_type, **kwargs):
self.error_type = error_type
self.message = self._get_error_message(**kwargs)
def print(self) -> None:
for msg in self.messages:
print_msg(msg)
def _get_error_message(self, **kwargs):
error_messages = {
"ConfigDirectoryIsFile": """
The path to your jrnl configuration directory is a file, not a directory:
def has_message_text(self, message_text: "MsgText"):
return any([m.text == message_text for m in self.messages])
{config_directory_path}
Removing this file will allow jrnl to save its configuration.
""",
"LineWrapTooSmallForDateFormat": """
The provided linewrap value of {config_linewrap} is too small by
{columns} columns to display the timestamps in the configured time
format for journal {journal}.
You can avoid this error by specifying a linewrap value that is larger
by at least {columns} in the configuration file or by using
--config-override at the command line
""",
"CannotEncryptJournalType": """
The journal {journal_name} can't be encrypted because it is a
{journal_type} journal.
To encrypt it, create a new journal referencing a file, export
this journal to the new journal, then encrypt the new journal.
""",
}
msg = error_messages[self.error_type].format(**kwargs)
msg = textwrap.dedent(msg)
return msg

View file

@ -1,83 +1,63 @@
# Copyright © 2012-2023 jrnl contributors
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import contextlib
import glob
import logging
import os
import sys
from rich.pretty import pretty_repr
from jrnl import __version__
from jrnl.config import DEFAULT_JOURNAL_KEY
from jrnl.config import get_config_path
from jrnl.config import get_default_colors
from jrnl.config import get_default_config
from jrnl.config import get_default_journal_path
from jrnl.config import load_config
from jrnl.config import save_config
from jrnl.config import verify_config_colors
from jrnl.exception import JrnlException
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
from jrnl.output import print_msg
from jrnl.path import absolute_path
from jrnl.path import expand_path
from jrnl.path import home_dir
from jrnl.prompt import yesno
from jrnl.upgrade import is_old_version
from .config import DEFAULT_JOURNAL_KEY
from .config import get_config_path
from .config import get_default_config
from .config import get_default_journal_path
from .config import load_config
from .config import save_config
from .config import verify_config_colors
from .exception import UserAbort
from .prompt import yesno
from .upgrade import is_old_version
def upgrade_config(config_data: dict, alt_config_path: str | None = None) -> None:
"""Checks if there are keys missing in a given config dict, and if so, updates the
config file accordingly. This essentially automatically ports jrnl installations
if new config parameters are introduced in later versions. Also checks for
existence of and difference in version number between config dict
and current jrnl version, and if so, update the config file accordingly.
def upgrade_config(config_data, alt_config_path=None):
"""Checks if there are keys missing in a given config dict, and if so, updates the config file accordingly.
This essentially automatically ports jrnl installations if new config parameters are introduced in later
versions.
Supply alt_config_path if using an alternate config through --config-file."""
default_config = get_default_config()
missing_keys = set(default_config).difference(config_data)
if missing_keys:
for key in missing_keys:
config_data[key] = default_config[key]
different_version = config_data["version"] != __version__
if different_version:
config_data["version"] = __version__
if missing_keys or different_version:
save_config(config_data, alt_config_path)
config_path = alt_config_path if alt_config_path else get_config_path()
print_msg(
Message(
MsgText.ConfigUpdated, MsgStyle.NORMAL, {"config_path": config_path}
)
print(
f"[Configuration updated to newest version at {config_path}]",
file=sys.stderr,
)
def find_default_config() -> str:
def find_default_config():
config_path = (
get_config_path()
if os.path.exists(get_config_path())
else os.path.join(home_dir(), ".jrnl_config")
else os.path.join(os.path.expanduser("~"), ".jrnl_config")
)
return config_path
def find_alt_config(alt_config: str) -> str:
if not os.path.exists(alt_config):
raise JrnlException(
Message(
MsgText.AltConfigNotFound, MsgStyle.ERROR, {"config_file": alt_config}
)
def find_alt_config(alt_config):
if os.path.exists(alt_config):
return alt_config
else:
print(
"Alternate configuration file not found at path specified.", file=sys.stderr
)
return alt_config
print("Exiting.", file=sys.stderr)
sys.exit(1)
def load_or_install_jrnl(alt_config_path: str) -> dict:
def load_or_install_jrnl(alt_config_path):
"""
If jrnl is already installed, loads and returns a default config object.
If alternate config is specified via --config-file flag, it will be used.
@ -91,83 +71,72 @@ def load_or_install_jrnl(alt_config_path: str) -> dict:
logging.debug("Reading configuration from file %s", config_path)
config = load_config(config_path)
if config is None:
raise JrnlException(
Message(
MsgText.CantParseConfigFile,
MsgStyle.ERROR,
{
"config_path": config_path,
},
)
)
if is_old_version(config_path):
from jrnl import upgrade
from . import upgrade
upgrade.upgrade_jrnl(config_path)
try:
upgrade.upgrade_jrnl(config_path)
except upgrade.UpgradeValidationException:
print("Aborting upgrade.", file=sys.stderr)
print(
"Please tell us about this problem at the following URL:",
file=sys.stderr,
)
print(
"https://github.com/jrnl-org/jrnl/issues/new?title=UpgradeValidationException",
file=sys.stderr,
)
print("Exiting.", file=sys.stderr)
sys.exit(1)
upgrade_config(config, alt_config_path)
verify_config_colors(config)
else:
logging.debug("Configuration file not found, installing jrnl...")
config = install()
try:
config = install()
except KeyboardInterrupt:
raise UserAbort("Installation aborted")
logging.debug('Using configuration:\n"%s"', pretty_repr(config))
logging.debug('Using configuration "%s"', config)
return config
def install() -> dict:
def install():
_initialize_autocomplete()
# Where to create the journal?
default_journal_path = get_default_journal_path()
user_given_path = print_msg(
Message(
MsgText.InstallJournalPathQuestion,
MsgStyle.PROMPT,
params={
"default_journal_path": default_journal_path,
},
),
get_input=True,
)
journal_path = absolute_path(user_given_path or default_journal_path)
path_query = f"Path to your journal file (leave blank for {default_journal_path}): "
journal_path = os.path.abspath(input(path_query).strip() or default_journal_path)
default_config = get_default_config()
default_config["journals"][DEFAULT_JOURNAL_KEY]["journal"] = journal_path
default_config["journals"][DEFAULT_JOURNAL_KEY] = os.path.expanduser(
os.path.expandvars(journal_path)
)
# If the folder doesn't exist, create it
path = os.path.split(journal_path)[0]
with contextlib.suppress(OSError):
path = os.path.split(default_config["journals"][DEFAULT_JOURNAL_KEY])[0]
try:
os.makedirs(path)
except OSError:
pass
# Encrypt it?
encrypt = yesno(Message(MsgText.EncryptJournalQuestion), default=False)
encrypt = yesno(
"Do you want to encrypt your journal? You can always change this later",
default=False,
)
if encrypt:
default_config["encrypt"] = True
print_msg(Message(MsgText.JournalEncrypted, MsgStyle.NORMAL))
# Use colors?
use_colors = yesno(Message(MsgText.UseColorsQuestion), default=True)
if use_colors:
default_config["colors"] = get_default_colors()
print("Journal will be encrypted.", file=sys.stderr)
save_config(default_config)
print_msg(
Message(
MsgText.InstallComplete,
MsgStyle.NORMAL,
params={"config_path": get_config_path()},
)
)
return default_config
def _initialize_autocomplete() -> None:
# readline is not included in Windows Active Python and perhaps some other distss
def _initialize_autocomplete():
# readline is not included in Windows Active Python and perhaps some other distributions
if sys.modules.get("readline"):
import readline
@ -176,8 +145,8 @@ def _initialize_autocomplete() -> None:
readline.set_completer(_autocomplete_path)
def _autocomplete_path(text: str, state: int) -> list[str | None]:
expansions = glob.glob(expand_path(text) + "*")
def _autocomplete_path(text, state):
expansions = glob.glob(os.path.expanduser(os.path.expandvars(text)) + "*")
expansions = [e + "/" if os.path.isdir(e) else e for e in expansions]
expansions.append(None)
return expansions[state]

View file

@ -1,158 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import codecs
import os
import pathlib
from typing import TYPE_CHECKING
from jrnl import time
from .Journal import Journal
if TYPE_CHECKING:
from jrnl.journals import Entry
# glob search patterns for folder/file structure
DIGIT_PATTERN = "[0123456789]"
YEAR_PATTERN = DIGIT_PATTERN * 4
MONTH_PATTERN = "[01]" + DIGIT_PATTERN
DAY_PATTERN = "[0123]" + DIGIT_PATTERN + ".txt"
class Folder(Journal):
"""A Journal handling multiple files in a folder"""
def __init__(self, name: str = "default", **kwargs):
self.entries = []
self._diff_entry_dates = []
self.can_be_encrypted = False
super().__init__(name, **kwargs)
def open(self) -> "Folder":
filenames = []
self.entries = []
if os.path.exists(self.config["journal"]):
filenames = Folder._get_files(self.config["journal"])
for filename in filenames:
with codecs.open(filename, "r", "utf-8") as f:
journal = f.read()
self.entries.extend(self._parse(journal))
self.sort()
return self
def write(self) -> None:
"""Writes only the entries that have been modified into proper files."""
# Create a list of dates of modified entries. Start with diff_entry_dates
modified_dates = self._diff_entry_dates
seen_dates = set(self._diff_entry_dates)
for e in self.entries:
if e.modified:
if e.date not in modified_dates:
modified_dates.append(e.date)
if e.date not in seen_dates:
seen_dates.add(e.date)
# For every date that had a modified entry, write to a file
for d in modified_dates:
write_entries = []
filename = os.path.join(
self.config["journal"],
d.strftime("%Y"),
d.strftime("%m"),
d.strftime("%d") + ".txt",
)
dirname = os.path.dirname(filename)
# create directory if it doesn't exist
if not os.path.exists(dirname):
os.makedirs(dirname)
for e in self.entries:
if (
e.date.year == d.year
and e.date.month == d.month
and e.date.day == d.day
):
write_entries.append(e)
journal = "\n".join([e.__str__() for e in write_entries])
with codecs.open(filename, "w", "utf-8") as journal_file:
journal_file.write(journal)
# look for and delete empty files
filenames = []
filenames = Folder._get_files(self.config["journal"])
for filename in filenames:
if os.stat(filename).st_size <= 0:
os.remove(filename)
def delete_entries(self, entries_to_delete: list["Entry"]) -> None:
"""Deletes specific entries from a journal."""
for entry in entries_to_delete:
self.entries.remove(entry)
self._diff_entry_dates.append(entry.date)
self.deleted_entry_count += 1
def change_date_entries(self, date: str, entries_to_change: list["Entry"]) -> None:
"""Changes entry dates to given date."""
date = time.parse(date)
self._diff_entry_dates.append(date)
for entry in entries_to_change:
self._diff_entry_dates.append(entry.date)
entry.date = date
entry.modified = True
def parse_editable_str(self, edited: str) -> None:
"""Parses the output of self.editable_str and updates its entries."""
mod_entries = self._parse(edited)
diff_entries = set(self.entries) - set(mod_entries)
for e in diff_entries:
self._diff_entry_dates.append(e.date)
# Match those entries that can be found in self.entries and set
# these to modified, so we can get a count of how many entries got
# modified and how many got deleted later.
for entry in mod_entries:
entry.modified = not any(entry == old_entry for old_entry in self.entries)
self.increment_change_counts_by_edit(mod_entries)
self.entries = mod_entries
@staticmethod
def _get_files(journal_path: str) -> list[str]:
"""Searches through sub directories starting with journal_path and find all text
files that look like entries"""
for year_folder in Folder._get_year_folders(pathlib.Path(journal_path)):
for month_folder in Folder._get_month_folders(year_folder):
yield from Folder._get_day_files(month_folder)
@staticmethod
def _get_year_folders(path: pathlib.Path) -> list[pathlib.Path]:
for child in path.glob(YEAR_PATTERN):
if child.is_dir():
yield child
return
@staticmethod
def _get_month_folders(path: pathlib.Path) -> list[pathlib.Path]:
for child in path.glob(MONTH_PATTERN):
if int(child.name) > 0 and int(child.name) <= 12 and path.is_dir():
yield child
return
@staticmethod
def _get_day_files(path: pathlib.Path) -> list[str]:
for child in path.glob(DAY_PATTERN):
if (
int(child.stem) > 0
and int(child.stem) <= 31
and time.is_valid_date(
year=int(path.parent.name),
month=int(path.name),
day=int(child.stem),
)
and child.is_file()
):
yield str(child)

View file

@ -1,5 +0,0 @@
from .DayOneJournal import DayOne
from .Entry import Entry
from .FolderJournal import Folder
from .Journal import Journal
from .Journal import open_journal

345
jrnl/jrnl.py Normal file
View file

@ -0,0 +1,345 @@
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import logging
import sys
from . import install
from . import plugins
from .Journal import open_journal
from .color import ERROR_COLOR
from .color import RESET_COLOR
from .config import get_journal_name
from .config import scope_config
from .config import get_config_path
from .editor import get_text_from_editor
from .editor import get_text_from_stdin
from .exception import UserAbort
from . import time
from .override import apply_overrides
def run(args):
"""
Flow:
1. Run standalone command if it doesn't require config (help, version, etc), then exit
2. Load config
3. Run standalone command if it does require config (encrypt, decrypt, etc), then exit
4. Load specified journal
5. Start write mode, or search mode
6. Profit
"""
# Run command if possible before config is available
if callable(args.preconfig_cmd):
return args.preconfig_cmd(args)
# Load the config, and extract journal name
try:
config = install.load_or_install_jrnl(args.config_file_path)
original_config = config.copy()
# Apply config overrides
config = apply_overrides(args, config)
args = get_journal_name(args, config)
config = scope_config(config, args.journal_name)
except UserAbort as err:
print(f"\n{err}", file=sys.stderr)
sys.exit(1)
# Run post-config command now that config is ready
if callable(args.postconfig_cmd):
return args.postconfig_cmd(
args=args, config=config, original_config=original_config
)
# --- All the standalone commands are now done --- #
# Get the journal we're going to be working with
journal = open_journal(args.journal_name, config)
kwargs = {
"args": args,
"config": config,
"journal": journal,
}
if _is_write_mode(**kwargs):
write_mode(**kwargs)
else:
search_mode(**kwargs)
def _is_write_mode(args, config, **kwargs):
"""Determines if we are in write mode (as opposed to search mode)"""
write_mode = True
# Are any search filters present? If so, then search mode.
write_mode = not any(
(
args.contains,
args.delete,
args.edit,
args.export,
args.end_date,
args.today_in_history,
args.month,
args.day,
args.year,
args.limit,
args.on_date,
args.short,
args.starred,
args.start_date,
args.strict,
args.tags,
)
)
# Might be writing and want to move to editor part of the way through
if args.edit and args.text:
write_mode = True
# If the text is entirely tags, then we are also searching (not writing)
if (
write_mode
and args.text
and all(word[0] in config["tagsymbols"] for word in " ".join(args.text).split())
):
write_mode = False
return write_mode
def write_mode(args, config, journal, **kwargs):
"""
Gets input from the user to write to the journal
1. Check for input from cli
2. Check input being piped in
3. Open editor if configured (prepopulated with template if available)
4. Use stdin.read as last resort
6. Write any found text to journal, or exit
"""
logging.debug("Write mode: starting")
if args.text:
logging.debug("Write mode: cli text detected: %s", args.text)
raw = " ".join(args.text).strip()
if args.edit:
raw = _write_in_editor(config, raw)
elif not sys.stdin.isatty():
logging.debug("Write mode: receiving piped text")
raw = sys.stdin.read()
else:
raw = _write_in_editor(config)
if not raw:
logging.error("Write mode: couldn't get raw text")
sys.exit()
logging.debug(
'Write mode: appending raw text to journal "%s": %s', args.journal_name, raw
)
journal.new_entry(raw)
print(f"[Entry added to {args.journal_name} journal]", file=sys.stderr)
journal.write()
logging.debug("Write mode: completed journal.write()", args.journal_name, raw)
def search_mode(args, journal, **kwargs):
"""
Search for entries in a journal, then either:
1. Send them to configured editor for user manipulation
2. Delete them (with confirmation for each entry)
3. Display them (with formatting options)
"""
kwargs = {
**kwargs,
"args": args,
"journal": journal,
"old_entries": journal.entries,
}
# Filters the journal entries in place
_search_journal(**kwargs)
# Where do the search results go?
if args.edit:
_edit_search_results(**kwargs)
elif args.delete:
_delete_search_results(**kwargs)
else:
_display_search_results(**kwargs)
def _write_in_editor(config, template=None):
if config["editor"]:
logging.debug("Write mode: opening editor")
if not template:
template = _get_editor_template(config)
raw = get_text_from_editor(config, template)
else:
raw = get_text_from_stdin()
return raw
def _get_editor_template(config, **kwargs):
logging.debug("Write mode: loading template for entry")
if not config["template"]:
logging.debug("Write mode: no template configured")
return ""
try:
template = open(config["template"]).read()
logging.debug("Write mode: template loaded: %s", template)
except OSError:
logging.error("Write mode: template not loaded")
print(
f"[Could not read template at '{config['template']}']",
file=sys.stderr,
)
sys.exit(1)
return template
def _search_journal(args, journal, **kwargs):
"""Search the journal with the given args"""
if args.on_date:
args.start_date = args.end_date = args.on_date
if args.today_in_history:
now = time.parse("now")
args.day = now.day
args.month = now.month
journal.filter(
tags=args.text,
month=args.month,
day=args.day,
year=args.year,
start_date=args.start_date,
end_date=args.end_date,
strict=args.strict,
starred=args.starred,
exclude=args.excluded,
contains=args.contains,
)
journal.limit(args.limit)
def _edit_search_results(config, journal, old_entries, **kwargs):
"""
1. Send the given journal entries to the user-configured editor
2. Print out stats on any modifications to journal
3. Write modifications to journal
"""
if not config["editor"]:
print(
f"""
[{ERROR_COLOR}ERROR{RESET_COLOR}: There is no editor configured.]
Please specify an editor in config file ({get_config_path()})
to use the --edit option.
""",
file=sys.stderr,
)
sys.exit(1)
# separate entries we are not editing
other_entries = [e for e in old_entries if e not in journal.entries]
# Get stats now for summary later
old_stats = _get_predit_stats(journal)
# Send user to the editor
edited = get_text_from_editor(config, journal.editable_str())
journal.parse_editable_str(edited)
# Print summary if available
_print_edited_summary(journal, old_stats)
# Put back entries we separated earlier, sort, and write the journal
journal.entries += other_entries
journal.sort()
journal.write()
def _print_edited_summary(journal, old_stats, **kwargs):
stats = {
"added": len(journal) - old_stats["count"],
"deleted": old_stats["count"] - len(journal),
"modified": len([e for e in journal.entries if e.modified]),
}
prompts = []
if stats["added"] > 0:
prompts.append(f"{stats['added']} {_pluralize_entry(stats['added'])} added")
stats["modified"] -= stats["added"]
if stats["deleted"] > 0:
prompts.append(
f"{stats['deleted']} {_pluralize_entry(stats['deleted'])} deleted"
)
if stats["modified"]:
prompts.append(
f"{stats['modified']} {_pluralize_entry(stats['modified'])} modified"
)
if prompts:
print(f"[{', '.join(prompts).capitalize()}]", file=sys.stderr)
def _get_predit_stats(journal):
return {"count": len(journal)}
def _pluralize_entry(num):
return "entry" if num == 1 else "entries"
def _delete_search_results(journal, old_entries, **kwargs):
if not journal.entries:
print(
"[No entries deleted, because the search returned no results.]",
file=sys.stderr,
)
sys.exit(1)
entries_to_delete = journal.prompt_delete_entries()
if entries_to_delete:
journal.entries = old_entries
journal.delete_entries(entries_to_delete)
journal.write()
def _display_search_results(args, journal, **kwargs):
if args.short or args.export == "short":
print(journal.pprint(short=True))
elif args.export == "pretty":
print(journal.pprint())
elif args.tags:
print(plugins.get_exporter("tags").export(journal))
elif args.export:
exporter = plugins.get_exporter(args.export)
print(exporter.export(journal, args.filename))
elif kwargs["config"].get("display_format"):
exporter = plugins.get_exporter(kwargs["config"]["display_format"])
print(exporter.export(journal, args.filename))
else:
print(journal.pprint())

View file

@ -1,29 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import keyring
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
from jrnl.output import print_msg
def get_keyring_password(journal_name: str = "default") -> str | None:
try:
return keyring.get_password("jrnl", journal_name)
except keyring.errors.KeyringError as e:
if not isinstance(e, keyring.errors.NoKeyringError):
print_msg(Message(MsgText.KeyringRetrievalFailure, MsgStyle.ERROR))
return None
def set_keyring_password(password: str, journal_name: str = "default") -> None:
try:
return keyring.set_password("jrnl", journal_name, password)
except keyring.errors.KeyringError as e:
if isinstance(e, keyring.errors.NoKeyringError):
msg = Message(MsgText.KeyringBackendNotFound, MsgStyle.WARNING)
else:
msg = Message(MsgText.KeyringRetrievalFailure, MsgStyle.ERROR)
print_msg(msg)

View file

@ -1,88 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import logging
import sys
import traceback
from rich.logging import RichHandler
from jrnl import controller
from jrnl.args import parse_args
from jrnl.exception import JrnlException
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
from jrnl.output import print_msg
def configure_logger(debug: bool = False) -> None:
if not debug:
logging.disable()
return
logging.basicConfig(
level=logging.DEBUG,
datefmt="[%X]",
format="%(message)s",
handlers=[RichHandler()],
)
logging.getLogger("parsedatetime").setLevel(logging.INFO)
logging.getLogger("keyring.backend").setLevel(logging.ERROR)
logging.debug("Logging start")
def run(manual_args: list[str] | None = None) -> int:
try:
if manual_args is None:
manual_args = sys.argv[1:]
args = parse_args(manual_args)
configure_logger(args.debug)
logging.debug("Parsed args:\n%s", args)
status_code = controller.run(args)
except JrnlException as e:
status_code = 1
e.print()
except KeyboardInterrupt:
status_code = 1
print_msg(
Message(
MsgText.KeyboardInterruptMsg,
MsgStyle.ERROR_ON_NEW_LINE,
)
)
except Exception as e:
# uncaught exception
status_code = 1
debug = False
try:
if args.debug: # type: ignore
debug = True
except NameError:
# This should only happen when the exception
# happened before the args were parsed
if "--debug" in sys.argv:
debug = True
if debug:
from rich.console import Console
traceback.print_tb(sys.exc_info()[2])
Console(stderr=True).print_exception(extra_lines=1)
print_msg(
Message(
MsgText.UncaughtException,
MsgStyle.ERROR,
{"name": type(e).__name__, "exception": e},
)
)
# This should be the only exit point
return status_code

View file

@ -1,17 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
from typing import TYPE_CHECKING
from typing import Mapping
from typing import NamedTuple
from jrnl.messages.MsgStyle import MsgStyle
if TYPE_CHECKING:
from jrnl.messages.MsgText import MsgText
class Message(NamedTuple):
text: "MsgText"
style: MsgStyle = MsgStyle.NORMAL
params: Mapping = {}

View file

@ -1,93 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
from enum import Enum
from typing import Callable
from typing import NamedTuple
from rich import box
from rich.panel import Panel
from jrnl.messages.MsgText import MsgText
class MsgStyle(Enum):
class _Color(NamedTuple):
"""
String representing a standard color to display
see: https://rich.readthedocs.io/en/stable/appendix/colors.html
"""
color: str
class _Decoration(Enum):
NONE = {
"callback": lambda x, **_: x,
"args": {},
}
BOX = {
"callback": Panel,
"args": {
"expand": False,
"padding": (0, 2),
"title_align": "left",
"box": box.HEAVY,
},
}
@property
def callback(self) -> Callable:
return self.value["callback"]
@property
def args(self) -> dict:
return self.value["args"]
PROMPT = {
"decoration": _Decoration.NONE,
"color": _Color("white"),
"append_space": True,
}
TITLE = {
"decoration": _Decoration.BOX,
"color": _Color("cyan"),
}
NORMAL = {
"decoration": _Decoration.BOX,
"color": _Color("white"),
}
WARNING = {
"decoration": _Decoration.BOX,
"color": _Color("yellow"),
}
ERROR = {
"decoration": _Decoration.BOX,
"color": _Color("red"),
"box_title": str(MsgText.Error),
}
ERROR_ON_NEW_LINE = {
"decoration": _Decoration.BOX,
"color": _Color("red"),
"prepend_newline": True,
"box_title": str(MsgText.Error),
}
@property
def decoration(self) -> _Decoration:
return self.value["decoration"]
@property
def color(self) -> _Color:
return self.value["color"].color
@property
def prepend_newline(self) -> bool:
return self.value.get("prepend_newline", False)
@property
def append_space(self) -> bool:
return self.value.get("append_space", False)
@property
def box_title(self) -> MsgText:
return self.value.get("box_title")

View file

@ -1,291 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
from enum import Enum
class MsgText(Enum):
def __str__(self) -> str:
return self.value
# -- Welcome --- #
WelcomeToJrnl = """
Welcome to jrnl {version}!
It looks like you've been using an older version of jrnl until now. That's
okay - jrnl will now upgrade your configuration and journal files. Afterwards
you can enjoy all of the great new features that come with jrnl 2:
- Support for storing your journal in multiple files
- Faster reading and writing for large journals
- New encryption back-end that makes installing jrnl much easier
- Tons of bug fixes
Please note that jrnl 1.x is NOT forward compatible with this version of jrnl.
If you choose to proceed, you will not be able to use your journals with
older versions of jrnl anymore.
"""
AllDoneUpgrade = "We're all done here and you can start enjoying jrnl 2"
InstallComplete = """
jrnl configuration created at {config_path}
For advanced features, read the docs at https://jrnl.sh
"""
# --- Prompts --- #
InstallJournalPathQuestion = """
Path to your journal file (leave blank for {default_journal_path}):
"""
DeleteEntryQuestion = "Delete entry '{entry_title}'?"
ChangeTimeEntryQuestion = "Change time for '{entry_title}'?"
EncryptJournalQuestion = """
Do you want to encrypt your journal? (You can always change this later)
"""
UseColorsQuestion = """
Do you want jrnl to use colors to display entries? (You can always change this later)
""" # noqa: E501 - the line is still under 88 when dedented
YesOrNoPromptDefaultYes = "[Y/n]"
YesOrNoPromptDefaultNo = "[y/N]"
ContinueUpgrade = "Continue upgrading jrnl?"
# these should be lowercase, if possible in language
# "lowercase" means whatever `.lower()` returns
OneCharacterYes = "y"
OneCharacterNo = "n"
# --- Exceptions ---#
Error = "Error"
UncaughtException = """
{name}
{exception}
This is probably a bug. Please file an issue at:
https://github.com/jrnl-org/jrnl/issues/new/choose
"""
ConfigDirectoryIsFile = """
Problem with config file!
The path to your jrnl configuration directory is a file, not a directory:
{config_directory_path}
Removing this file will allow jrnl to save its configuration.
"""
CantParseConfigFile = """
Unable to parse config file at:
{config_path}
"""
LineWrapTooSmallForDateFormat = """
The provided linewrap value of {config_linewrap} is too small by
{columns} columns to display the timestamps in the configured time
format for journal {journal}.
You can avoid this error by specifying a linewrap value that is larger
by at least {columns} in the configuration file or by using
--config-override at the command line
"""
CannotEncryptJournalType = """
The journal {journal_name} can't be encrypted because it is a
{journal_type} journal.
To encrypt it, create a new journal referencing a file, export
this journal to the new journal, then encrypt the new journal.
"""
ConfigEncryptedForUnencryptableJournalType = """
The config for journal "{journal_name}" has 'encrypt' set to true, but this type
of journal can't be encrypted. Please fix your config file.
"""
DecryptionFailedGeneric = "The decryption of journal data failed."
KeyboardInterruptMsg = "Aborted by user"
CantReadTemplate = """
Unable to find a template file {template_path}.
The following paths were checked:
* {jrnl_template_dir}{template_path}
* {actual_template_path}
"""
NoNamedJournal = "No '{journal_name}' journal configured\n{journals}"
DoesNotExist = "{name} does not exist"
# --- Journal status ---#
JournalNotSaved = "Entry NOT saved to journal"
JournalEntryAdded = "Entry added to {journal_name} journal"
JournalCountAddedSingular = "{num} entry added"
JournalCountModifiedSingular = "{num} entry modified"
JournalCountDeletedSingular = "{num} entry deleted"
JournalCountAddedPlural = "{num} entries added"
JournalCountModifiedPlural = "{num} entries modified"
JournalCountDeletedPlural = "{num} entries deleted"
JournalCreated = "Journal '{journal_name}' created at {filename}"
DirectoryCreated = "Directory {directory_name} created"
JournalEncrypted = "Journal will be encrypted"
JournalEncryptedTo = "Journal encrypted to {path}"
JournalDecryptedTo = "Journal decrypted to {path}"
BackupCreated = "Created a backup at {filename}"
# --- Editor ---#
WritingEntryStart = """
Writing Entry
To finish writing, press {how_to_quit} on a blank line.
"""
HowToQuitWindows = "Ctrl+z and then Enter"
HowToQuitLinux = "Ctrl+d"
EditorMisconfigured = """
No such file or directory: '{editor_key}'
Please check the 'editor' key in your config file for errors:
editor: '{editor_key}'
"""
EditorNotConfigured = """
There is no editor configured
To use the --edit option, please specify an editor your config file:
{config_file}
For examples of how to configure an external editor, see:
https://jrnl.sh/en/stable/external-editors/
"""
NoEditsReceivedJournalNotDeleted = """
No text received from editor. Were you trying to delete all the entries?
This seems a bit drastic, so the operation was cancelled.
To delete all entries, use the --delete option.
"""
NoEditsReceived = "No edits to save, because nothing was changed"
NoTextReceived = """
No entry to save, because no text was received
"""
NoChangesToTemplate = """
No entry to save, because the template was not changed
"""
# --- Upgrade --- #
JournalFailedUpgrade = """
The following journal{s} failed to upgrade:
{failed_journals}
Please tell us about this problem at the following URL:
https://github.com/jrnl-org/jrnl/issues/new?title=JournalFailedUpgrade
"""
UpgradeAborted = "jrnl was NOT upgraded"
AbortingUpgrade = "Aborting upgrade..."
ImportAborted = "Entries were NOT imported"
JournalsToUpgrade = """
The following journals will be upgraded to jrnl {version}:
"""
JournalsToIgnore = """
The following journals will not be touched:
"""
UpgradingJournal = """
Upgrading '{journal_name}' journal stored in {path}...
"""
UpgradingConfig = "Upgrading config..."
PaddedJournalName = "{journal_name:{pad}} -> {path}"
# -- Config --- #
AltConfigNotFound = """
Alternate configuration file not found at the given path:
{config_file}
"""
ConfigUpdated = """
Configuration updated to newest version at {config_path}
"""
ConfigDoubleKeys = """
There is at least one duplicate key in your configuration file.
Details:
{error_message}
"""
# --- Password --- #
Password = "Password:"
PasswordFirstEntry = "Enter password for journal '{journal_name}': "
PasswordConfirmEntry = "Enter password again: "
PasswordMaxTriesExceeded = "Too many attempts with wrong password"
PasswordCanNotBeEmpty = "Password can't be empty!"
PasswordDidNotMatch = "Passwords did not match, please try again"
WrongPasswordTryAgain = "Wrong password, try again"
PasswordStoreInKeychain = "Do you want to store the password in your keychain?"
# --- Search --- #
NothingToDelete = """
No entries to delete, because the search returned no results
"""
NothingToModify = """
No entries to modify, because the search returned no results
"""
NoEntriesFound = "no entries found"
EntryFoundCountSingular = "{num} entry found"
EntryFoundCountPlural = "{num} entries found"
# --- Formats --- #
HeadingsPastH6 = """
Headings increased past H6 on export - {date} {title}
"""
YamlMustBeDirectory = """
YAML export must be to a directory, not a single file
"""
JournalExportedTo = "Journal exported to {path}"
# --- Import --- #
ImportSummary = """
{count} imported to {journal_name} journal
"""
ImporterNotFound = """
No importer found for file type '{format}'.
'{format}' is likely to be an export-only format.
"""
# --- Color --- #
InvalidColor = "{key} set to invalid color: {color}"
# --- Keyring --- #
KeyringBackendNotFound = """
Keyring backend not found.
Please install one of the supported backends by visiting:
https://pypi.org/project/keyring/
"""
KeyringRetrievalFailure = "Failed to retrieve keyring"
# --- Deprecation --- #
DeprecatedCommand = """
The command {old_cmd} is deprecated and will be removed from jrnl soon.
Please use {new_cmd} instead.
"""

View file

@ -1,10 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
Message = Message.Message
MsgStyle = MsgStyle.MsgStyle
MsgText = MsgText.MsgText

View file

@ -1,18 +1,18 @@
# Copyright © 2012-2023 jrnl contributors
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import shlex
from sys import platform
def on_windows() -> bool:
def on_windows():
return "win32" in platform
def on_posix() -> bool:
def on_posix():
return not on_windows()
def split_args(args: str) -> list[str]:
def split_args(args):
"""Split arguments and add escape characters as appropriate for the OS"""
return shlex.split(args, posix=on_posix())

View file

@ -1,142 +1,36 @@
# Copyright © 2012-2023 jrnl contributors
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import textwrap
from typing import Callable
from rich.console import Console
from rich.text import Text
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
import logging
def deprecated_cmd(
old_cmd: str, new_cmd: str, callback: Callable | None = None, **kwargs
) -> None:
print_msg(
Message(
MsgText.DeprecatedCommand,
MsgStyle.WARNING,
{"old_cmd": old_cmd, "new_cmd": new_cmd},
)
)
def deprecated_cmd(old_cmd, new_cmd, callback=None, **kwargs):
import sys
import textwrap
from .color import RESET_COLOR
from .color import WARNING_COLOR
warning_msg = f"""
The command {old_cmd} is deprecated and will be removed from jrnl soon.
Please use {new_cmd} instead.
"""
warning_msg = textwrap.dedent(warning_msg)
logging.warning(warning_msg)
print(f"{WARNING_COLOR}{warning_msg}{RESET_COLOR}", file=sys.stderr)
if callback is not None:
callback(**kwargs)
def journal_list_to_json(journal_list: dict) -> str:
import json
def list_journals(configuration):
from . import config
return json.dumps(journal_list)
def journal_list_to_yaml(journal_list: dict) -> str:
from io import StringIO
from ruamel.yaml import YAML
output = StringIO()
dumper = YAML()
dumper.width = 1000
dumper.dump(journal_list, output)
return output.getvalue()
def journal_list_to_stdout(journal_list: dict) -> str:
result = f"Journals defined in config ({journal_list['config_path']})\n"
ml = min(max(len(k) for k in journal_list["journals"]), 20)
for journal, cfg in journal_list["journals"].items():
"""List the journals specified in the configuration file"""
result = f"Journals defined in {config.get_config_path()}\n"
ml = min(max(len(k) for k in configuration["journals"]), 20)
for journal, cfg in configuration["journals"].items():
result += " * {:{}} -> {}\n".format(
journal, ml, cfg["journal"] if isinstance(cfg, dict) else cfg
)
return result
def list_journals(configuration: dict, format: str | None = None) -> str:
from jrnl import config
"""List the journals specified in the configuration file"""
journal_list = {
"config_path": config.get_config_path(),
"journals": configuration["journals"],
}
if format == "json":
return journal_list_to_json(journal_list)
elif format == "yaml":
return journal_list_to_yaml(journal_list)
else:
return journal_list_to_stdout(journal_list)
def print_msg(msg: Message, **kwargs) -> str | None:
"""Helper function to print a single message"""
kwargs["style"] = msg.style
return print_msgs([msg], **kwargs)
def print_msgs(
msgs: list[Message],
delimiter: str = "\n",
style: MsgStyle = MsgStyle.NORMAL,
get_input: bool = False,
hide_input: bool = False,
) -> str | None:
# Same as print_msg, but for a list
text = Text("", end="")
kwargs = style.decoration.args
for i, msg in enumerate(msgs):
kwargs = _add_extra_style_args_if_needed(kwargs, msg=msg)
m = format_msg_text(msg)
if i != len(msgs) - 1:
m.append(delimiter)
text.append(m)
if style.append_space:
text.append(" ")
decorated_text = style.decoration.callback(text, **kwargs)
# Always print messages to stderr
console = _get_console(stderr=True)
if get_input:
return str(console.input(prompt=decorated_text, password=hide_input))
console.print(decorated_text, new_line_start=style.prepend_newline)
def _get_console(stderr: bool = True) -> Console:
return Console(stderr=stderr)
def _add_extra_style_args_if_needed(args: dict, msg: Message):
args["border_style"] = msg.style.color
args["title"] = msg.style.box_title
return args
def format_msg_text(msg: Message) -> Text:
text = textwrap.dedent(msg.text.value)
text = text.format(**msg.params)
# dedent again in case inserted text needs it
text = textwrap.dedent(text)
text = text.strip()
return Text(text)
def wrap_with_ansi_colors(text: str, width: int) -> str:
richtext = Text.from_ansi(text, no_wrap=False, tab_size=None)
console = Console(width=width, force_terminal=True)
with console.capture() as capture:
console.print(richtext, sep="", end="")
return capture.get()

View file

@ -1,17 +1,8 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
from typing import TYPE_CHECKING
from jrnl.config import make_yaml_valid_dict
from jrnl.config import update_config
if TYPE_CHECKING:
from argparse import Namespace
from .config import update_config, make_yaml_valid_dict
from argparse import Namespace
# import logging
def apply_overrides(args: "Namespace", base_config: dict) -> dict:
def apply_overrides(args: Namespace, base_config: dict) -> dict:
"""Unpack CLI provided overrides into the configuration tree.
:param overrides: List of configuration key-value pairs collected from the CLI
@ -21,12 +12,13 @@ def apply_overrides(args: "Namespace", base_config: dict) -> dict:
:return: Configuration to be used during runtime with the overrides applied
:rtype: dict
"""
overrides = vars(args).get("config_override")
overrides = vars(args).get("config_override", None)
if not overrides:
return base_config
cfg_with_overrides = base_config.copy()
for pairs in overrides:
pairs = make_yaml_valid_dict(pairs)
key_as_dots, override_value = _get_key_and_value_from_pair(pairs)
keys = _convert_dots_to_list(key_as_dots)
@ -38,12 +30,12 @@ def apply_overrides(args: "Namespace", base_config: dict) -> dict:
return base_config
def _get_key_and_value_from_pair(pairs: dict) -> tuple:
def _get_key_and_value_from_pair(pairs):
key_as_dots, override_value = list(pairs.items())[0]
return key_as_dots, override_value
def _convert_dots_to_list(key_as_dots: str) -> list[str]:
def _convert_dots_to_list(key_as_dots):
keys = key_as_dots.split(".")
keys = [k for k in keys if k != ""] # remove empty elements
return keys
@ -56,8 +48,7 @@ def _recursively_apply(tree: dict, nodes: list, override_value) -> dict:
Args:
config (dict): Configuration to modify
nodes (list): Vector of override keys; the length of the vector indicates tree
depth
nodes (list): Vector of override keys; the length of the vector indicates tree depth
override_value (str): Runtime override passed from the command-line
"""
key = nodes[0]

View file

@ -1,72 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import os.path
from pathlib import Path
import xdg.BaseDirectory
from jrnl.exception import JrnlException
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
# Constants
XDG_RESOURCE = "jrnl"
DEFAULT_CONFIG_NAME = "jrnl.yaml"
DEFAULT_JOURNAL_NAME = "journal.txt"
def home_dir() -> str:
return os.path.expanduser("~")
def expand_path(path: str) -> str:
return os.path.expanduser(os.path.expandvars(path))
def absolute_path(path: str) -> str:
return os.path.abspath(expand_path(path))
def get_default_journal_path() -> str:
journal_data_path = xdg.BaseDirectory.save_data_path(XDG_RESOURCE) or home_dir()
return os.path.join(journal_data_path, DEFAULT_JOURNAL_NAME)
def get_templates_path() -> str:
"""
Get the path to the XDG templates directory. Creates the directory if it
doesn't exist.
"""
# jrnl_xdg_resource_path is created by save_data_path if it does not exist
jrnl_xdg_resource_path = Path(xdg.BaseDirectory.save_data_path(XDG_RESOURCE))
jrnl_templates_path = jrnl_xdg_resource_path / "templates"
# Create the directory if needed.
jrnl_templates_path.mkdir(exist_ok=True)
return str(jrnl_templates_path)
def get_config_directory() -> str:
try:
return xdg.BaseDirectory.save_config_path(XDG_RESOURCE)
except FileExistsError:
raise JrnlException(
Message(
MsgText.ConfigDirectoryIsFile,
MsgStyle.ERROR,
{
"config_directory_path": os.path.join(
xdg.BaseDirectory.xdg_config_home, XDG_RESOURCE
)
},
),
)
def get_config_path() -> str:
try:
config_directory_path = get_config_directory()
except JrnlException:
return os.path.join(home_dir(), DEFAULT_CONFIG_NAME)
return os.path.join(config_directory_path, DEFAULT_CONFIG_NAME)

View file

@ -1,30 +1,28 @@
# Copyright © 2012-2023 jrnl contributors
# encoding: utf-8
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
from typing import Type
from jrnl.plugins.calendar_heatmap_exporter import CalendarHeatmapExporter
from jrnl.plugins.dates_exporter import DatesExporter
from jrnl.plugins.fancy_exporter import FancyExporter
from jrnl.plugins.jrnl_importer import JRNLImporter
from jrnl.plugins.json_exporter import JSONExporter
from jrnl.plugins.markdown_exporter import MarkdownExporter
from jrnl.plugins.tag_exporter import TagExporter
from jrnl.plugins.text_exporter import TextExporter
from jrnl.plugins.xml_exporter import XMLExporter
from jrnl.plugins.yaml_exporter import YAMLExporter
from .fancy_exporter import FancyExporter
from .jrnl_importer import JRNLImporter
from .json_exporter import JSONExporter
from .markdown_exporter import MarkdownExporter
from .tag_exporter import TagExporter
from .dates_exporter import DatesExporter
from .template_exporter import __all__ as template_exporters
from .text_exporter import TextExporter
from .xml_exporter import XMLExporter
from .yaml_exporter import YAMLExporter
__exporters = [
CalendarHeatmapExporter,
DatesExporter,
FancyExporter,
JSONExporter,
MarkdownExporter,
TagExporter,
DatesExporter,
TextExporter,
XMLExporter,
YAMLExporter,
]
FancyExporter,
] + template_exporters
__importers = [JRNLImporter]
__exporter_types = {name: plugin for plugin in __exporters for name in plugin.names}
@ -36,14 +34,14 @@ EXPORT_FORMATS = sorted(__exporter_types.keys())
IMPORT_FORMATS = sorted(__importer_types.keys())
def get_exporter(format: str) -> Type[TextExporter] | None:
def get_exporter(format):
for exporter in __exporters:
if hasattr(exporter, "names") and format in exporter.names:
return exporter
return None
def get_importer(format: str) -> Type[JRNLImporter] | None:
def get_importer(format):
for importer in __importers:
if hasattr(importer, "names") and format in importer.names:
return importer

View file

@ -1,117 +0,0 @@
# Copyright © 2012-2023 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import calendar
from datetime import datetime
from typing import TYPE_CHECKING
from rich import box
from rich.align import Align
from rich.columns import Columns
from rich.console import Console
from rich.table import Table
from rich.text import Text
from jrnl.plugins.text_exporter import TextExporter
from jrnl.plugins.util import get_journal_frequency_nested
if TYPE_CHECKING:
from jrnl.journals import Entry
from jrnl.journals import Journal
from jrnl.plugins.util import NestedDict
class CalendarHeatmapExporter(TextExporter):
"""This Exporter displays a calendar heatmap of the journaling frequency."""
names = ["calendar", "heatmap"]
extension = "cal"
@classmethod
def export_entry(cls, entry: "Entry"):
raise NotImplementedError
@classmethod
def print_calendar_heatmap(cls, journal_frequency: "NestedDict") -> str:
"""Returns a string representation of the calendar heatmap."""
console = Console()
cal = calendar.Calendar()
curr_year = datetime.now().year
curr_month = datetime.now().month
curr_day = datetime.now().day
hit_first_entry = False
with console.capture() as capture:
for year, month_journaling_freq in journal_frequency.items():
year_calendar = []
for month in range(1, 13):
if month > curr_month and year == curr_year:
break
entries_this_month = sum(month_journaling_freq[month].values())
if not hit_first_entry and entries_this_month > 0:
hit_first_entry = True
if entries_this_month == 0 and not hit_first_entry:
continue
elif entries_this_month == 0:
entry_msg = "No entries"
elif entries_this_month == 1:
entry_msg = "1 entry"
else:
entry_msg = f"{entries_this_month} entries"
table = Table(
title=f"{calendar.month_name[month]} {year} ({entry_msg})",
title_style="bold green",
box=box.SIMPLE_HEAVY,
padding=0,
)
for week_day in cal.iterweekdays():
table.add_column(
"{:.3}".format(calendar.day_name[week_day]), justify="right"
)
month_days = cal.monthdayscalendar(year, month)
for weekdays in month_days:
days = []
for _, day in enumerate(weekdays):
if day == 0: # Not a part of this month, just filler.
day_label = Text(str(day or ""), style="white")
elif (
day > curr_day
and month == curr_month
and year == curr_year
):
break
else:
journal_frequency_for_day = (
month_journaling_freq[month][day] or 0
)
day = str(day)
# TODO: Make colors configurable?
if journal_frequency_for_day == 0:
day_label = Text(day, style="red on black")
elif journal_frequency_for_day == 1:
day_label = Text(day, style="black on yellow")
elif journal_frequency_for_day == 2:
day_label = Text(day, style="black on green")
else:
day_label = Text(day, style="black on white")
days.append(day_label)
table.add_row(*days)
year_calendar.append(Align.center(table))
# Print year header line
console.rule(str(year))
console.print()
# Print calendar
console.print(Columns(year_calendar, padding=1, expand=True))
return capture.get()
@classmethod
def export_journal(cls, journal: "Journal"):
"""Returns dates and their frequencies for an entire journal."""
journal_entry_date_frequency = get_journal_frequency_nested(journal)
return cls.print_calendar_heatmap(journal_entry_date_frequency)

View file

@ -1,14 +1,9 @@
# Copyright © 2012-2023 jrnl contributors
# encoding: utf-8
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
from collections import Counter
from typing import TYPE_CHECKING
from jrnl.plugins.text_exporter import TextExporter
from jrnl.plugins.util import get_journal_frequency_one_level
if TYPE_CHECKING:
from jrnl.journals import Entry
from jrnl.journals import Journal
from .text_exporter import TextExporter
class DatesExporter(TextExporter):
@ -18,12 +13,16 @@ class DatesExporter(TextExporter):
extension = "dates"
@classmethod
def export_entry(cls, entry: "Entry"):
def export_entry(cls, entry):
raise NotImplementedError
@classmethod
def export_journal(cls, journal: "Journal") -> str:
def export_journal(cls, journal):
"""Returns dates and their frequencies for an entire journal."""
date_counts = get_journal_frequency_one_level(journal)
date_counts = Counter()
for entry in journal.entries:
# entry.date.date() gets date without time
date = str(entry.date.date())
date_counts[date] += 1
result = "\n".join(f"{date}, {count}" for date, count in date_counts.items())
return result

View file

@ -1,24 +1,15 @@
# Copyright © 2012-2023 jrnl contributors
# encoding: utf-8
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import logging
import os
from jrnl.exception import JrnlError
from textwrap import TextWrapper
from typing import TYPE_CHECKING
from jrnl.exception import JrnlException
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
from jrnl.plugins.text_exporter import TextExporter
if TYPE_CHECKING:
from jrnl.journals import Entry
from jrnl.journals import Journal
from .text_exporter import TextExporter
class FancyExporter(TextExporter):
"""This Exporter converts entries and journals into text with unicode boxes."""
"""This Exporter can convert entries and journals into text with unicode box drawing characters."""
names = ["fancy", "boxed"]
extension = "txt"
@ -40,31 +31,16 @@ class FancyExporter(TextExporter):
border_m = ""
@classmethod
def export_entry(cls, entry: "Entry") -> str:
def export_entry(cls, entry):
"""Returns a fancy unicode representation of a single entry."""
date_str = entry.date.strftime(entry.journal.config["timeformat"])
if entry.journal.config["linewrap"]:
linewrap = entry.journal.config["linewrap"]
if linewrap == "auto":
try:
linewrap = os.get_terminal_size().columns
except OSError:
logging.debug(
"Can't determine terminal size automatically 'linewrap': '%s'",
entry.journal.config["linewrap"],
)
linewrap = 79
else:
linewrap = 79
linewrap = entry.journal.config["linewrap"] or 78
initial_linewrap = max((1, linewrap - len(date_str) - 2))
body_linewrap = linewrap - 2
card = [
cls.border_a + cls.border_b * (initial_linewrap) + cls.border_c + date_str
]
check_provided_linewrap_viability(linewrap, card, entry.journal.name)
check_provided_linewrap_viability(linewrap, card, entry.journal)
w = TextWrapper(
width=initial_linewrap,
@ -72,7 +48,7 @@ class FancyExporter(TextExporter):
subsequent_indent=cls.border_g + " ",
)
title_lines = w.wrap(entry.title) or [""]
title_lines = w.wrap(entry.title)
card.append(
title_lines[0].ljust(initial_linewrap + 1)
+ cls.border_d
@ -100,24 +76,17 @@ class FancyExporter(TextExporter):
return "\n".join(card)
@classmethod
def export_journal(cls, journal) -> str:
def export_journal(cls, journal):
"""Returns a unicode representation of an entire journal."""
return "\n".join(cls.export_entry(entry) for entry in journal)
def check_provided_linewrap_viability(
linewrap: int, card: list[str], journal: "Journal"
):
def check_provided_linewrap_viability(linewrap, card, journal):
if len(card[0]) > linewrap:
width_violation = len(card[0]) - linewrap
raise JrnlException(
Message(
MsgText.LineWrapTooSmallForDateFormat,
MsgStyle.NORMAL,
{
"config_linewrap": linewrap,
"columns": width_violation,
"journal": journal,
},
)
raise JrnlError(
"LineWrapTooSmallForDateFormat",
config_linewrap=linewrap,
columns=width_violation,
journal=journal,
)

View file

@ -1,17 +1,8 @@
# Copyright © 2012-2023 jrnl contributors
# encoding: utf-8
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import sys
from typing import TYPE_CHECKING
from jrnl.exception import JrnlException
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
from jrnl.output import print_msg
if TYPE_CHECKING:
from jrnl.journals import Journal
class JRNLImporter:
@ -20,7 +11,7 @@ class JRNLImporter:
names = ["jrnl"]
@staticmethod
def import_(journal: "Journal", input: str | None = None) -> None:
def import_(journal, input=None):
"""Imports from an existing file if input is specified, and
standard input otherwise."""
old_cnt = len(journal.entries)
@ -31,21 +22,12 @@ class JRNLImporter:
try:
other_journal_txt = sys.stdin.read()
except KeyboardInterrupt:
raise JrnlException(
Message(MsgText.KeyboardInterruptMsg, MsgStyle.ERROR_ON_NEW_LINE),
Message(MsgText.ImportAborted, MsgStyle.WARNING),
)
print("[Entries NOT imported into journal.]", file=sys.stderr)
sys.exit(0)
journal.import_(other_journal_txt)
new_cnt = len(journal.entries)
journal.write()
print_msg(
Message(
MsgText.ImportSummary,
MsgStyle.NORMAL,
{
"count": new_cnt - old_cnt,
"journal_name": journal.name,
},
)
print(
"[{} imported to {} journal]".format(new_cnt - old_cnt, journal.name),
file=sys.stderr,
)
journal.write()

View file

@ -1,15 +1,11 @@
# Copyright © 2012-2023 jrnl contributors
# encoding: utf-8
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import json
from typing import TYPE_CHECKING
from jrnl.plugins.text_exporter import TextExporter
from jrnl.plugins.util import get_tags_count
if TYPE_CHECKING:
from jrnl.journals import Entry
from jrnl.journals import Journal
from .text_exporter import TextExporter
from .util import get_tags_count
class JSONExporter(TextExporter):
@ -19,7 +15,7 @@ class JSONExporter(TextExporter):
extension = "json"
@classmethod
def entry_to_dict(cls, entry: "Entry") -> dict:
def entry_to_dict(cls, entry):
entry_dict = {
"title": entry.title,
"body": entry.body,
@ -54,12 +50,12 @@ class JSONExporter(TextExporter):
return entry_dict
@classmethod
def export_entry(cls, entry: "Entry") -> str:
def export_entry(cls, entry):
"""Returns a json representation of a single entry."""
return json.dumps(cls.entry_to_dict(entry), indent=2) + "\n"
@classmethod
def export_journal(cls, journal: "Journal") -> str:
def export_journal(cls, journal):
"""Returns a json representation of an entire journal."""
tags = get_tags_count(journal)
result = {

View file

@ -1,19 +1,15 @@
# Copyright © 2012-2023 jrnl contributors
# encoding: utf-8
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import os
import re
from typing import TYPE_CHECKING
import sys
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
from jrnl.output import print_msg
from jrnl.plugins.text_exporter import TextExporter
from jrnl.color import RESET_COLOR
from jrnl.color import WARNING_COLOR
if TYPE_CHECKING:
from jrnl.journals import Entry
from jrnl.journals import Journal
from .text_exporter import TextExporter
class MarkdownExporter(TextExporter):
@ -23,7 +19,7 @@ class MarkdownExporter(TextExporter):
extension = "md"
@classmethod
def export_entry(cls, entry: "Entry", to_multifile: bool = True) -> str:
def export_entry(cls, entry, to_multifile=True):
"""Returns a markdown representation of a single entry."""
date_str = entry.date.strftime(entry.journal.config["timeformat"])
body_wrapper = "\n" if entry.body else ""
@ -67,27 +63,25 @@ class MarkdownExporter(TextExporter):
newbody = newbody + os.linesep
if warn_on_heading_level is True:
print_msg(
Message(
MsgText.HeadingsPastH6,
MsgStyle.WARNING,
{"date": date_str, "title": entry.title},
)
print(
f"{WARNING_COLOR}WARNING{RESET_COLOR}: "
f"Headings increased past H6 on export - {date_str} {entry.title}",
file=sys.stderr,
)
return f"{heading} {date_str} {entry.title}\n{newbody} "
@classmethod
def export_journal(cls, journal: "Journal") -> str:
def export_journal(cls, journal):
"""Returns a Markdown representation of an entire journal."""
out = []
year, month = -1, -1
for e in journal.entries:
if e.date.year != year:
if not e.date.year == year:
year = e.date.year
out.append("# " + str(year))
out.append("")
if e.date.month != month:
if not e.date.month == month:
month = e.date.month
out.append("## " + e.date.strftime("%B"))
out.append("")

View file

@ -1,29 +1,24 @@
# Copyright © 2012-2023 jrnl contributors
# encoding: utf-8
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
from typing import TYPE_CHECKING
from jrnl.plugins.text_exporter import TextExporter
from jrnl.plugins.util import get_tags_count
if TYPE_CHECKING:
from jrnl.journals import Entry
from jrnl.journals import Journal
from .text_exporter import TextExporter
from .util import get_tags_count
class TagExporter(TextExporter):
"""This Exporter lists the tags for entries and journals."""
"""This Exporter can lists the tags for entries and journals, exported as a plain text file."""
names = ["tags"]
extension = "tags"
@classmethod
def export_entry(cls, entry: "Entry") -> str:
def export_entry(cls, entry):
"""Returns a list of tags for a single entry."""
return ", ".join(entry.tags)
@classmethod
def export_journal(cls, journal: "Journal") -> str:
def export_journal(cls, journal):
"""Returns a list of tags and their frequency for an entire journal."""
tag_counts = get_tags_count(journal)
result = ""

142
jrnl/plugins/template.py Normal file
View file

@ -0,0 +1,142 @@
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import re
import yaml
VAR_RE = r"[_a-zA-Z][a-zA-Z0-9_]*"
EXPRESSION_RE = r"[\[\]():.a-zA-Z0-9_]*"
PRINT_RE = r"{{ *(.+?) *}}"
START_BLOCK_RE = r"{% *(if|for) +(.+?) *%}"
END_BLOCK_RE = r"{% *end(for|if) *%}"
FOR_RE = r"{{% *for +({varname}) +in +([^%]+) *%}}".format(varname=VAR_RE)
IF_RE = r"{% *if +(.+?) *%}"
BLOCK_RE = r"{% *block +(.+?) *%}((?:.|\n)+?){% *endblock *%}"
INCLUDE_RE = r"{% *include +(.+?) *%}"
class Template:
def __init__(self, template):
self.template = template
self.clean_template = None
self.blocks = {}
@classmethod
def from_file(cls, filename):
with open(filename) as f:
front_matter, body = f.read().strip("-\n").split("---", 2)
front_matter = yaml.load(front_matter, Loader=yaml.SafeLoader)
template = cls(body)
template.__dict__.update(front_matter)
return template
def render(self, **vars):
if self.clean_template is None:
self._get_blocks()
return self._expand(self.clean_template, **vars)
def render_block(self, block, **vars):
if self.clean_template is None:
self._get_blocks()
return self._expand(self.blocks[block], **vars)
def _eval_context(self, vars):
import asteval
e = asteval.Interpreter(use_numpy=False, writer=None)
e.symtable.update(vars)
e.symtable["__last_iteration"] = vars.get("__last_iteration", False)
return e
def _get_blocks(self):
def s(match):
name, contents = match.groups()
self.blocks[name] = self._strip_single_nl(contents)
return ""
self.clean_template = re.sub(BLOCK_RE, s, self.template, flags=re.MULTILINE)
def _expand(self, template, **vars):
stack = sorted(
[
(m.start(), 1, m.groups()[0])
for m in re.finditer(START_BLOCK_RE, template)
]
+ [
(m.end(), -1, m.groups()[0])
for m in re.finditer(END_BLOCK_RE, template)
]
)
last_nesting, nesting = 0, 0
start = 0
result = ""
block_type = None
if not stack:
return self._expand_vars(template, **vars)
for pos, indent, typ in stack:
nesting += indent
if nesting == 1 and last_nesting == 0:
block_type = typ
result += self._expand_vars(template[start:pos], **vars)
start = pos
elif nesting == 0 and last_nesting == 1:
if block_type == "if":
result += self._expand_cond(template[start:pos], **vars)
elif block_type == "for":
result += self._expand_loops(template[start:pos], **vars)
elif block_type == "block":
result += self._save_block(template[start:pos], **vars)
start = pos
last_nesting = nesting
result += self._expand_vars(template[stack[-1][0] :], **vars)
return result
def _expand_vars(self, template, **vars):
safe_eval = self._eval_context(vars)
expanded = re.sub(
INCLUDE_RE, lambda m: self.render_block(m.groups()[0], **vars), template
)
return re.sub(PRINT_RE, lambda m: str(safe_eval(m.groups()[0])), expanded)
def _expand_cond(self, template, **vars):
start_block = re.search(IF_RE, template, re.M)
end_block = list(re.finditer(END_BLOCK_RE, template, re.M))[-1]
expression = start_block.groups()[0]
sub_template = self._strip_single_nl(
template[start_block.end() : end_block.start()]
)
safe_eval = self._eval_context(vars)
if safe_eval(expression):
return self._expand(sub_template)
return ""
def _strip_single_nl(self, template, strip_r=True):
if template[0] == "\n":
template = template[1:]
if strip_r and template[-1] == "\n":
template = template[:-1]
return template
def _expand_loops(self, template, **vars):
start_block = re.search(FOR_RE, template, re.M)
end_block = list(re.finditer(END_BLOCK_RE, template, re.M))[-1]
var_name, iterator = start_block.groups()
sub_template = self._strip_single_nl(
template[start_block.end() : end_block.start()], strip_r=False
)
safe_eval = self._eval_context(vars)
result = ""
items = safe_eval(iterator)
for idx, var in enumerate(items):
vars[var_name] = var
vars["__last_iteration"] = idx == len(items) - 1
result += self._expand(sub_template, **vars)
del vars[var_name]
return self._strip_single_nl(result)

View file

@ -0,0 +1,43 @@
# encoding: utf-8
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
from glob import glob
import os
from .template import Template
from .text_exporter import TextExporter
class GenericTemplateExporter(TextExporter):
"""This Exporter can convert entries and journals into text files."""
@classmethod
def export_entry(cls, entry):
"""Returns a string representation of a single entry."""
vars = {"entry": entry, "tags": entry.tags}
return cls.template.render_block("entry", **vars)
@classmethod
def export_journal(cls, journal):
"""Returns a string representation of an entire journal."""
vars = {"journal": journal, "entries": journal.entries, "tags": journal.tags}
return cls.template.render_block("journal", **vars)
def __exporter_from_file(template_file):
"""Create a template class from a file"""
name = os.path.basename(template_file).replace(".template", "")
template = Template.from_file(template_file)
return type(
str(f"{name.title()}Exporter"),
(GenericTemplateExporter,),
{"names": [name], "extension": template.extension, "template": template},
)
__all__ = []
# Factory pattern to create Exporter classes for all available templates
for template_file in glob("jrnl/templates/*.template"):
__all__.append(__exporter_from_file(template_file))

View file

@ -1,20 +1,13 @@
# Copyright © 2012-2023 jrnl contributors
# encoding: utf-8
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import errno
import os
import re
import unicodedata
from typing import TYPE_CHECKING
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
from jrnl.output import print_msg
if TYPE_CHECKING:
from jrnl.journals import Entry
from jrnl.journals import Journal
from jrnl.color import ERROR_COLOR
from jrnl.color import RESET_COLOR
class TextExporter:
@ -24,70 +17,46 @@ class TextExporter:
extension = "txt"
@classmethod
def export_entry(cls, entry: "Entry") -> str:
def export_entry(cls, entry):
"""Returns a string representation of a single entry."""
return str(entry)
@classmethod
def export_journal(cls, journal: "Journal") -> str:
def export_journal(cls, journal):
"""Returns a string representation of an entire journal."""
return "\n".join(cls.export_entry(entry) for entry in journal)
@classmethod
def write_file(cls, journal: "Journal", path: str) -> str:
def write_file(cls, journal, path):
"""Exports a journal into a single file."""
export_str = cls.export_journal(journal)
with open(path, "w", encoding="utf-8") as f:
f.write(export_str)
print_msg(
Message(
MsgText.JournalExportedTo,
MsgStyle.NORMAL,
{
"path": path,
},
)
)
return ""
try:
with open(path, "w", encoding="utf-8") as f:
f.write(cls.export_journal(journal))
return f"[Journal exported to {path}]"
except IOError as e:
return f"[{ERROR_COLOR}ERROR{RESET_COLOR}: {e.filename} {e.strerror}]"
@classmethod
def make_filename(cls, entry: "Entry") -> str:
def make_filename(cls, entry):
return entry.date.strftime("%Y-%m-%d") + "_{}.{}".format(
cls._slugify(str(entry.title)), cls.extension
)
@classmethod
def write_files(cls, journal: "Journal", path: str) -> str:
def write_files(cls, journal, path):
"""Exports a journal into individual files for each entry."""
for entry in journal.entries:
entry_is_written = False
while not entry_is_written:
try:
full_path = os.path.join(path, cls.make_filename(entry))
try:
with open(full_path, "w", encoding="utf-8") as f:
f.write(cls.export_entry(entry))
entry_is_written = True
except OSError as oserr:
title_length = len(str(entry.title))
if (
oserr.errno == errno.ENAMETOOLONG
or oserr.errno == errno.ENOENT
or oserr.errno == errno.EINVAL
) and title_length > 1:
shorter_file_length = title_length // 2
entry.title = str(entry.title)[:shorter_file_length]
else:
raise
print_msg(
Message(
MsgText.JournalExportedTo,
MsgStyle.NORMAL,
{"path": path},
)
)
return ""
with open(full_path, "w", encoding="utf-8") as f:
f.write(cls.export_entry(entry))
except IOError as e:
return "[{2}ERROR{3}: {0} {1}]".format(
e.filename, e.strerror, ERROR_COLOR, RESET_COLOR
)
return "[Journal exported to {}]".format(path)
def _slugify(string: str) -> str:
def _slugify(string):
"""Slugifies a string.
Based on public domain code from https://github.com/zacharyvoase/slugify
"""
@ -97,7 +66,7 @@ class TextExporter:
return slug
@classmethod
def export(cls, journal: "Journal", output: str | None = None) -> str:
def export(cls, journal, output=None):
"""Exports to individual files if output is an existing path, or into
a single file if output is a file name, or returns the exporter's
representation as string if output is None."""

View file

@ -1,33 +1,19 @@
# Copyright © 2012-2023 jrnl contributors
# encoding: utf-8
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
from collections import Counter
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from jrnl.journals import Journal
class NestedDict(dict):
"""https://stackoverflow.com/a/74873621/8740440"""
def __missing__(self, x):
self[x] = NestedDict()
return self[x]
def get_tags_count(journal: "Journal") -> set[tuple[int, str]]:
def get_tags_count(journal):
"""Returns a set of tuples (count, tag) for all tags present in the journal."""
# Astute reader: should the following line leave you as puzzled as me the first time
# I came across this construction, worry not and embrace the ensuing moment of
# enlightment.
# I came across this construction, worry not and embrace the ensuing moment of enlightment.
tags = [tag for entry in journal.entries for tag in set(entry.tags)]
# To be read: [for entry in journal.entries: for tag in set(entry.tags): tag]
tag_counts = {(tags.count(tag), tag) for tag in tags}
return tag_counts
def oxford_list(lst: list) -> str:
def oxford_list(lst):
"""Return Human-readable list of things obeying the object comma)"""
lst = sorted(lst)
if not lst:
@ -38,26 +24,3 @@ def oxford_list(lst: list) -> str:
return lst[0] + " or " + lst[1]
else:
return ", ".join(lst[:-1]) + ", or " + lst[-1]
def get_journal_frequency_nested(journal: "Journal") -> NestedDict:
"""Returns a NestedDict of the form {year: {month: {day: count}}}"""
journal_frequency = NestedDict()
for entry in journal.entries:
date = entry.date.date()
if date.day in journal_frequency[date.year][date.month]:
journal_frequency[date.year][date.month][date.day] += 1
else:
journal_frequency[date.year][date.month][date.day] = 1
return journal_frequency
def get_journal_frequency_one_level(journal: "Journal") -> Counter:
"""Returns a Counter of the form {date (YYYY-MM-DD): count}"""
date_counts = Counter()
for entry in journal.entries:
# entry.date.date() gets date without time
date = str(entry.date.date())
date_counts[date] += 1
return date_counts

View file

@ -1,15 +1,11 @@
# Copyright © 2012-2023 jrnl contributors
# encoding: utf-8
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
from typing import TYPE_CHECKING
from xml.dom import minidom
from jrnl.plugins.json_exporter import JSONExporter
from jrnl.plugins.util import get_tags_count
if TYPE_CHECKING:
from jrnl.journals import Entry
from jrnl.journals import Journal
from .json_exporter import JSONExporter
from .util import get_tags_count
class XMLExporter(JSONExporter):
@ -19,9 +15,7 @@ class XMLExporter(JSONExporter):
extension = "xml"
@classmethod
def export_entry(
cls, entry: "Entry", doc: minidom.Document | None = None
) -> minidom.Element | str:
def export_entry(cls, entry, doc=None):
"""Returns an XML representation of a single entry."""
doc_el = doc or minidom.Document()
entry_el = doc_el.createElement("entry")
@ -36,7 +30,7 @@ class XMLExporter(JSONExporter):
return entry_el
@classmethod
def entry_to_xml(cls, entry: "Entry", doc: minidom.Document) -> minidom.Element:
def entry_to_xml(cls, entry, doc):
entry_el = doc.createElement("entry")
entry_el.setAttribute("date", entry.date.isoformat())
if hasattr(entry, "uuid"):
@ -51,7 +45,7 @@ class XMLExporter(JSONExporter):
return entry_el
@classmethod
def export_journal(cls, journal: "Journal") -> str:
def export_journal(cls, journal):
"""Returns an XML representation of an entire journal."""
tags = get_tags_count(journal)
doc = minidom.Document()

View file

@ -1,41 +1,41 @@
# Copyright © 2012-2023 jrnl contributors
# encoding: utf-8
# Copyright (C) 2012-2021 jrnl contributors
# License: https://www.gnu.org/licenses/gpl-3.0.html
import os
import re
from typing import TYPE_CHECKING
import sys
from jrnl.exception import JrnlException
from jrnl.messages import Message
from jrnl.messages import MsgStyle
from jrnl.messages import MsgText
from jrnl.output import print_msg
from jrnl.plugins.text_exporter import TextExporter
from jrnl.color import ERROR_COLOR
from jrnl.color import RESET_COLOR
from jrnl.color import WARNING_COLOR
if TYPE_CHECKING:
from jrnl.journals import Entry
from jrnl.journals import Journal
from .text_exporter import TextExporter
class YAMLExporter(TextExporter):
"""This Exporter converts entries and journals into Markdown formatted text with
YAML front matter."""
"""This Exporter can convert entries and journals into Markdown formatted text with YAML front matter."""
names = ["yaml"]
extension = "md"
@classmethod
def export_entry(cls, entry: "Entry", to_multifile: bool = True) -> str:
"""Returns a markdown representation of an entry, with YAML front matter."""
def export_entry(cls, entry, to_multifile=True):
"""Returns a markdown representation of a single entry, with YAML front matter."""
if to_multifile is False:
raise JrnlException(Message(MsgText.YamlMustBeDirectory, MsgStyle.ERROR))
print(
f"{ERROR_COLOR}ERROR{RESET_COLOR}: YAML export must be to individual files. Please \
specify a directory to export to.",
file=sys.stderr,
)
return
date_str = entry.date.strftime(entry.journal.config["timeformat"])
body_wrapper = "\n" if entry.body else ""
body = body_wrapper + entry.body
tagsymbols = entry.journal.config["tagsymbols"]
# see also Entry.rag_regex
# see also Entry.Entry.rag_regex
multi_tag_regex = re.compile(rf"(?u)^\s*([{tagsymbols}][-+*#/\w]+\s*)+$")
"""Increase heading levels in body text"""
@ -80,12 +80,11 @@ class YAMLExporter(TextExporter):
spacebody = spacebody + "\t" + line
if warn_on_heading_level is True:
print_msg(
Message(
MsgText.HeadingsPastH6,
MsgStyle.WARNING,
{"date": date_str, "title": entry.title},
)
print(
"{}WARNING{}: Headings increased past H6 on export - {} {}".format(
WARNING_COLOR, RESET_COLOR, date_str, entry.title
),
file=sys.stderr,
)
dayone_attributes = ""
@ -118,14 +117,7 @@ class YAMLExporter(TextExporter):
# source directory is entry.journal.config['journal']
# output directory is...?
return (
"{start}\n"
"title: {title}\n"
"date: {date}\n"
"starred: {starred}\n"
"tags: {tags}\n"
"{dayone}body: |{body}{end}"
).format(
return "{start}\ntitle: {title}\ndate: {date}\nstarred: {starred}\ntags: {tags}\n{dayone}body: |{body}{end}".format(
start="---",
date=date_str,
title=entry.title,
@ -137,6 +129,12 @@ class YAMLExporter(TextExporter):
)
@classmethod
def export_journal(cls, journal: "Journal"):
def export_journal(cls, journal):
"""Returns an error, as YAML export requires a directory as a target."""
raise JrnlException(Message(MsgText.YamlMustBeDirectory, MsgStyle.ERROR))
print(
"{}ERROR{}: YAML export must be to individual files. Please specify a directory to export to.".format(
ERROR_COLOR, RESET_COLOR
),
file=sys.stderr,
)
return

Some files were not shown because too many files have changed in this diff Show more