Compare commits

...

47 commits
0.4.0 ... main

Author SHA1 Message Date
shumadrid
28fbb87a58 chore: add .env.example 2026-05-15 18:04:56 +02:00
shumadrid
f8c4ba9cce docs: mention another alternative 2026-02-11 18:12:15 +01:00
shumadrid
da39f3c03f docs: update README 2026-01-26 15:36:36 +01:00
shumadrid
c0b5af4c33 docs: put disclaimer in README 2025-09-27 03:05:01 +02:00
shumadrid
17dd8af17a docs: update README 2025-08-31 00:49:35 +02:00
shumadrid
758e0894f1 fix: make ReviewChangesReminderInterval notification animate away normally 2025-06-19 10:57:19 +02:00
shumadrid
bf0a1c423f 0.6.0 2025-06-18 19:37:15 +02:00
shumadrid
ce31de08d9 docs: update README 2025-06-18 19:28:59 +02:00
shumadrid
b0ee224df1 refactor: rename checkpointReminderInterval to reviewChangesReminderInterval 2025-06-18 19:24:43 +02:00
shumadrid
003839ecd5 fix: clean up settings tab and CheckpointReminderInterval notification ui 2025-06-18 19:16:49 +02:00
shumadrid
18b9e3fde0 chore: revert deps 2025-06-18 18:50:21 +02:00
shumadrid
f73534721b docs: update README 2025-06-18 18:19:15 +02:00
shumadrid
1e51e7133b chore: verify compatibility with git plugin version 2.34.0 2025-06-18 18:10:09 +02:00
shumadrid
bff0523bdd feat: implement checkpoint reminder functionality 2025-06-18 18:04:59 +02:00
shumadrid
4c2b879790 feat: add checkpoint reminder settings 2025-06-18 17:05:45 +02:00
shumadrid
65b4d25ec7 docs: update README 2025-06-17 16:25:57 +02:00
shumadrid
d462290099 chore: update deps 2025-06-12 12:35:33 +02:00
shumadrid
6d856a18c9 refactor: remove unused constructor parameter in FileChangelogManager 2025-05-18 13:46:10 +02:00
shumadrid
e47e967cd3 fix: more accurate whitespace ignore settings descriptions 2025-05-05 15:48:28 +02:00
shumadrid
c17b5fa397 0.5.1 2025-04-29 22:09:54 +02:00
shumadrid
002412e7a1 chore: update MAX_TESTED_GIT_PLUGIN_VERSION 2025-04-29 22:08:37 +02:00
shumadrid
de8ec18fb7 fix: don't auto initialize the first checkpoint 2025-04-26 20:00:58 +02:00
shumadrid
cefed096f2 docs: update README 2025-04-26 19:59:23 +02:00
shumadrid
4d9f831662 docs: add QuickAdd macro example to README 2025-04-20 00:26:37 +02:00
shumadrid
541bfc217e docs: fix README 2025-04-16 21:47:17 +02:00
shumadrid
c10368ab75 fix: update versions.json 2025-04-16 20:33:59 +02:00
shumadrid
717dc0db22 0.5.0 2025-04-16 20:25:57 +02:00
shumadrid
e661c75182 feat: show notice when user updates the version 2025-04-16 19:48:07 +02:00
shumadrid
54d7b1db4d docs: update README 2025-04-16 19:01:51 +02:00
shumadrid
b1f407a7b4 feat: introduce validation messages to settings 2025-04-16 19:00:37 +02:00
shumadrid
b37d52b7ea feat: show in file changelog if file is in .gitignore 2025-04-15 11:07:36 +02:00
shumadrid
8f39e82434 fix: mention file changelog edge cases in info tooltip 2025-04-15 02:14:33 +02:00
shumadrid
e58a981253 fix: empty the file changelog view if no DiffViews are visible 2025-04-15 00:06:01 +02:00
shumadrid
4f55251839 feat: close temporary compare views when they aren't visible anymore 2025-04-12 17:35:23 +02:00
shumadrid
f267afbea3 fix: prevent excluding the git root folder from changelog 2025-04-11 14:42:22 +02:00
shumadrid
53a7b0335f refactor: print stack trace to console in assertNotNull 2025-04-11 14:32:09 +02:00
shumadrid
a8ef4e2097 fix: properly convert timezones in PrepareCompareModal 2025-04-11 14:31:11 +02:00
shumadrid
f73934999e fix: disable adding paths above repo root to exclude list to avoid git errors 2025-04-11 13:00:38 +02:00
shumadrid
7d4d0ecdb3 docs: update README 2025-04-11 00:00:21 +02:00
shumadrid
d907fc8984 feat: add two new views, add setting validation in ui 2025-04-10 16:09:13 +02:00
shumadrid
29f984736b refactor: rename settings properties 2025-04-08 16:51:28 +02:00
shumadrid
b37f46e571 fix: fix double computation on changing intervals 2025-04-08 10:36:26 +02:00
shumadrid
2628a4ffca refactor: switch settings code template 2025-04-08 03:39:44 +02:00
shumadrid
790fc02936 refactor: rename convertToInclude setting 2025-04-07 10:28:36 +02:00
shumadrid
7302642bcb docs: update README 2025-04-04 00:16:33 +02:00
shumadrid
559f0d3645 docs: update docs 2025-04-03 18:56:20 +02:00
shumadrid
fd92aea22a feat: add option to convert ExcludeFilesAndFolders to include list 2025-04-03 01:11:27 +02:00
85 changed files with 5936 additions and 2630 deletions

1
.env.example Normal file
View file

@ -0,0 +1 @@
OBSIDIAN_CONFIG_FOLDER=

BIN
.github/quick-add-macro.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

View file

@ -1,5 +1,46 @@
# CHANGELOG
## 0.6.0
### Features
- "Review changes reminder" feature. Receive a notification to review changes in your vault at a recurring interval (disabled by default).
### Bug Fixes
- More accurate descriptions for the whitespace ignore settings.
## 0.5.1
### Bug Fixes
- Stop auto initializing the first checkpoint (#4 Thanks to @texastoland for the suggestion).
- Shorten "Approve & create new checkpoint" button text.
## 0.5.0
### What's Changed
#### Features
- New "Compare two vault states in history" and "Show vault changes since the last checkpoint" commands. The results of these commands are shown in a temporary side view.
- Add validation to settings tab UI and polish the layout.
- Display a message in the file changelog view when the opened file is ignored by Git.
- Mention unusual scenarios that can lead to the "File has no git history" state in the file changelog view. (#3 Thanks to @AMC-Albert for the suggestion!)
- Option to convert ExcludeFilesAndFolders to an include list.
- Option to temporarily disable the ExcludeFilesAndFolders list.
- Reorganized the settings internally. Users that are updating from a previous version will need to reconfigure all settings that have been affected.
#### Bug Fixes
- Clear the file changelog view if no DiffViews are visible.
- Improved conditional changelog recalculation logic on settings changes.
- Fix an issue where the date labels of the changelog versions were sometimes staying outdated.
- Prevent excluding the git root folder from the vault changelog.
- Prevent adding paths above git root folder to the exclude list to avoid git errors.
- Apply the "Day start time" setting only when the day interval for a changelog is active (to avoid confusion).
- Update the minimum required Obsidian version to 1.8.9.
## 0.4.0
### Features

238
README.md
View file

@ -1,66 +1,104 @@
# Git Changelog
A new [Obsidian](https://obsidian.md) plugin that utilizes Git commit history to display dynamic changelogs in your sidebar. Also usable as a practical data loss monitoring tool.
An [Obsidian](https://obsidian.md) plugin that utilizes Git commit history to display dynamic changelogs in your sidebar. Also usable as a practical data loss monitoring tool.
> [!NOTE]
> January 2026 update: I didn't forget about this plugin, I'm just busy with other stuff currently. I plan to continue working on it when I get the time.
> If in the meantime a change happens in Obsidian or the Git plugin that breaks this plugin, I'll fix it.
![Showcase](.github/showcase.gif)
## Table of Contents
- [Installation](#installation)
- [Features](#features)
- [Vault Changelog View](#vault-changelog-view)
- [File Changelog View](#file-changelog-view)
- [Changelog Customizability](#changelog-customizability)
- [Live Stats in the Status Bar for the Current Note](#live-stats-in-the-status-bar-for-the-current-note)
- [Integration with Git Plugin's Diff View](#integration-with-git-plugins-diff-view)
- [Compare Two Vault States in History](#compare-two-vault-states-in-history)
- [Show Vault Changes since the Last Checkpoint](#show-vault-changes-since-the-last-checkpoint)
- [Data Loss Monitoring](#data-loss-monitoring)
- [Common Causes of Data Loss](#common-causes-of-data-loss)
- [How to Use](#how-to-use)
- [Limitations](#limitations)
- [Roadmap](#roadmap)
- [Alternatives](#alternatives)
- [FAQ](#faq)
- [Debugging](#debugging)
- [Contributing](#contributing)
- [Credits](#credits)
## Installation
Install the plugin from [the official Community Plugins repository](https://obsidian.md/plugins?id=git-changelog).
[Download](https://obsidian.md/plugins?id=git-changelog) the plugin from the official Community Plugins repository.
> [!IMPORTANT]
> Requires the [Git plugin](https://github.com/Vinzent03/obsidian-git) to be installed. Installing it and maintaining a Git repository can be beneficial, even if you rely on other syncing services.
> [!NOTE]
> This plugin is currently in beta and still under development, so your existing settings may break after each update.
> This plugin is currently in beta and still under development, so your existing settings may break after each update. If some saved settings were broken, they will be mentioned in the changelog.
## Features
To easily see the what's new in future updates, it's recommended to use the [Plugin Update Tracker](https://obsidian.md/plugins?id=obsidian-plugin-update-tracker).
### Vault Changelog View
- Detects renamed and moved files separately.
- Shows the total count of lines added and deleted.
- Displays counts of files added, modified, deleted, and moved/renamed (total or text and non-text separately). If a file is both renamed/moved and modified, it will contribute towards the renamed files stats.
- Lists per file lines added and deleted, along with additional file statuses (**A**dded, **R**enamed, **M**oved, or **D**eleted).
- **Exclude Files and Folders:**
Usually you specify files and folders you want to exclude from your Git repository in the `.gitignore` file.
Example of suggested items to put in `.gitignore` include OS specific files like `.DS_Store`, `.obsidian/workspace.json` and other plugins' cache files that constantly change and trigger commits even when no changes were made to the vault. These files usually don't hold any important user data and are regenerated easily (in case of needing to restore the vault from a backup).
But this setting is useful if you want to keep some files backed up by your repository (e.g. because they're valuable), but exclude them from appearing in the vault changelog.
Common examples for this: `.trash` and `.obsidian` folders, debug/log files, or conflict files generated by a syncing service that can clutter the changelog stats.
Also use this setting to filter files and folders that already exist in previous commits, since specifying files in .gitignore doesn't remove them from previous commits.
**Context menu integration:** To exclude a file or folder, just right-click on it inside the File explorer and select "Git changelog: Exclude" from the context menu, no need to manually define paths.
For advanced users: If you configured your Git repository to be below the vault root directory, the paths should be relative to the Git repo, not the vault.
![Vault Changelog View](.github/vault-changelog-view.webp)
### File Changelog View
- Detects renamed and moved files separately.
- Shows the total count of lines added and deleted.
- Displays counts of files added, modified, moved/renamed and deleted (total or text and non-text separately). **NOTE:** If a file is both renamed/moved and modified, it will contribute towards the renamed/moved files stats.
- Lists per file lines added and deleted, along with additional file statuses (**A**dded, **R**enamed, **M**oved, or **D**eleted).
- The files are sorted from most number of lines changed to least.
- **Exclude Files and Folders:**
- Shows the count of added and deleted lines for all previous versions of the active note.
- Usually you specify files and folders you want to exclude from your Git repository in the `.gitignore` file.
Example of suggested items to put in `.gitignore` include OS specific files like `.DS_Store`, `.obsidian/workspace.json` and other plugins' cache files that constantly change and trigger commits even when no changes were made to the vault. These files usually don't hold any important user data and are regenerated easily (in case of needing to restore the vault from a backup).
But this setting is useful if you want to keep some files backed up by your repository (e.g. because they're valuable), but exclude them from appearing in the vault changelog.
Common examples for this: `/.trash`, `/attachments` and `/.obsidian` folders, debug/log files, or conflict files generated by a syncing service that can clutter the changelog stats.
Also use this setting to filter files and folders that already exist in previous commits, since specifying files in .gitignore doesn't remove them from previous commits.
- **Context menu integration:** To exclude a file or folder, just right-click on it inside the File explorer and select "Git changelog: Exclude" from the context menu, no need to manually define paths.
- For advanced users: If you configured your Git repository to be below the vault root directory, the paths should be relative to the Git repo, not the vault.
- **Include items instead:**
- Convert the `Exclude Files and Folders` list to an include list, while excluding everything else.
- An example case where this can come in handy is when you notice your vault misbehaving, you can trigger this setting and put `.obsidian` in the list to exclusively see changes made inside your configuration folder.
Then you can easily investigate what settings recently changed and if some of the changes are the cause of your issue.
### File Changelog View
![File Changelog View](.github/file-changelog-view.webp)
- Shows the count of added and deleted lines for all previous versions of the active note.
> [!WARNING]
> Using the "Expand all" toggle will reduce view performance. This will be fixed soon.
> Showing a lot of versions and files will reduce view performance. This will be fixed soon.
### Changelog Customizability
- Set a custom day start time (if you're a night owl and want to track your actual days).
- Set a custom timezone to base the intervals on or detect it automatically.
- Choose to view hourly, daily, weekly, or monthly intervals.
- Easily switch between hourly, daily, weekly, and monthly intervals.
- Choose from 5 options to ignore whitespace changes with varying intensity.
- **Adjust file rename detection strictness:**
Git can't actually track which files you renamed. Instead, it tries to detect renames by comparing the file contents of the old and new files.
- Git can't actually track which files you renamed. Instead, it tries to detect renames by comparing the file contents of the old and new files.
It can falsely mark new files as some old file getting renamed, and it can miss actual renames and mark them as separate files getting deleted and created.
It can falsely mark new files as some old file getting renamed, and it can miss actual renames and mark them as separate files getting deleted and created.
Higher strictness results in detecting less renames.
- Higher strictness results in detecting less renames.
### Live Stats in the Status Bar for the Current Note
@ -71,7 +109,35 @@ Install the plugin from [the official Community Plugins repository](https://obsi
- Click on any file version in the changelog views to open the corresponding diff view showing the changes.
> [!WARNING]
> Currently only the "Split" diff view works. The "Unified" view shows inaccurate changes.
> Currently, only the "Split" diff view works. The "Unified" view shows inaccurate changes.
### Compare Two Vault States in History
- Use the `Compare two vault states in history` command to compare any two points in the vault's Git history.
- All settings that apply to the changelog views also apply to this command.
![Vault's git history comparison](.github/vault-git-history-comparison-modal.png)
### Show Vault Changes since the Last Checkpoint
- The easiest way to track all changes made to your vault over time is to use the `Show vault changes since the last checkpoint` command to open a temporary view that shows all changes that happened since the last checkpoint (meaning: the last time you ran this command and approved the shown changes by creating a new checkpoint).
- If you're someone who's always concerned about data integrity, you don't need to have the vault changelog view open all the time in order to track changes. 😁 Just run this command every now and then to inspect all changes made since the last time you checked. (Be it a few minutes ago or a few months.)
- Optionally receive a notification at a recurring set interval (in minutes) that reminds you to review the changes made since the last checkpoint.
- If you don't like that this command is using the latest commit as the comparison point instead of the live vault state:
- You can create an action (macro) using the [QuickAdd](https://obsidian.md/plugins?id=quickadd) plugin that will:
1. Run the "Commit-and-sync" or "Commit" command, depending on if you use Github to sync or not (these commands are available through the Git plugin).
2. Wait for some time for the commit to complete (e.g. 200ms).
3. Run the "Show Vault Changes since the Last Checkpoint" command.
- That way you will always compare the current state of your vault to the state of the last checkpoint.
- You can assign a hotkey to this macro by exposing it as an Obsidian command ([see how](https://youtu.be/gYK3VDQsZJo?t=179)).
- ![Quick Add Macro](.github/quick-add-macro.png)
- All settings that apply to the changelog views also apply to this command.
## Data Loss Monitoring
@ -83,43 +149,63 @@ This plugin can also serve as a tool for early detection of data loss: if the di
- ❌ Faulty plugins
- ⛓️‍💥 Device malfunction
- 🤷‍♂️ Accidental text overwrites and other user errors
- 📜 Running faulty or outdated scripts
- 🤖 **AI Tools**: They have a tendency to overwrite or delete random content.
### How to Use
The result of all of this can be you asking yourself:
This plugin was not designed to accumulate all changes made inside an interval.
> Wait, didnt this note have more lines yesterday? 🤔
For example, if you add a block of text, delete it, re-add it, then delete it again in the same day, the changelog will show zero modifications instead of a bunch of additions and deletions.
This plugin tries it's best to help you answer that question. 😎
This is because this plugin only compares neighboring versions (intervals) directly, and if a block of text didn't exist in the previous interval and is also absent in the latest interval, zero changes have occurred.
- The recommended way to monitor for data loss is to simply frequently run the [Show Vault Changes since the Last Checkpoint](#show-vault-changes-since-the-last-checkpoint) command and check if the shown changes seem correct.
Consequently, if you add text that gets lost within the same interval, you can detect this data loss **not** by seeing a high 'lines deleted' count, but by noticing a lack of expected additions.
### How it works
A "Copy commit hash" context menu option is provided so that you can further investigate the commit tied to some suspicious version.
- This plugin was not designed to accumulate all changes made inside an interval.
If some lost data was never committed, it won't be recoverable by Git. So it's recommended to configure a frequent (< 5 minutes) auto-commit interval (no need to manually stage and commit files).
For example, if you add a block of text, delete it, re-add it, then delete it again in the same day, the changelog will show zero modifications instead of a bunch of additions and deletions.
But if some version of a file wasn't committed, you can still rely on the [File Recovery](https://help.obsidian.md/plugins/file-recovery) plugin, or the [Version history](https://help.obsidian.md/Obsidian+Sync/Version+history) feature to recover it.
This is because this plugin only compares neighboring versions (intervals) directly, and if a block of text didn't exist in the previous interval and is also absent in the latest interval, zero changes have occurred.
Use the [Version History Diff](https://github.com/kometenstaub/obsidian-version-history-diff) plugin for easier navigation through those versions.
Consequently, if you add text that gets lost within the same interval, you can detect this data loss **not** by seeing a high 'lines deleted' count, but by noticing a lack of expected additions.
It's also recommended to occasionally check the integrity of your repo. To do this, open a terminal at your vault's location and just run:
- A "Copy commit hash" context menu option is provided so that you can further investigate the commit tied to some suspicious version.
```bash
git fsck -full
```
- If some lost data was never committed, it won't be recoverable by Git. So it's recommended to configure a frequent (< 5 minutes) auto-commit interval (no need to manually stage and commit files).
But if some version of a file wasn't committed, you can still rely on the [File Recovery](https://help.obsidian.md/plugins/file-recovery) plugin, or the [Version history](https://help.obsidian.md/Obsidian+Sync/Version+history) feature to recover it.
Use the [Version History Diff](https://github.com/kometenstaub/obsidian-version-history-diff) plugin for easier navigation through those versions.
- It's also recommended to occasionally check the integrity of your repo. To do this, open a terminal at your vault's location and just run:
```bash
git fsck -full
```
## Limitations
⚠️ There are quite a few limitations, and some of them are simply the result of choosing this specific approach to changelog management.
- No meaningful way of tracking changes to canvas files.
- No mobile support yet.
- File changelog doesn't clear if opening a diff view but keeps showing stats for the previous note. This is intentional for quickly switching between versions but may result in showing stats for a closed note. This will be fixed in the future.
- Only status bar counts update live; other views refresh on each commit because of performance reasons.
- Assumes your vault has a linear commit & date history (which it should have). This plugin is not tested or made for repos with non-linear commit history.
- Git does not track changes inside other nested Git repositories—you should use proper Git submodules instead if you want to track changes for multiple repositories inside your vault.
- By Git design, files/folders specified in `.gitignore` aren't watched for changes.
- Git decides if a file is binary (non-text) or a text file by analyzing the file contents rather than looking at the file extension. If you rename a text file to have a `.png` extension, Git will still count its lines and treat it as a text file.
- If some data loss is only a few words/lines in a heavily edited file, you probably won't notice it. Even though those few lines could have been important.
- Interaction with submodules isn't tested yet!
## Roadmap
@ -135,47 +221,79 @@ git fsck -full
- [ ] Code cleanup and refactoring.
- [ ] Improve README.
- [ ] Folder stats in the Vault changelog view.
- [ ] Command to compare the current state of the vault (repo) to any point in history.
- [x] Command to compare any two points in the vault (repo) history.
- [ ] Extensive per-file type stats.
- [ ] Optimize computing stats performance.
- [ ] Integrate the status bar and the file changelog view with [Git plugin's](https://github.com/Vinzent03/obsidian-git) diff views.
- [ ] Notify if the amount of changes between neighboring commits exceeds a threshold.
- [ ] File & folder stats inside the File explorer view.
- [ ] Search & filtering features.
## Alternatives
If you don't want to depend on Git, check out the [Vault Changelog](https://github.com/philoserf/obsidian-vault-changelog) plugin.
If you don't want to depend on Git, check out the these alternative plugins:
- [Vault Changelog](https://github.com/philoserf/obsidian-vault-changelog) - tested and reliable, writes a changelog note to your vault
- [List Modified](https://github.com/franciskafieh/obsidian-list-modified) - popular, links all modified files meeting certain criteria to a note.
- [Edit History](https://github.com/antoniotejada/obsidian-edit-history) - similar to this plugin, but generates it's own history files instead of relying on other tools.
- [Time Machine](https://github.com/dsebastien/obsidian-time-machine) - experimental, relies on snapshots from the Obsidian's core "File recovery" plugin.
## FAQ
### Will this plugin alter my Git repository/config?
- Why is the File changelog view showing inaccurate history for some files?
- No. This plugin is intended to be read-only and does not alter any Git configurations.
However, it's in beta, so bugs are possible.
- Most common cases for this are: **The file had its file path changed (renamed/moved or one of its parent folders was renamed/moved)**...
### I have been using Obsidian for some time but don't have a Git repo set up. Can I still use this plugin to view the history of my vault?
1. and the change isn't committed yet.
- No. 😔
2. and was also significantly modified, so that the similarity of the old and new version went below the `File move/rename detection strictness` threshold, resulting in Git treating the file as a new file instead of a renamed/moved one.
3. but the only changes were letter capitalization changes, and now Git is saying that the file has no history. [Why?](https://github.com/shumadrid/obsidian-git-changelog/issues/3) (TLDR: Git is case sensitive, your file system might not be). To solve this:
1. Add an emoji (or anything) as a prefix in the name to all the affected files/folders in your vault (an easier way is to only prefix all the topmost folders).
2. Commit all the changes.
3. After committing, the files will be tracked with the newly capitalized file paths, and you can remove the emoji prefixes.
- Will this plugin alter my Git repository/config?
- No. This plugin is intended to be read-only and does not alter any Git configurations. However, it's in beta, so bugs are possible.
The only exception is if you explicitly click the `Apply` button for the `Difference detection algorithm` setting, which applies the selected algorithm to the `.git/config` file. But this setting is easily reversible.
- I have been using Obsidian for some time but don't have a Git repo set up. Can I still use this plugin to view the history of my vault?
- No. 😔
- After making substantial changes, the plugin is showing unusual stats.
- Try disabling all exclusion rules and see if it was some exclusion rule that was influencing the stats.
Example scenario: A folder that was marked as excluded is now moved to a different location, the existing rule no longer affects that folder, so the plugin is showing the files inside that folder as added instead of moved.
## Debugging
By default, debug messages for this plugin are hidden. They aren't intended for the user.
- By default, debug messages for this plugin are hidden. They aren't intended for the user.
To show them, enable `Verbose` mode in the console and run the following command:
To show them, enable `Verbose` mode in the console and run the following command:
```bash
window.DEBUG.enable('git-changelog');
```
```bash
window.DEBUG.enable('git-changelog');
```
For more details, refer to [this guide](https://github.com/mnaoumov/obsidian-dev-utils?tab=readme-ov-file#debugging).
- For more details, refer to [this guide](https://github.com/mnaoumov/obsidian-dev-utils?tab=readme-ov-file#debugging).
## Contributing
Feel free to submit a PR or a feature request. I'd especially appreciate help with styling and restructuring the code.
- Feel free to submit a PR or a feature request. I'd especially appreciate help with styling and restructuring the code.
This plugin is in beta, so please do report all bugs that you find.
- This plugin is in beta, so please do report all bugs that you find.
For easier development, [define](https://github.com/mnaoumov/generator-obsidian-plugin?tab=readme-ov-file#build-development-version) a `OBSIDIAN_CONFIG_DIR` variable and run `npm run dev`.
- For easier development, [define](https://github.com/mnaoumov/obsidian-dev-utils?tab=readme-ov-file#build-development-version) a `OBSIDIAN_CONFIG_FOLDER` variable and run `npm run dev`.
## Credits

View file

@ -86,10 +86,12 @@
"subtags",
"succ",
"Syncthing",
"texastoland",
"tsbuildinfo",
"tsdoc",
"tsdocs",
"tseslint",
"Uncollapsible",
"unregisters",
"vararg",
"varargs",

View file

@ -89,7 +89,8 @@ export default typescriptEslint.config(
'error',
{
ignore: [-1, 0, 1, 2],
ignoreDefaultValues: true
ignoreDefaultValues: true,
ignoreClassFieldInitialValues: true
}
],
'@typescript-eslint/explicit-function-return-type': [

View file

@ -5,6 +5,6 @@
"id": "git-changelog",
"isDesktopOnly": true,
"name": "Git Changelog",
"version": "0.4.0",
"minAppVersion": "1.7.2"
"version": "0.6.0",
"minAppVersion": "1.8.10"
}

3612
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
{
"name": "git-changelog",
"version": "0.4.0",
"version": "0.6.0",
"description": "Uses Git to display dynamic vault and file changelogs in the sidebar, useful for spotting data loss.",
"keywords": [],
"license": "MIT",
@ -37,20 +37,21 @@
"eslint-plugin-svelte": "^3.2.2",
"eslint-plugin-unicorn": "^57.0.0",
"globals": "^16.0.0",
"obsidian": "^1.8.7",
"obsidian-dev-utils": "^21.0.0",
"obsidian-typings": "^2.35.0",
"obsidian": "latest",
"obsidian-dev-utils": "26.4.0",
"obsidian-typings": "latest",
"prettier": "3.5.3",
"prettier-plugin-svelte": "^3.3.3",
"sass": "^1.83.4",
"simple-git": "^3.27.0",
"spacetime": "^7.8.0",
"svelte": "^5.23.1",
"svelte-eslint-parser": "^0.43.0",
"svelte-infinite": "^0.5.0",
"svelte-preprocess": "^6.0.3",
"type-fest": "^4.39.1",
"typescript": "^5.8.2",
"typescript-eslint": "^8.25.0",
"simple-git": "^3.27.0"
"typescript-eslint": "^8.25.0"
},
"overrides": {
"boolean": "npm:dry-uninstall"

View file

@ -1,3 +1,4 @@
import type { BuildOptions } from 'esbuild';
import type { CliTaskResult } from 'obsidian-dev-utils/ScriptUtils/CliUtils';
import {
@ -9,9 +10,10 @@ export async function buildWithSvelte(
developmentMode: boolean
): Promise<CliTaskResult> {
return await buildObsidianPlugin({
customEsbuildOptions: {
dropLabels: developmentMode ? undefined : ['DEV']
customizeEsbuildOptions: (options: BuildOptions) => {
options.dropLabels = developmentMode ? undefined : ['DEV'];
},
customEsbuildPlugins: [
{
name: 'add-condition',

View file

@ -1,8 +1,8 @@
import { getDirname } from 'obsidian-dev-utils/Path';
import { getFolderName } from 'obsidian-dev-utils/Path';
import { existsSync } from 'obsidian-dev-utils/ScriptUtils/NodeModules';
import {
execFromRoot,
getRootDir,
getRootFolder,
resolvePathFromRootSafe
} from 'obsidian-dev-utils/ScriptUtils/Root';
@ -11,7 +11,7 @@ export async function formatWithPrettier(rewrite: boolean): Promise<void> {
const prettierJsonPath = resolvePathFromRootSafe('.prettierrc.json');
if (!existsSync(prettierJsonPath)) {
const packageDirectory = getRootDir(getDirname(import.meta.url));
const packageDirectory = getRootFolder(getFolderName(import.meta.url));
if (!packageDirectory) {
throw new Error('Could not find package directory.');
}

View file

@ -1,28 +1,41 @@
import type { GitChangelogPluginTypes } from 'constants.ts';
import type { ObsidianGitPlugin } from 'gitPluginTypes.ts';
import type { Debouncer, PluginSettingTab } from 'obsidian';
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
import type { Debouncer } from 'obsidian';
import type { ExtractPluginSettingsWrapper } from 'obsidian-dev-utils/obsidian/Plugin/PluginTypesBase';
import type { GitChangelogSettings } from 'settings/settings.ts';
import type { SimpleGit } from 'simple-git';
import type { ReadonlyDeep } from 'type-fest';
import {
COMPARE_REPO_COMMITS_VIEW_CONFIG,
COMPARE_TO_CHECKPOINT_VIEW_CONFIG
} from 'constants.ts';
import { FileChangelogManager } from 'core/FileChangelogManager.ts';
import { runHashObjectEmptyTree } from 'core/gitOperations/runHashObjectEmptyTree.ts';
import { changelogGenerationSettingsChanged } from 'core/helper.ts';
import { VaultChangelogManager } from 'core/VaultChangelogManager.ts';
import { addContextMenuItems } from 'menu.ts';
import { debounce, ItemView, Notice } from 'obsidian';
import { debounce, Notice } from 'obsidian';
import { invokeAsyncSafely } from 'obsidian-dev-utils/Async';
import { PluginBase } from 'obsidian-dev-utils/obsidian/Plugin/PluginBase';
import { changelogGenerationSettingsChanged } from 'settings/helper.ts';
import { GitChangelogPluginSettings } from 'settings/settings.ts';
import { getTimeZone } from 'settings/ui/CustomTimeZone.ts';
import { GitChangelogSettingsManager } from 'settings/settingsManager.ts';
import { getLocaleToAssign } from 'settings/ui/CustomLocale.ts';
import {
gitPluginCompatibleVersion,
gitPluginTestedVersion
} from 'settings/ui/GitPluginWarning.ts';
import { handleReviewChangesReminderInterval } from 'settings/ui/ReviewChangesReminderInterval.ts';
import spacetime from 'spacetime';
import { TaskManager } from 'TaskManager.svelte.ts';
import { formatDateHour } from 'timeUtils.ts';
import { assertNotNull, removeCompareVersionsView } from 'utils.ts';
import { CompareRepoCommitsView } from 'Views/CompareRepoCommits/CompareRepoCommits.ts';
import { CompareToCheckpointView } from 'Views/CompareToCheckpoint/CompareToCheckpoint.ts';
import {
FILE_CHANGELOG_VIEW_CONFIG,
FileChangelogView
} from 'Views/FileChangelog/FileChangelog.ts';
import { getActiveGitRelativeFile, isDiffView } from 'Views/helper.ts';
import { getActiveGitRelativeFile, isDiffViewVisible } from 'Views/helper.ts';
import {
VAULT_CHANGELOG_VIEW_CONFIG,
VaultChangelogView
@ -38,26 +51,26 @@ import {
GitRepoMissingError
} from './types.ts';
export class GitChangelogPlugin extends PluginBase<GitChangelogPluginSettings> {
export class GitChangelogPlugin extends PluginBase<GitChangelogPluginTypes> {
public debouncedChangelogSettingsChangedCheck:
| Debouncer<
[
oldSettings: ReadonlyDeep<GitChangelogPluginSettings>,
newSettings: ReadonlyDeep<GitChangelogPluginSettings>
oldSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>,
newSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>
],
void
>
| undefined;
public gitPluginState = $state<GitPluginState>();
public gitRepoReady = $state<boolean>();
// Used for keeping relative interval labels like "today" and "yesterday" up to date
public currentDay = $state<string>();
/**
* If we were to persist this, it would be less flexible if the user changes his repo or the hashing algorithm and we would need to either manually have a database of all possible empty tree hashes or validate it in runtime
*/
public emptyTreeHash: string | undefined;
public gitRepoReady = $state<boolean>();
// Used for keeping relative interval labels like "today" and "yesterday" up to date
public dependenciesReady = $derived(
(this.gitPluginState === GitPluginState.Enabled ||
this.gitPluginState === GitPluginState.UntestedVersion) &&
@ -65,14 +78,31 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginSettings> {
);
public detectedTimeZone: string | undefined;
public detectedLocale: string | undefined;
public utcCurrentDateHour = $state<string>(
formatDateHour(spacetime.now('utc'))
); // In UTC so it doesn't depend on the timezone setting
public vaultChangelogManager = $state<VaultChangelogManager>();
public fileChangelogManager = $state<FileChangelogManager>();
public settingsOfComputedCache?: ChangelogGenerationSettings;
public statusBarStats?: StatusBarStats;
public cachedActiveGitFile: string | undefined;
public compareVersionsUtcNewerDate: string | undefined;
public compareVersionsUtcOlderDate: string | undefined;
public localeSafe = $state<string>('en-US'); // Properly loaded in onLayoutReady
public checkpointReminderNotice: Notice | undefined;
public get emptyTreeHashUnsafe(): string {
return assertNotNull(this.emptyTreeHash);
}
/**
* If we were to persist this, it would be less flexible if the user changes his repo or the hashing algorithm and we would need to either manually have a database of all possible empty tree hashes or validate it in runtime
*/
private emptyTreeHash: string | undefined;
public async addFileChangelogView(): Promise<void> {
await this.app.workspace.ensureSideLeaf(
FILE_CHANGELOG_VIEW_CONFIG.type,
@ -106,8 +136,16 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginSettings> {
this.consoleDebug(`Error:`, error.stack);
}
// eslint-disable-next-line no-magic-numbers
public displayNotice(message: string, timeout: number = 3 * 1000): void {
public displayNotice(
message: DocumentFragment | string,
// eslint-disable-next-line no-magic-numbers
timeout: number = 3 * 1000
): void {
if (message instanceof DocumentFragment) {
new Notice(message, timeout);
return;
}
new Notice(`${this.manifest.name}:\n${message}`, timeout);
}
@ -142,40 +180,60 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginSettings> {
}
}
public override async saveSettings(
newSettings: GitChangelogPluginSettings,
debounceOnSettingsSave = true
): Promise<void> {
const oldSettings = this.settings;
await super.saveSettings(newSettings);
if (debounceOnSettingsSave) {
this.debouncedChangelogSettingsChangedCheck?.(oldSettings, newSettings);
} else {
this.onSettingsSave(oldSettings, newSettings);
public async getEmptyTreeHash(): Promise<string> {
if (this.emptyTreeHash) {
return this.emptyTreeHash;
}
const git = await this.getGit();
const emptyTreeHash = await runHashObjectEmptyTree({ git });
this.emptyTreeHash ??= emptyTreeHash;
return this.emptyTreeHash;
}
protected override createPluginSettings(
data: unknown
): GitChangelogPluginSettings {
return new GitChangelogPluginSettings(data);
// We only pass the relevant settings for checking because if some invalid value was changed to some other invalid value, that means the default value is used in both cases and we discard that change
// eslint-disable-next-line @typescript-eslint/require-await
public override async onSaveSettings(
_newSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>,
_oldSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>,
skipCheck?: boolean
): Promise<void> {
// If the local setting was modified externally, we need to update the localeSafe property.
this.localeSafe = getLocaleToAssign(this);
if (skipCheck === true) {
return;
}
this.debouncedChangelogSettingsChangedCheck?.(_oldSettings, _newSettings);
}
protected override createPluginSettingsTab(): null | PluginSettingTab {
protected override createSettingsTab(): GitChangelogSettingsTab {
return new GitChangelogSettingsTab(this);
}
// Functions below are from obsidian-dev-utils (https://github.com/mnaoumov/obsidian-dev-utils/blob/main/src/obsidian/Plugin/PluginBase.ts)
protected override createSettingsManager(): GitChangelogSettingsManager {
return new GitChangelogSettingsManager(this);
}
protected override onloadComplete(): void {
// Runs when the plugin is unloaded.
this.register(() => {
this.debouncedChangelogSettingsChangedCheck?.cancel();
this.fileChangelogManager?.taskManager.abort();
this.vaultChangelogManager?.taskManager.abort();
this.statusBarStats?.destroy();
});
// Runs when the plugin is unloaded.
// eslint-disable-next-line @typescript-eslint/require-await
protected override async onunloadImpl(): Promise<void> {
this.debouncedChangelogSettingsChangedCheck?.cancel();
this.fileChangelogManager?.taskManager.abort();
this.vaultChangelogManager?.taskManager.abort();
this.statusBarStats?.destroy();
if (this.checkpointReminderNotice) {
this.checkpointReminderNotice.hide();
this.checkpointReminderNotice = undefined;
}
}
protected override async onloadImpl(): Promise<void> {
await super.onloadImpl();
this.registerView(VAULT_CHANGELOG_VIEW_CONFIG.type, (leaf) => {
return new VaultChangelogView(leaf, this);
});
@ -184,16 +242,33 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginSettings> {
return new FileChangelogView(leaf, this);
});
this.registerView(COMPARE_TO_CHECKPOINT_VIEW_CONFIG.type, (leaf) => {
return new CompareToCheckpointView(leaf, this);
});
this.registerView(COMPARE_REPO_COMMITS_VIEW_CONFIG.type, (leaf) => {
return new CompareRepoCommitsView({
leaf,
plugin: this,
utcOlderDate: assertNotNull(this.compareVersionsUtcOlderDate),
utcNewerDate: assertNotNull(this.compareVersionsUtcNewerDate)
});
});
addCommands(this);
addContextMenuItems(this);
this.debouncedChangelogSettingsChangedCheck = debounce(
(
oldSettings: GitChangelogPluginSettings,
newSettings: GitChangelogPluginSettings
oldSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>,
newSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>
) => {
this.onSettingsSave(oldSettings, newSettings);
this.onSaveSettingsCheck(oldSettings, newSettings);
},
// eslint-disable-next-line no-magic-numbers
700,
@ -202,6 +277,11 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginSettings> {
}
protected override async onLayoutReady(): Promise<void> {
// This is a temporary view, and shouldn't persist between sessions
removeCompareVersionsView(this);
this.localeSafe = getLocaleToAssign(this);
// These have to be initiated first.
this.vaultChangelogManager = new VaultChangelogManager({
plugin: this,
@ -212,12 +292,12 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginSettings> {
taskManager: new TaskManager(this)
});
if (this.settings.statusBarStats) {
if (this.settings.showStatusBarStats) {
this.initStatusBar();
}
this.registerEvent(
this.app.workspace.on('file-open', () => {
this.app.workspace.on('active-leaf-change', () => {
this.updateActiveGitFile();
})
);
@ -229,18 +309,19 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginSettings> {
})
);
// Every 5 minutes it checks if it's a new day in order to update the potentially outdated interval labels.
this.registerInterval(
window.setInterval(
() => {
const timezone = getTimeZone(
this.settings.changelogGenerationSettings,
this
);
this.currentDay = spacetime.now(timezone).format('day');
// Every minute it checks if it's a new hour (most common interval) in order to update the potentially outdated interval labels.
const utcCurrentDate = spacetime.now('utc');
// Svelte triggers updates only if the strings are different.
this.utcCurrentDateHour = formatDateHour(utcCurrentDate);
// Register minute interval for checkpoint reminders
invokeAsyncSafely(() => handleReviewChangesReminderInterval(this));
},
// eslint-disable-next-line no-magic-numbers
5 * 60 * 1000
60 * 1000
)
);
@ -254,70 +335,17 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginSettings> {
await this.addVaultChangelogView();
await this.addFileChangelogView();
const newSettings = this.settingsClone;
newSettings.firstStartup = false;
await this.saveSettings(newSettings, false);
await this.settingsManager.editAndSave(
(settings: GitChangelogSettings): void => {
settings.firstStartup = false;
}
);
}
// Also checks the status of the Git plugin
this.updateActiveGitFile();
}
/**
* Triggers events for the views to listen to instead of updating the changelogs directly from the settings so that if the views aren't active we don't do unnecessary computation.
* This allows us to check if relevant settings have changed and only then recompute changelogs, instead of recomputing after every single settings change.
*/
private onSettingsSave(
oldSettings: ReadonlyDeep<GitChangelogPluginSettings>,
newSettings: GitChangelogPluginSettings
): void {
try {
if (
changelogGenerationSettingsChanged({
newChangelogSettings: newSettings.changelogGenerationSettings,
oldChangelogSettings: oldSettings.changelogGenerationSettings,
plugin: this
})
) {
// The main settings, that trigger recalculation for all stats when they change.
this.app.workspace.trigger('git-changelog:generation-settings-changed');
} else {
if (
this.fileChangelogManager?.generationSettingsChanged(
oldSettings,
newSettings
) &&
this.cachedActiveGitFile
) {
this.app.workspace.trigger(
'git-changelog:file-changelog-generation-settings-changed'
);
}
if (
this.statusBarStats &&
StatusBarStats.generationSettingsChanged(oldSettings, newSettings) &&
this.cachedActiveGitFile
) {
this.app.workspace.trigger(
'git-changelog:status-bar-settings-changed'
);
}
if (
this.vaultChangelogManager?.generationSettingsChanged(
oldSettings,
newSettings
)
) {
this.app.workspace.trigger(
'git-changelog:vault-changelog-generation-settings-changed'
);
}
}
} catch {
/* Empty */
}
}
private setNewActiveGitFile(activeGitFile: string | undefined): void {
this.fileChangelogManager?.resetAndGetSignal(); // Does this belong inside the file changelog class?
this.cachedActiveGitFile = activeGitFile;
@ -336,17 +364,84 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginSettings> {
if (currentActiveGitFile) {
this.setNewActiveGitFile(currentActiveGitFile);
} else {
const currentActiveView =
this.app.workspace.getActiveViewOfType(ItemView);
// If a DiffView is active, don't clear the active git file, but keep it, so that the file changelog still shows stats for that previously active file. Only works if the diff view is also focused.
if (isDiffView(currentActiveView)) {
return;
}
} else if (
!isDiffViewVisible({
app: this.app
})
) {
// If a DiffView is visible, don't clear the active git file, but keep it, so that the file changelog still shows stats for that previously active file.
this.setNewActiveGitFile(undefined);
}
} catch {
/* Just do nothing */
}
}
/**
* Triggers events for the views to listen to instead of updating the changelogs directly from the settings so that if the views aren't active we don't do unnecessary computation.
* This allows us to check if relevant settings have changed and only then recompute changelogs, instead of recomputing after every single settings change.
*/
private onSaveSettingsCheck(
oldSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>,
newSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>
): void {
try {
if (
changelogGenerationSettingsChanged({
newSettings,
oldSettings
})
) {
// The main settings, that trigger recalculation for all stats when they change.
this.app.workspace.trigger('git-changelog:generation-settings-changed');
return;
}
if (
this.fileChangelogManager?.specificSettingsChanged(
oldSettings,
newSettings
) &&
this.cachedActiveGitFile
) {
this.app.workspace.trigger(
'git-changelog:file-changelog-generation-settings-changed'
);
}
// Handle destroying and initializing the status bar stats
if (this.settings.showStatusBarStats !== !!this.statusBarStats) {
const shouldEnableStatusBarStats = this.settings.showStatusBarStats;
if (shouldEnableStatusBarStats) {
this.initStatusBar();
} else {
this.statusBarStats?.destroy?.();
this.statusBarStats = undefined;
}
}
// Handle status bar settings changes
else if (
this.statusBarStats &&
StatusBarStats.generationSettingsChanged(oldSettings, newSettings) &&
this.cachedActiveGitFile
) {
this.app.workspace.trigger('git-changelog:status-bar-settings-changed');
}
if (
this.vaultChangelogManager?.specificSettingsChanged(
oldSettings,
newSettings
)
) {
this.app.workspace.trigger(
'git-changelog:vault-changelog-generation-settings-changed'
);
}
} catch {
/* Empty */
}

View file

@ -0,0 +1,154 @@
import type { GitChangelogPlugin } from 'GitChangelogPlugin.svelte.ts';
import type { PromiseResolve } from 'obsidian-dev-utils/Async';
import type { ModalOptionsBase } from 'obsidian-dev-utils/obsidian/Modals/ModalBase';
import type { CompareRepoCommitsViewState } from 'types.ts';
import { ButtonComponent, moment } from 'obsidian';
import { CssClass } from 'obsidian-dev-utils/CssClass';
import { ModalBase } from 'obsidian-dev-utils/obsidian/Modals/ModalBase';
import { SettingEx } from 'obsidian-dev-utils/obsidian/SettingEx';
import { assertNotNull } from 'utils.ts';
export class CompareVersionsModal extends ModalBase<
CompareRepoCommitsViewState | undefined,
ModalOptionsBase
> {
public plugin: GitChangelogPlugin;
// Date-time component automatically converts dates to the system timezone in the UI and stores them as UTC
private utcOlderDate: Date | undefined;
private utcNewerDate: Date;
private compareRepoCommitsViewEphemeralState:
| CompareRepoCommitsViewState
| undefined;
public constructor({
options,
resolve,
modalCssClass,
plugin,
utcOlderDateString,
utcNewerDateString
}: {
options: ModalOptionsBase;
resolve: PromiseResolve<CompareRepoCommitsViewState | undefined>;
modalCssClass: string;
plugin: GitChangelogPlugin;
utcOlderDateString: string | undefined;
utcNewerDateString: string | undefined;
}) {
super(options, resolve, modalCssClass);
this.plugin = plugin;
// Load the newer date from the previous modal or if this is the first time the user is comparing in this Obsidian session then assign the current date
this.utcNewerDate = utcNewerDateString
? new Date(utcNewerDateString)
: new Date();
if (utcOlderDateString) {
this.utcOlderDate = new Date(utcOlderDateString);
}
}
public override onClose(): void {
super.onClose();
this.resolve(this.compareRepoCommitsViewEphemeralState);
}
public override onOpen(): void {
super.onOpen();
this.contentEl.addClass('git-changelog-checkpoint-modal');
const titleElement = new SettingEx(this.contentEl);
titleElement.setName('Compare two vault states in git history');
titleElement.setDesc(
createFragment((fragment) => {
fragment.appendText(
`The nearest commit that came before the each specified date will be used.`
);
fragment.createEl('br');
fragment.appendText(
`Specify the dates in your system timezone (not the one configured in the plugin settings).`
);
})
);
this.createTimeInput({
text: 'Newer date',
onChange: (value) => {
this.utcNewerDate = value;
},
startValue: this.utcNewerDate
});
this.createTimeInput({
text: 'Older date',
onChange: (value) => {
this.utcOlderDate = value;
},
startValue: this.utcOlderDate
});
this.createCompareButton();
}
private createTimeInput({
onChange,
text,
startValue
}: {
onChange: (value: Date) => void;
text: string;
startValue: Date | undefined;
}): void {
const setting = new SettingEx(this.contentEl);
setting.setName(text).addDateTime((dateTime) => {
if (startValue) {
dateTime.setValue(startValue);
}
dateTime.onChange(onChange);
});
}
private validateDates(): string | undefined {
if (!this.utcOlderDate || !this.utcNewerDate) {
return 'Both dates must be selected.';
}
// Try parsing both dates
if (!moment.isDate(this.utcOlderDate)) {
return 'Invalid start date.';
}
if (!moment.isDate(this.utcNewerDate)) {
return 'Invalid end date.';
}
// Check if the older date is before the newer date
return this.utcOlderDate < this.utcNewerDate
? undefined
: 'Older date must be before the newer date.';
}
private createCompareButton(): void {
const approveButton = new ButtonComponent(this.contentEl);
approveButton.setButtonText('Compare');
approveButton.setCta();
approveButton.onClick(() => {
const validationMessage = this.validateDates();
if (validationMessage) {
this.plugin.displayNotice(validationMessage);
} else {
// Input dates are in UTC, so that git can process them accurately.
this.compareRepoCommitsViewEphemeralState = {
utcOlderDate: assertNotNull(this.utcOlderDate).toISOString(),
utcNewerDate: this.utcNewerDate.toISOString()
};
this.close();
}
});
approveButton.setClass(CssClass.OkButton);
}
}

View file

@ -0,0 +1,212 @@
<script lang="ts">
import type { VaultChangelogEntry } from 'core/ChangelogEntry.svelte.ts';
import type GitChangelogPlugin from 'main.ts';
import {
COMPARED_VERSIONS_DATE_SEPARATOR_ICON,
COPY_COMMIT_HASH_ICON,
TOGGLE_FILES_SUMMARY_OPTION_ICON
} from 'constants.ts';
import { findFirstCommitBefore } from 'core/gitOperations/findFirstCommitBefore.ts';
import { runRepoDiff } from 'core/gitOperations/runRepoDiff.ts';
import { setIcon } from 'obsidian';
import { CssClass } from 'obsidian-dev-utils/CssClass';
import { getTimeZone } from 'settings/ui/CustomTimeZone.ts';
import { onDestroy, onMount } from 'svelte';
import { FileSummariesDisplayMode } from 'types.ts';
import { assertNotNull } from 'utils.ts';
import DependenciesStatusCheck from 'Views/components/DependenciesStatusCheck.svelte';
import { formatFullDate } from 'Views/formatters.ts';
import VersionComponent from 'Views/VaultChangelog/components/Version.svelte';
// eslint-disable-next-line capitalized-comments
// svelte-ignore non_reactive_update
enum CompareVersionsState {
Loading = 'Loading...',
OnCheckpointCommit = 'Specified dates fall inside the same commit.',
BeforeInitialCommit = 'Both dates are before the initial commit.',
NoChanges = 'The versions are the same.',
Loaded = 'Loaded',
UnknownError = 'Unknown error occurred.'
}
interface Properties {
plugin: GitChangelogPlugin;
closeView: () => void;
utcOlderDate: string;
utcNewerDate: string;
}
const { plugin, closeView, utcOlderDate, utcNewerDate }: Properties =
$props();
let filesSummaryDisplayModeButton = $state<HTMLElement>();
let version = $state<VaultChangelogEntry>();
let timezoneAdjustedOlderDate = $state<string>();
let timezoneAdjustedNewerDate = $state<string>();
let compareVersionsState = $state<CompareVersionsState>(
CompareVersionsState.Loading
);
const showFilesCountSummariesMode = FileSummariesDisplayMode.TextAndBinary;
let arrowIconElement = $state<HTMLElement>();
let sameCommitIconElement = $state<HTMLElement>();
onMount(async () => {
try {
const git = await plugin.getGit();
const timeZone = getTimeZone(plugin);
const upperCommit = await findFirstCommitBefore({
abortSignal: new AbortController().signal,
isoString: utcNewerDate,
git,
timeZone
});
if (!upperCommit) {
// Since the newer date must be newer than the older date and the newer date is already older than the first commit, that means both dates belong to the time before the repository was created and therefore when comparing the state of the repository between these two dates, the state is the same: non-existent.
compareVersionsState = CompareVersionsState.BeforeInitialCommit;
return;
}
let lowerCommitIsEmptyTree = false;
let lowerCommit = await findFirstCommitBefore({
abortSignal: new AbortController().signal,
isoString: utcOlderDate,
git,
timeZone
});
if (!lowerCommit) {
lowerCommitIsEmptyTree = true;
lowerCommit = {
hash: await plugin.getEmptyTreeHash(),
// This date won't be used in this scenario, so we can set it to anything.
timeZoneAdjustedDate: upperCommit.timeZoneAdjustedDate
};
}
timezoneAdjustedNewerDate = formatFullDate(
upperCommit.timeZoneAdjustedDate.toNativeDate(),
plugin.localeSafe,
getTimeZone(plugin)
);
if (lowerCommit.hash === upperCommit.hash) {
compareVersionsState = CompareVersionsState.OnCheckpointCommit;
// Show the single date of the commit if this is the case
return;
}
// Potentially indicate that we're comparing to empty state because the provided older date is older than the repository
timezoneAdjustedOlderDate = lowerCommitIsEmptyTree
? 'Beginning'
: formatFullDate(
lowerCommit.timeZoneAdjustedDate.toNativeDate(),
plugin.localeSafe,
getTimeZone(plugin)
);
version = await runRepoDiff({
git,
oldCommit: lowerCommit,
newCommit: upperCommit,
abortSignal: new AbortController().signal,
convertToIncludeList: plugin.settings.convertToIncludeList,
diffAlgorithm: plugin.settings.diffAlgorithm,
excludeFilesAndFoldersLines:
plugin.settings.excludeFilesAndFoldersLines,
enableExclusionList: plugin.settings.enableExclusionList,
ignoreBlankLines: plugin.settings.ignoreBlankLines,
renameDetectionStrictness: plugin.settings.renameDetectionStrictness,
renameLimit: plugin.settings.renameLimit,
whitespaceIgnoreMode: plugin.settings.whitespaceIgnoreMode,
emptyTreeHash: await plugin.getEmptyTreeHash(),
plugin
});
// If you pass identical commit hashes to git diff, or if there are no changes, it will just output nothing.
compareVersionsState = version
? CompareVersionsState.Loaded
: CompareVersionsState.NoChanges;
} catch {
compareVersionsState = CompareVersionsState.UnknownError;
}
});
$effect(() => {
if (arrowIconElement) {
setIcon(arrowIconElement, COMPARED_VERSIONS_DATE_SEPARATOR_ICON);
}
if (sameCommitIconElement) {
setIcon(sameCommitIconElement, COPY_COMMIT_HASH_ICON);
}
if (filesSummaryDisplayModeButton) {
setIcon(filesSummaryDisplayModeButton, TOGGLE_FILES_SUMMARY_OPTION_ICON);
}
});
onDestroy(() => {
filesSummaryDisplayModeButton = undefined;
arrowIconElement = undefined;
sameCommitIconElement = undefined;
});
</script>
<div class="git-changelog-view">
<div class="nav-header git-changelog-force-center">
<div class="nav-buttons-container git-changelog-top-margin">
<button type="button" class={CssClass.OkButton} onclick={closeView}>
Exit comparison
</button>
</div>
</div>
<DependenciesStatusCheck {plugin}>
<div class="git-changelog-compared-versions-container">
{#if timezoneAdjustedOlderDate && (compareVersionsState === CompareVersionsState.Loaded || compareVersionsState === CompareVersionsState.NoChanges)}
<div class="git-changelog-compared-version-title">
{timezoneAdjustedOlderDate}
</div>
<span
class="git-changelog-compared-version-title-arrow icon git-changelog-stat-color"
bind:this={arrowIconElement}
></span>
{/if}
<div class="git-changelog-compared-version-title">
<!-- ' ' because it serves as a space placeholder -->
{timezoneAdjustedNewerDate &&
compareVersionsState !== CompareVersionsState.Loading &&
compareVersionsState !== CompareVersionsState.UnknownError
? timezoneAdjustedNewerDate
: ' '}
</div>
</div>
<div class="nav-files-container">
{#if compareVersionsState === CompareVersionsState.Loaded}
<VersionComponent
version={assertNotNull(version)}
{plugin}
hideTitleAndMakeUncollapsible={true}
showFilesCountSummaries={showFilesCountSummariesMode}
/>
{:else}
<div class="pane-empty git-changelog-git-issue">
{#if compareVersionsState === CompareVersionsState.OnCheckpointCommit}
<span
class="icon git-changelog-on-checkpoint-commit-icon"
bind:this={sameCommitIconElement}
></span>
{/if}
{compareVersionsState}
</div>
{/if}
</div>
</DependenciesStatusCheck>
</div>
<style lang="scss">
</style>

View file

@ -0,0 +1,87 @@
import type GitChangelogPlugin from 'main.ts';
import type { WorkspaceLeaf } from 'obsidian';
import type { CompareRepoCommitsViewState } from 'types.ts';
import { COMPARE_REPO_COMMITS_VIEW_CONFIG } from 'constants.ts';
import { ItemView } from 'obsidian';
import { mount, unmount } from 'svelte';
import { removeCompareVersionsView } from 'utils.ts';
import CompareRepoCommitsComponent from 'Views/CompareRepoCommits/CompareRepoCommits.svelte';
import { registerCloseViewIfDeferred } from 'Views/helper.ts';
export class CompareRepoCommitsView
extends ItemView
implements CompareRepoCommitsViewState
{
public plugin: GitChangelogPlugin;
public utcOlderDate: string;
public utcNewerDate: string;
private _view: CompareRepoCommitsComponent | undefined = undefined;
public constructor({
leaf,
plugin,
utcOlderDate,
utcNewerDate
}: {
leaf: WorkspaceLeaf;
plugin: GitChangelogPlugin;
utcOlderDate: string;
utcNewerDate: string;
}) {
super(leaf);
this.plugin = plugin;
this.utcOlderDate = utcOlderDate;
this.utcNewerDate = utcNewerDate;
this.navigation = false;
}
public async destroy(): Promise<void> {
if (this._view) {
await unmount(this._view);
this._view = undefined;
}
}
public override getDisplayText(): string {
return COMPARE_REPO_COMMITS_VIEW_CONFIG.name;
}
public override getIcon(): string {
return COMPARE_REPO_COMMITS_VIEW_CONFIG.icon;
}
public override getViewType(): string {
return COMPARE_REPO_COMMITS_VIEW_CONFIG.type;
}
public override async onClose(): Promise<void> {
await this.destroy();
return super.onClose();
}
// eslint-disable-next-line @typescript-eslint/require-await
public override async onOpen(): Promise<void> {
this._view = mount(CompareRepoCommitsComponent, {
props: {
plugin: this.plugin,
closeView: () => {
// Await this.close();
removeCompareVersionsView(this.plugin);
},
utcOlderDate: this.utcOlderDate,
utcNewerDate: this.utcNewerDate
},
target: this.contentEl
}) as CompareRepoCommitsComponent;
registerCloseViewIfDeferred(this, this.plugin);
}
public override onunload(): void {
super.onunload();
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.destroy();
}
}

View file

@ -0,0 +1,276 @@
<script lang="ts">
import type { VaultChangelogEntry } from 'core/ChangelogEntry.svelte.ts';
import type GitChangelogPlugin from 'main.ts';
import type { GitChangelogSettings } from 'settings/settings.ts';
import {
COMPARED_VERSIONS_DATE_SEPARATOR_ICON,
COPY_COMMIT_HASH_ICON,
TOGGLE_FILES_SUMMARY_OPTION_ICON
} from 'constants.ts';
import { getCommitTimestampOrUndefined } from 'core/gitOperations/getCommitTimestamp.ts';
import { runRepoDiff } from 'core/gitOperations/runRepoDiff.ts';
import { setIcon } from 'obsidian';
import { CssClass } from 'obsidian-dev-utils/CssClass';
import { getTimeZone } from 'settings/ui/CustomTimeZone.ts';
import { onDestroy, onMount } from 'svelte';
import { FileSummariesDisplayMode } from 'types.ts';
import { assertNotNull } from 'utils.ts';
import DependenciesStatusCheck from 'Views/components/DependenciesStatusCheck.svelte';
import { formatFullDate } from 'Views/formatters.ts';
import VersionComponent from 'Views/VaultChangelog/components/Version.svelte';
// eslint-disable-next-line capitalized-comments
// svelte-ignore non_reactive_update
enum ModalCheckpointState {
Loading = 'Loading...',
OnCheckpointCommit = 'No commits occurred since the last checkpoint.',
NoCommits = 'No commits in the repository.',
NoCheckpoints = 'No checkpoints yet.',
CheckpointCommitNoLongerExists = 'The commit tied to the last checkpoint no longer exists or the checkpoint value is corrupted.',
NoChanges = 'No committed included changes since the last checkpoint.',
Loaded = 'Loaded',
UnknownError = 'Unknown error occurred.'
}
interface Properties {
plugin: GitChangelogPlugin;
closeView: () => void;
}
const { plugin, closeView }: Properties = $props();
let filesSummaryDisplayModeButton = $state<HTMLElement>();
let version = $state<VaultChangelogEntry>();
let startingCheckpointDate = $state<string>();
let latestStateDate = $state<string>();
let upperCommitHash: string | undefined;
let modalCheckpointState = $state<ModalCheckpointState>(
ModalCheckpointState.Loading
);
let approveButtonText = $state<string>('Loading...');
let setCta = $state<boolean>(false);
let showFilesCountSummariesMode = $state(
FileSummariesDisplayMode.TextAndBinary
);
let arrowIconElement = $state<HTMLElement>();
let onCheckpointCommitIconElement = $state<HTMLElement>();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function toggleFilesSummaryOption(): void {
showFilesCountSummariesMode =
showFilesCountSummariesMode === FileSummariesDisplayMode.Total
? FileSummariesDisplayMode.TextAndBinary
: FileSummariesDisplayMode.Total;
}
async function onApproveButtonClick(event: MouseEvent): Promise<void> {
event.stopPropagation();
// UpperCommitHash could be cleaned up
const checkpointToSave = upperCommitHash;
closeView();
if (checkpointToSave) {
await plugin.settingsManager.editAndSave(
(settings: GitChangelogSettings): void => {
// We only save the latest commit as a new checkpoint if the user closes the temporary view by clicking "approve".
// Otherwise we don't change anything.
settings.checkpointCommits.push(checkpointToSave);
}
);
}
}
onMount(async () => {
try {
const git = await plugin.getGit();
const upperCommit = await getCommitTimestampOrUndefined({
abortSignal: new AbortController().signal,
git,
timeZone: getTimeZone(plugin)
});
if (!upperCommit) {
// If the repo has no commits, git will throw this error:
// "Fatal: your current branch 'main' does not have any commits yet"
// And the upperCommit will be undefined.
modalCheckpointState = ModalCheckpointState.NoCommits;
approveButtonText = 'Close';
// Don't show approve button, because if upperCommit doesn't exist, then that means there are no commits in the repo, so we don't have anything to save as a checkpoint anyway.
return;
}
// Save this because if the user clicks "approve" we need to register the latest commit as the latest checkpoint.
// We can't depend on the version.commitHash because version might not get computed in certain states (most common scenario is when there are no previous checkpoints).
upperCommitHash = upperCommit.hash;
const lowerCommitHash = plugin.settings.checkpointCommits.at(-1);
if (!lowerCommitHash) {
// There are no checkpoints to compare to.
modalCheckpointState = ModalCheckpointState.NoCheckpoints;
setCta = true;
approveButtonText = 'Create first checkpoint';
return;
}
if (lowerCommitHash === upperCommit.hash) {
modalCheckpointState = ModalCheckpointState.OnCheckpointCommit;
// Do not show the "approve" button because there is no point in registering the same commit as the last checkpoint.
approveButtonText = 'Close';
// Show the date of the latest commit if this is the case
latestStateDate = formatFullDate(
upperCommit.timeZoneAdjustedDate.toNativeDate(),
plugin.localeSafe,
getTimeZone(plugin)
);
return;
}
const lowerCommit = await getCommitTimestampOrUndefined({
abortSignal: new AbortController().signal,
commitHash: lowerCommitHash,
git,
timeZone: getTimeZone(plugin)
});
if (!lowerCommit) {
// The passed commit hash was corrupted (that's possible because it's read from data.json) or the commit no longer exists (is deleted from repo).
// If it's some other error like GitPluginMissingError, then that will be handled and displayed over this in DependenciesStatusCheck anyway, so it doesn't need to be accurate here
modalCheckpointState =
ModalCheckpointState.CheckpointCommitNoLongerExists;
setCta = true;
approveButtonText = 'Create new checkpoint';
return;
}
startingCheckpointDate = formatFullDate(
lowerCommit.timeZoneAdjustedDate.toNativeDate(),
plugin.localeSafe,
getTimeZone(plugin)
);
version = await runRepoDiff({
git,
oldCommit: lowerCommit,
newCommit: upperCommit,
abortSignal: new AbortController().signal,
convertToIncludeList: plugin.settings.convertToIncludeList,
diffAlgorithm: plugin.settings.diffAlgorithm,
excludeFilesAndFoldersLines:
plugin.settings.excludeFilesAndFoldersLines,
ignoreBlankLines: plugin.settings.ignoreBlankLines,
enableExclusionList: plugin.settings.enableExclusionList,
renameDetectionStrictness: plugin.settings.renameDetectionStrictness,
renameLimit: plugin.settings.renameLimit,
whitespaceIgnoreMode: plugin.settings.whitespaceIgnoreMode,
emptyTreeHash: await plugin.getEmptyTreeHash(),
plugin
});
latestStateDate = formatFullDate(
upperCommit.timeZoneAdjustedDate.toNativeDate(),
plugin.localeSafe,
getTimeZone(plugin)
);
// If you pass identical commit hashes to git diff, or if there are no changes, it will just output nothing.
modalCheckpointState = version
? ModalCheckpointState.Loaded
: ModalCheckpointState.NoChanges;
setCta = true;
approveButtonText = 'Create new checkpoint';
} catch {
modalCheckpointState = ModalCheckpointState.UnknownError;
approveButtonText = 'Close';
}
});
$effect(() => {
if (arrowIconElement) {
setIcon(arrowIconElement, COMPARED_VERSIONS_DATE_SEPARATOR_ICON);
}
if (onCheckpointCommitIconElement) {
setIcon(onCheckpointCommitIconElement, COPY_COMMIT_HASH_ICON);
}
if (filesSummaryDisplayModeButton) {
setIcon(filesSummaryDisplayModeButton, TOGGLE_FILES_SUMMARY_OPTION_ICON);
}
});
onDestroy(() => {
filesSummaryDisplayModeButton = undefined;
arrowIconElement = undefined;
onCheckpointCommitIconElement = undefined;
});
</script>
<div class="git-changelog-view">
<!-- {#if !compactMode} -->
<div class="nav-header git-changelog-force-center">
<div class="nav-buttons-container git-changelog-top-margin">
<button
type="submit"
disabled={modalCheckpointState === ModalCheckpointState.Loading}
class={`${setCta ? 'mod-cta ' : ''}${CssClass.OkButton}`}
onclick={onApproveButtonClick}
>
{approveButtonText}
</button>
</div>
</div>
<DependenciesStatusCheck {plugin}>
<div class="git-changelog-compared-versions-container">
{#if startingCheckpointDate && (modalCheckpointState === ModalCheckpointState.Loaded || modalCheckpointState === ModalCheckpointState.NoChanges)}
<div class="git-changelog-compared-version-title">
{startingCheckpointDate}
</div>
<span
class="git-changelog-compared-version-title-arrow icon git-changelog-stat-color"
bind:this={arrowIconElement}
></span>
{/if}
<div class="git-changelog-compared-version-title">
<!-- ' ' because it serves as a space placeholder -->
{latestStateDate &&
modalCheckpointState !== ModalCheckpointState.Loading &&
modalCheckpointState !== ModalCheckpointState.UnknownError
? latestStateDate
: ' '}
</div>
</div>
<div class="nav-files-container">
{#if modalCheckpointState === ModalCheckpointState.Loaded}
<VersionComponent
version={assertNotNull(version)}
{plugin}
hideTitleAndMakeUncollapsible={true}
showFilesCountSummaries={showFilesCountSummariesMode}
/>
{:else}
<div class="pane-empty git-changelog-git-issue">
{#if modalCheckpointState === ModalCheckpointState.OnCheckpointCommit}
<span
class="icon git-changelog-on-checkpoint-commit-icon"
bind:this={onCheckpointCommitIconElement}
></span>
{/if}
{modalCheckpointState}
</div>
{/if}
</div>
</DependenciesStatusCheck>
</div>
<style lang="scss">
</style>

View file

@ -0,0 +1,70 @@
import type GitChangelogPlugin from 'main.ts';
import type { WorkspaceLeaf } from 'obsidian';
import { COMPARE_TO_CHECKPOINT_VIEW_CONFIG } from 'constants.ts';
import { ItemView } from 'obsidian';
import { mount, unmount } from 'svelte';
import { removeCompareVersionsView } from 'utils.ts';
import CompareToCheckpointComponent from 'Views/CompareToCheckpoint/CompareToCheckpoint.svelte';
import { registerCloseViewIfDeferred } from 'Views/helper.ts';
/**
* This was originally a modal, but user should also be able to click on the changes to inspect them, so it was migrated to a temporary view.
*/
export class CompareToCheckpointView extends ItemView {
public plugin: GitChangelogPlugin;
private _view: CompareToCheckpointComponent | undefined = undefined;
public constructor(leaf: WorkspaceLeaf, plugin: GitChangelogPlugin) {
super(leaf);
this.plugin = plugin;
this.navigation = false;
// This.closeable = true;
}
public async destroy(): Promise<void> {
if (this._view) {
await unmount(this._view);
this._view = undefined;
}
}
public override getDisplayText(): string {
return COMPARE_TO_CHECKPOINT_VIEW_CONFIG.name;
}
public override getIcon(): string {
return COMPARE_TO_CHECKPOINT_VIEW_CONFIG.icon;
}
public override getViewType(): string {
return COMPARE_TO_CHECKPOINT_VIEW_CONFIG.type;
}
public override async onClose(): Promise<void> {
await this.destroy();
return super.onClose();
}
// eslint-disable-next-line @typescript-eslint/require-await
public override async onOpen(): Promise<void> {
this._view = mount(CompareToCheckpointComponent, {
props: {
plugin: this.plugin,
closeView: () => {
// Await this.close();
removeCompareVersionsView(this.plugin);
}
},
target: this.contentEl
}) as CompareToCheckpointComponent;
registerCloseViewIfDeferred(this, this.plugin);
}
public override onunload(): void {
super.onunload();
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.destroy();
}
}

View file

@ -2,6 +2,9 @@
import type { GitChangelogPlugin } from 'GitChangelogPlugin.svelte.ts';
import type { EventRef } from 'obsidian';
import { INFO_TOOLTIP_ICON } from 'constants.ts';
import { runCheckIgnore } from 'core/gitOperations/runCheckIgnore.ts';
import { setIcon } from 'obsidian';
import { onDestroy, untrack } from 'svelte';
import { LoaderState } from 'svelte-infinite';
import { assertNotNull } from 'utils.ts';
@ -31,12 +34,14 @@
let settingsChangedReference: EventRef;
let activeFileChangedReference: EventRef;
let infoTooltipIcon = $state<HTMLElement>();
const changelogManager = $derived(plugin.fileChangelogManager);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call
const loaderState = new LoaderState();
let intervalAdjective = $state<string>();
const changelogState = $derived.by(() => {
let changelogState = $derived.by(() => {
if (!changelogManager) {
return FileChangelogState.Initializing;
}
@ -57,10 +62,43 @@
if (!plugin.cachedActiveGitFile) {
return FileChangelogState.NoMarkdownFileOpen;
}
return FileChangelogState.EmptyHistory;
//
untrack(() => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
checkFileInGitIgnore();
});
// Set a loading state while checkFileInGitIgnore is in progress
return FileChangelogState.Recomputing;
});
// Const fileInGitIgnore = $state<boolean>();
// If the file git log yielded no entries, check if it's because the file is ignored by git, or if it's just a new file with no history. Should be instant so no visible UI mismatch.
async function checkFileInGitIgnore(): Promise<void> {
if (!plugin.cachedActiveGitFile || !changelogManager) {
return;
}
const abortSignal = changelogManager.taskManager.getAbortSignal();
const cachedActiveGitFile = plugin.cachedActiveGitFile;
await changelogManager.taskManager.enqueueAndWait(async () => {
try {
const git = await plugin.getGit();
const isIgnored = await runCheckIgnore({
abortSignal,
activeGitFile: cachedActiveGitFile,
git
});
changelogState = isIgnored
? FileChangelogState.GitIgnoredFileOpen
: FileChangelogState.EmptyHistory;
} catch {
changelogState = FileChangelogState.EmptyHistory;
}
});
}
let fileChangelogSettingsChangedReference: EventRef;
headChangeReference = plugin.app.workspace.on(
@ -100,6 +138,15 @@
}
});
$effect(() => {
if (infoTooltipIcon) {
setIcon(
infoTooltipIcon,
assertNotNull(infoTooltipIcon.getAttr('data-icon'))
);
}
});
$effect.pre(() => {
setIntervalAdjective();
});
@ -162,7 +209,25 @@
{:else if changelogState === FileChangelogState.NoMarkdownFileOpen}
<div class="pane-empty">No file opened.</div>
{:else if changelogState === FileChangelogState.EmptyHistory}
<div class="pane-empty">File has no Git history.</div>
<div class="pane-empty">
<div>File has no Git history.</div>
<div class="git-changelog-row">
<div
bind:this={infoTooltipIcon}
data-icon={INFO_TOOLTIP_ICON}
aria-label="Due to Git limitations, it doesn't show the history of files that had their:
1. file path changed without the changes being committed.
2. file path changes be capitalization changes only."
class="icon git-changelog-tooltip-icon"
></div>
<a
href="https://github.com/shumadrid/obsidian-git-changelog?tab=readme-ov-file#faq"
class="external-link git-changelog-read-more">Read more</a
>
</div>
</div>
{:else if changelogState === FileChangelogState.GitIgnoredFileOpen}
<div class="pane-empty">File is ignored by Git.</div>
{/if}
<!-- if changelogState === FileChangelogState.Initializing, show nothing -->
</div>
@ -170,4 +235,18 @@
</div>
<style lang="scss">
.git-changelog-tooltip-icon {
margin-top: var(--size-4-1);
}
.git-changelog-read-more {
font-size: var(--font-small);
}
.git-changelog-row {
display: flex;
gap: var(--size-4-1);
align-items: center;
justify-content: center;
}
</style>

View file

@ -58,6 +58,7 @@ export class FileChangelogView extends ItemView {
}
public override onunload(): void {
super.onunload();
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.destroy();
}

View file

@ -5,6 +5,7 @@
import { OPEN_FILE_ICON } from 'constants.ts';
import { mayTriggerChangelogMenu } from 'menu.ts';
import { setIcon } from 'obsidian';
import { getTimeZone } from 'settings/ui/CustomTimeZone.ts';
import { DiffFileStatus } from 'types.ts';
import { assertNotNull } from 'utils.ts';
import DiffStatsComponent from 'Views/components/DiffStats.svelte';
@ -26,6 +27,19 @@
let openFileButton = $state<HTMLElement>();
const formattedVersionDateLabel = $derived.by(() => {
const currentDate = plugin.utcCurrentDateHour;
const locale = plugin.localeSafe;
return composeVersionTitle({
interval: plugin.settings.fileChangelogInterval,
dayStartHour: plugin.settings.dayStartHour,
locale,
timeZone: getTimeZone(plugin),
utcCurrentDateHour: currentDate,
timeZoneAdjustedEntryDate: entry.timeZoneAdjustedDate
});
});
function primaryClick(event: MouseEvent): void {
event.stopPropagation();
@ -33,8 +47,7 @@
changelogFileClick({
// Plugin.emptyTreeHash is guaranteed to be initialized. Git plugin throws an error when you pass Plugin.emptyTreeHash but I haven't been able to work around it and it doesn't affect usability.
aReference:
previousEntry?.commitHash ?? assertNotNull(plugin.emptyTreeHash),
aReference: previousEntry?.commitHash ?? plugin.emptyTreeHashUnsafe,
bReference: entry.commitHash,
event,
file: entry,
@ -73,17 +86,6 @@
})
);
}
const formattedVersionDateLabel = $derived.by(() => {
// CurrentDay just used to trigger updates
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const currentDay = plugin.currentDay;
return composeVersionTitle({
interval: plugin.settings.fileChangelogInterval,
plugin,
timezoneAdjustedEntryDate: entry.timezoneAdjustedDate
});
});
</script>
<!-- svelte-ignore a11y_no_static_element_interactions -->

View file

@ -2,12 +2,13 @@
// Import { SimpleGit } from "src/gitManager/simpleGit";
import type GitChangelogPlugin from 'main.ts';
import type { EventRef } from 'obsidian';
import type { GitChangelogSettings } from 'settings/settings.ts';
import { TOGGLE_FILES_SUMMARY_OPTION_ICON } from 'constants.ts';
import { setIcon } from 'obsidian';
import { onDestroy, untrack } from 'svelte';
import { LoaderState } from 'svelte-infinite';
import { FilesSummariesDisplayMode } from 'types.ts';
import { FileSummariesDisplayMode } from 'types.ts';
import { assertNotNull } from 'utils.ts';
import { getIntervalAdjectiveString } from 'Views/formatters.ts';
@ -141,16 +142,17 @@
collapseButton = undefined;
});
function toggleFilesSummaryOption(): void {
async function toggleFilesSummaryOption(): Promise<void> {
showFilesCountSummariesMode =
showFilesCountSummariesMode === FilesSummariesDisplayMode.Total
? FilesSummariesDisplayMode.TextAndBinary
: FilesSummariesDisplayMode.Total;
showFilesCountSummariesMode === FileSummariesDisplayMode.Total
? FileSummariesDisplayMode.TextAndBinary
: FileSummariesDisplayMode.Total;
const newSettings = plugin.settingsClone;
newSettings.fileSummariesDisplayMode = showFilesCountSummariesMode;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
plugin.saveSettings(newSettings);
await plugin.settingsManager.editAndSave(
(settings: GitChangelogSettings): void => {
settings.fileSummariesDisplayMode = showFilesCountSummariesMode;
}
);
}
function toggleCollapsedState(): void {
@ -167,7 +169,7 @@
entry.isCollapsed = !everythingCollapsed;
} else {
plugin.displayNotice(
`Too many entries. Can't expand all because of performance reasons.`,
`Too many versions. Unable to expand them all because of the impact on performance.`,
// eslint-disable-next-line no-magic-numbers
1500
);
@ -206,7 +208,7 @@
data-icon={TOGGLE_FILES_SUMMARY_OPTION_ICON}
aria-disabled={changelogState !== VaultChangelogState.HasEntries}
aria-label={showFilesCountSummariesMode ===
FilesSummariesDisplayMode.Total
FileSummariesDisplayMode.Total
? 'Text/media summary stats'
: 'Total files summary stats'}
bind:this={filesSummaryDisplayModeButton}

View file

@ -57,6 +57,7 @@ export class VaultChangelogView extends ItemView {
}
public override onunload(): void {
super.onunload();
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.destroy();
}

View file

@ -54,8 +54,7 @@
if (!isClickable) return;
changelogFileClick({
aReference:
previousVersionCommitHash ?? assertNotNull(plugin.emptyTreeHash),
aReference: previousVersionCommitHash ?? plugin.emptyTreeHashUnsafe,
bReference: currentVersionCommitHash,
event,
file,

View file

@ -3,8 +3,9 @@
import type GitChangelogPlugin from 'main.ts';
import { mayTriggerChangelogMenu } from 'menu.ts';
import { getTimeZone } from 'settings/ui/CustomTimeZone.ts';
import { slide } from 'svelte/transition';
import { FilesSummariesDisplayMode } from 'types.ts';
import { FileSummariesDisplayMode } from 'types.ts';
import { composeVersionTitle } from 'Views/formatters.ts';
import { VaultChangelogView } from 'Views/VaultChangelog/VaultChangelog.ts';
@ -14,20 +15,29 @@
interface Properties {
plugin: GitChangelogPlugin;
showFilesCountSummaries: FilesSummariesDisplayMode;
showFilesCountSummaries: FileSummariesDisplayMode;
version: VaultChangelogEntry;
hideTitleAndMakeUncollapsible?: boolean;
}
const { plugin, showFilesCountSummaries, version }: Properties = $props();
const {
plugin,
showFilesCountSummaries,
version,
hideTitleAndMakeUncollapsible: hideTitleAndCollapseIcon
}: Properties = $props();
const formattedVersionDateLabel = $derived.by(() => {
// CurrentDay just used to trigger updates
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const currentDay = plugin.currentDay;
// Doing it this way to ensure they're properly reacted to if changed.
const currentDate = plugin.utcCurrentDateHour;
const locale = plugin.localeSafe;
return composeVersionTitle({
interval: plugin.settings.vaultChangelogGenerationSettings.interval,
plugin,
timezoneAdjustedEntryDate: version.timezoneAdjustedDate
interval: plugin.settings.vaultChangelogInterval,
dayStartHour: plugin.settings.dayStartHour,
locale,
timeZone: getTimeZone(plugin),
utcCurrentDateHour: currentDate,
timeZoneAdjustedEntryDate: version.timeZoneAdjustedDate
});
});
</script>
@ -35,15 +45,17 @@
<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div
class:is-collapsed={version.isCollapsed}
class:is-collapsed={hideTitleAndCollapseIcon ? false : version.isCollapsed}
class="git-changelog-bottom-padding"
>
<div
class="tree-item-self is-clickable"
class={`tree-item-self${hideTitleAndCollapseIcon ? '' : ' is-clickable'}`}
data-tooltip-position="bottom"
onclick={() => {
version.isCollapsed = !version.isCollapsed;
}}
onclick={hideTitleAndCollapseIcon
? undefined
: () => {
version.isCollapsed = !version.isCollapsed;
}}
onauxclick={(event) => {
event.stopPropagation();
// eslint-disable-next-line eqeqeq
@ -61,36 +73,40 @@
}
}}
>
<div
class="tree-item-icon nav-folder-collapse-indicator collapse-icon"
class:is-collapsed={version.isCollapsed}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="svg-icon right-triangle"><path d="M3 8L12 17L21 8" /></svg
{#if !hideTitleAndCollapseIcon}
<div
class="tree-item-icon nav-folder-collapse-indicator collapse-icon"
class:is-collapsed={version.isCollapsed}
>
</div>
<div class="file-stats git-changelog-files-summaries-stats">
<div class="git-changelog-entry-title">
<div>{formattedVersionDateLabel}</div>
{#if !version.previousVersionCommitHash}
<div>
<span class="nav-file-tag git-changelog-initial-version-tag"
>Initial</span
>
</div>
{/if}
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="svg-icon right-triangle"><path d="M3 8L12 17L21 8" /></svg
>
</div>
{/if}
<div class="file-stats git-changelog-files-summaries-stats">
{#if !hideTitleAndCollapseIcon}
<div class="git-changelog-entry-title">
<div>{formattedVersionDateLabel}</div>
{#if !version.previousVersionCommitHash}
<div>
<span class="nav-file-tag git-changelog-initial-version-tag"
>Initial</span
>
</div>
{/if}
</div>
{/if}
<!-- if more than one option is selected then show labels -->
{#if showFilesCountSummaries === FilesSummariesDisplayMode.Total}
{#if showFilesCountSummaries === FileSummariesDisplayMode.Total}
<div class="git-changelog-stat">
<DayFilesStatusComponent
filesSummary={version.getChangelogFilesSummary()}
@ -98,7 +114,7 @@
</div>
{/if}
{#if showFilesCountSummaries === FilesSummariesDisplayMode.TextAndBinary}
{#if showFilesCountSummaries === FileSummariesDisplayMode.TextAndBinary}
{#if version.binaryFiles.length > 0}
<div class="git-changelog-stat">
<DayFilesStatusComponent
@ -132,7 +148,7 @@
/>
</div>
</div>
{#if !version.isCollapsed}
{#if hideTitleAndCollapseIcon ? true : !version.isCollapsed}
<div class="tree-item-children" transition:slide|local={{ duration: 150 }}>
{#each version.textFiles as file (file.pathGitRelative)}
{#if file !== undefined && file !== undefined}

View file

@ -1,13 +1,9 @@
import type GitChangelogPlugin from 'main.ts';
import type { Spacetime } from 'spacetime';
import type { DiffFile } from 'types.ts';
import { normalizePath } from 'obsidian';
import { getUserLocale } from 'settings/ui/CustomLocale.ts';
import { getTimeZone } from 'settings/ui/CustomTimeZone.ts';
import { getDayStartTime } from 'settings/ui/DayStartTime.ts';
import spacetime from 'spacetime';
import { applyDayStartTimeSetting } from 'timeUtils.ts';
import { applyDayStartHourSetting } from 'timeUtils.ts';
import { ChangelogInterval } from 'types.ts';
import {
assertNotNull,
@ -60,14 +56,27 @@ export function getIntervalAdjectiveString(
}
export function composeDailyVersionDisplayText({
fullyAdjustedCurrentDate,
fullyAdjustedEntryDate,
plugin
timeZoneAdjustedCurrentDate,
locale,
timeZone,
timeZoneAdjustedEntryDate,
dayStartHour
}: {
fullyAdjustedCurrentDate: Spacetime;
fullyAdjustedEntryDate: Spacetime;
plugin: GitChangelogPlugin;
timeZoneAdjustedCurrentDate: Spacetime;
timeZoneAdjustedEntryDate: Spacetime;
locale: string;
dayStartHour: number;
timeZone: string;
}): string {
const fullyAdjustedEntryDate = applyDayStartHourSetting({
dayStartHour,
timeZoneAdjustedDate: timeZoneAdjustedEntryDate
});
const fullyAdjustedCurrentDate = applyDayStartHourSetting({
dayStartHour,
timeZoneAdjustedDate: timeZoneAdjustedCurrentDate
});
const isToday = fullyAdjustedEntryDate.isSame(
fullyAdjustedCurrentDate,
'day'
@ -84,163 +93,152 @@ export function composeDailyVersionDisplayText({
return 'Yesterday';
}
return formatDate(
fullyAdjustedEntryDate.toNativeDate(),
getUserLocale(plugin),
getTimeZone(plugin.settings.changelogGenerationSettings, plugin)
);
return formatDate(fullyAdjustedEntryDate.toNativeDate(), locale, timeZone);
}
// Only for composing the UI string
export function applyDayDisplayOffset({
dayStartTime,
timezoneAdjustedDate
dayStartHour,
timeZoneAdjustedDate
}: {
dayStartTime: number;
timezoneAdjustedDate: Spacetime;
dayStartHour: number;
timeZoneAdjustedDate: Spacetime;
}): Spacetime {
const dayOffset = timezoneAdjustedDate.hour() < dayStartTime ? 1 : 0;
return timezoneAdjustedDate.clone().subtract(dayOffset, 'day');
const dayOffset = timeZoneAdjustedDate.hour() < dayStartHour ? 1 : 0;
return timeZoneAdjustedDate.clone().subtract(dayOffset, 'day');
}
export function composeHourlyVersionDisplayText({
fullyAdjustedCurrentDate,
fullyAdjustedEntryDate,
timezoneAdjustedEntryDate,
plugin
timeZoneAdjustedEntryDate,
locale,
timeZone,
timeZoneAdjustedCurrentDate
}: {
fullyAdjustedCurrentDate: Spacetime;
fullyAdjustedEntryDate: Spacetime;
timezoneAdjustedEntryDate: Spacetime;
plugin: GitChangelogPlugin;
timeZoneAdjustedEntryDate: Spacetime;
locale: string;
timeZoneAdjustedCurrentDate: Spacetime;
timeZone: string;
}): string {
// Use the fullyAdjusted dates only to check if the dates belong to the same day after the dayStartTime setting is applied.
const isToday = fullyAdjustedEntryDate.isSame(
fullyAdjustedCurrentDate,
const isToday = timeZoneAdjustedEntryDate.isSame(
timeZoneAdjustedCurrentDate,
'day'
);
const isYesterday = fullyAdjustedEntryDate.isSame(
fullyAdjustedCurrentDate.clone().subtract(1, 'days'),
const isYesterday = timeZoneAdjustedEntryDate.isSame(
timeZoneAdjustedCurrentDate.clone().subtract(1, 'days'),
'day'
);
const userLocale = getUserLocale(plugin);
const timeZone = getTimeZone(
plugin.settings.changelogGenerationSettings,
plugin
);
// Replaces the day part of the date time string with today or yesterday labels.
if (isToday || isYesterday) {
const timeFormatter = new Intl.DateTimeFormat(userLocale, {
const timeFormatter = new Intl.DateTimeFormat(locale, {
timeStyle: 'short',
timeZone
});
const timeString = timeFormatter.format(
timezoneAdjustedEntryDate.startOf('hour').toNativeDate()
timeZoneAdjustedEntryDate.startOf('hour').toNativeDate()
);
return `${isToday ? 'Today' : 'Yesterday'}, ${timeString}`;
}
const formatter = new Intl.DateTimeFormat(userLocale, {
const formatter = new Intl.DateTimeFormat(locale, {
dateStyle: 'short',
timeStyle: 'short',
timeZone
});
// Use the timezoneAdjustedEntryDate in the UI and just potentially subtract a day if it crosses the dayStartTime boundary. Don't show the fake fullyAdjustedEntryDate that has the dayStartTime offset applied to hours.
const timezoneAdjustedEntryDateWithDayOffset = applyDayDisplayOffset({
dayStartTime: getDayStartTime(plugin.settings.changelogGenerationSettings),
timezoneAdjustedDate: timezoneAdjustedEntryDate
});
return formatter.format(
timezoneAdjustedEntryDateWithDayOffset.startOf('hour').toNativeDate()
timeZoneAdjustedEntryDate.startOf('hour').toNativeDate()
);
}
export function composeMonthlyVersionDisplayText({
fullyAdjustedEntryDate,
plugin
timeZoneAdjustedEntryDate,
locale,
timeZone
}: {
fullyAdjustedEntryDate: Spacetime;
plugin: GitChangelogPlugin;
timeZoneAdjustedEntryDate: Spacetime;
locale: string;
timeZone: string;
}): string {
return formatMonthYear(
fullyAdjustedEntryDate.toNativeDate(),
getUserLocale(plugin),
getTimeZone(plugin.settings.changelogGenerationSettings, plugin)
timeZoneAdjustedEntryDate.toNativeDate(),
locale,
timeZone
);
}
export function composeVersionTitle({
interval,
plugin,
timezoneAdjustedEntryDate
dayStartHour,
locale,
timeZone,
timeZoneAdjustedEntryDate,
utcCurrentDateHour
}: {
interval: ChangelogInterval;
plugin: GitChangelogPlugin;
timezoneAdjustedEntryDate: Spacetime;
dayStartHour: number;
locale: string;
utcCurrentDateHour: string;
timeZone: string;
timeZoneAdjustedEntryDate: Spacetime;
}): string {
const timezoneAdjustedCurrentDate = spacetime.now(
getTimeZone(plugin.settings.changelogGenerationSettings, plugin)
);
const fullyAdjustedCurrentDate = applyDayStartTimeSetting({
dayStartTime: getDayStartTime(plugin.settings.changelogGenerationSettings),
timezoneAdjustedDate: timezoneAdjustedCurrentDate
});
const fullyAdjustedEntryDate = applyDayStartTimeSetting({
dayStartTime: getDayStartTime(plugin.settings.changelogGenerationSettings),
timezoneAdjustedDate: timezoneAdjustedEntryDate
});
// Clipped to the hour
const timeZoneAdjustedCurrentDate =
spacetime(utcCurrentDateHour).goto(timeZone);
switch (interval) {
case ChangelogInterval.Hourly: {
return composeHourlyVersionDisplayText({
fullyAdjustedCurrentDate,
fullyAdjustedEntryDate,
timezoneAdjustedEntryDate,
plugin
timeZoneAdjustedEntryDate,
timeZoneAdjustedCurrentDate,
locale,
timeZone
});
}
case ChangelogInterval.Daily: {
return composeDailyVersionDisplayText({
fullyAdjustedCurrentDate,
fullyAdjustedEntryDate,
plugin
timeZoneAdjustedEntryDate,
timeZoneAdjustedCurrentDate,
dayStartHour,
locale,
timeZone
});
}
case ChangelogInterval.Weekly: {
return composeWeeklyVersionDisplayText({
fullyAdjustedCurrentDate,
fullyAdjustedEntryDate,
plugin
timeZoneAdjustedEntryDate,
timeZoneAdjustedCurrentDate,
locale,
timeZone
});
}
case ChangelogInterval.Monthly: {
return composeMonthlyVersionDisplayText({
fullyAdjustedEntryDate,
plugin
timeZoneAdjustedEntryDate,
locale,
timeZone
});
}
}
}
export function composeWeeklyVersionDisplayText({
fullyAdjustedCurrentDate,
fullyAdjustedEntryDate,
plugin
timeZoneAdjustedEntryDate,
timeZoneAdjustedCurrentDate,
locale,
timeZone
}: {
fullyAdjustedCurrentDate: Spacetime;
fullyAdjustedEntryDate: Spacetime;
plugin: GitChangelogPlugin;
timeZoneAdjustedCurrentDate: Spacetime;
timeZoneAdjustedEntryDate: Spacetime;
locale: string;
timeZone: string;
}): string {
const fullyAdjustedEntryWeek = fullyAdjustedEntryDate.startOf('week');
const timeZoneAdjustedEntryWeek = timeZoneAdjustedEntryDate.startOf('week');
// In order for this to be accurate we need to normalize the dates to the start of the interval, which is a week here. If comparing would be based on what the actual commit date is of the current version is, instead of that interval that version belongs to, the diffs would be inconsistent because e.g. when comparing the latest version with the latest commit on thursday with the previous version that had it's last commit on wednesday, the diff would count 2 weeks difference instead of 1.
const weeksDifference = fullyAdjustedEntryWeek.diff(
fullyAdjustedCurrentDate.startOf('week'),
// In order for this to be accurate we need to normalize the dates to the start of the interval, which is a week here.
// If comparing would be based on what the actual commit date is of the current version is, instead of that interval that version belongs to, the diffs would be inconsistent because e.g. when comparing the latest version with the latest commit on thursday with the previous version that had it's last commit on wednesday, the diff would count 2 weeks difference instead of 1.
const weeksDifference = timeZoneAdjustedEntryWeek.diff(
timeZoneAdjustedCurrentDate.startOf('week'),
'weeks'
);
@ -251,34 +249,29 @@ export function composeWeeklyVersionDisplayText({
return 'Last week';
}
const userLocale = getUserLocale(plugin);
const weekNumber = timeZoneAdjustedEntryDate.week();
const weekNumber = fullyAdjustedEntryDate.week();
const isCurrentYear = fullyAdjustedEntryDate.isSame(
fullyAdjustedCurrentDate,
const isCurrentYear = timeZoneAdjustedEntryDate.isSame(
timeZoneAdjustedCurrentDate,
'year'
);
const nativeFullyAdjustedEntryWeek = fullyAdjustedEntryWeek.toNativeDate();
const timeZone = getTimeZone(
plugin.settings.changelogGenerationSettings,
plugin
);
const nativeTimeZoneAdjustedEntryWeek =
timeZoneAdjustedEntryWeek.toNativeDate();
if (isCurrentYear) {
const monthString = new Intl.DateTimeFormat(userLocale, {
const monthString = new Intl.DateTimeFormat(locale, {
month: 'short',
timeZone
}).format(nativeFullyAdjustedEntryWeek);
}).format(nativeTimeZoneAdjustedEntryWeek);
return `Week ${weekNumber}, ${monthString}`;
}
const monthAndYearString = new Intl.DateTimeFormat(userLocale, {
const monthAndYearString = new Intl.DateTimeFormat(locale, {
month: 'short',
year: '2-digit',
timeZone
}).format(nativeFullyAdjustedEntryWeek);
}).format(nativeTimeZoneAdjustedEntryWeek);
return `Week ${weekNumber}, ${monthAndYearString}`;
}
@ -316,6 +309,22 @@ export function formatMonthYear(
}).format(date);
}
export function formatFullDate(
date: Date,
locale: string,
timeZone: string
): string {
return new Intl.DateTimeFormat(locale, {
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
year: 'numeric',
timeZone
}).format(date);
}
export function getDisplayExtensionFromPath(filePath: string): string {
const normalizedPath = normalizePath(filePath);
const segments = normalizedPath.split('/');

View file

@ -1,4 +1,4 @@
import type { ItemView } from 'obsidian';
import type { App, ItemView } from 'obsidian';
import { MarkdownView, TFile } from 'obsidian';
import { getNewLeaf } from 'utils.ts';
@ -87,11 +87,18 @@ export function getDisplayPath(path: string): string {
return path.split('/').last()?.replace(/\.md$/, '') ?? '';
}
export function isDiffView(view: ItemView | null): boolean {
return (
view?.getViewType() === 'diff-view' ||
view?.getViewType() === 'split-diff-view'
);
/**
* Assumes that no file view is currently active
*/
export function isDiffViewVisible({ app }: { app: App }): boolean {
const diffViews = [
...app.workspace.getLeavesOfType('diff-view'),
...app.workspace.getLeavesOfType('split-diff-view')
];
return diffViews.some((leaf) => {
return leaf.containerEl.isShown();
});
}
export function openFile({
@ -136,3 +143,18 @@ export function showDiff(
event
});
}
export function registerCloseViewIfDeferred(
compareView: ItemView,
plugin: GitChangelogPlugin
): void {
// On each workspace layout change, check if this view is still visible.
compareView.registerEvent(
plugin.app.workspace.on('active-leaf-change', () => {
// If the view exists but isn't visible, close it
if (!compareView.contentEl.isShown()) {
compareView.leaf.detach();
}
})
);
}

View file

@ -1,5 +1,16 @@
import type { GitChangelogPlugin } from 'GitChangelogPlugin.svelte.ts';
import type { GitChangelogSettings } from 'settings/settings.ts';
import type { CompareRepoCommitsViewState } from 'types.ts';
import {
COMPARE_REPO_COMMITS_VIEW_CONFIG,
COMPARE_TO_CHECKPOINT_VIEW_CONFIG
} from 'constants.ts';
import { CssClass } from 'obsidian-dev-utils/CssClass';
import { showModal } from 'obsidian-dev-utils/obsidian/Modals/ModalBase';
import { openCompareToCheckpointView } from 'settings/ui/ReviewChangesReminderInterval.ts';
import { removeCompareVersionsView } from 'utils.ts';
import { CompareVersionsModal } from 'Views/CompareRepoCommits/CompareModal.ts';
import { FILE_CHANGELOG_VIEW_CONFIG } from 'Views/FileChangelog/FileChangelog.ts';
import { VAULT_CHANGELOG_VIEW_CONFIG } from 'Views/VaultChangelog/VaultChangelog.ts';
@ -29,4 +40,77 @@ export function addCommands(plugin: GitChangelogPlugin): void {
id: `open-${FILE_CHANGELOG_VIEW_CONFIG.type}`,
name: `Open ${FILE_CHANGELOG_VIEW_CONFIG.name.toLocaleLowerCase()} view`
});
plugin.addCommand({
callback: async () => {
await openCompareToCheckpointView(plugin);
},
id: `show-${COMPARE_TO_CHECKPOINT_VIEW_CONFIG.type}`,
name: `Show ${COMPARE_TO_CHECKPOINT_VIEW_CONFIG.name.toLocaleLowerCase()}`
});
plugin.addCommand({
callback: async () => {
await plugin.settingsManager.editAndSave(
(settings: GitChangelogSettings): void => {
settings.enableExclusionList = !settings.enableExclusionList;
}
);
// Hotkeys or the command palette don't work in the settings tab under normal circumstances so we don't have to handle refreshing the settingsTab display
plugin.displayNotice(
plugin.settings.enableExclusionList
? 'Exclusion list enabled.'
: 'Exclusion list disabled.',
// eslint-disable-next-line no-magic-numbers
1500
);
},
id: `toggle-exclusion-list`,
name: `Toggle exclusion list`
});
addCompareRepoVersionsCommand(plugin);
}
function addCompareRepoVersionsCommand(plugin: GitChangelogPlugin): void {
plugin.addCommand({
id: 'compare-two-versions',
name: 'Compare two vault states in history',
callback: async () => {
// Always returns undefined if the modal was exited without clicking "approve" button.
const compareRepoCommitsViewState = await showModal<
CompareRepoCommitsViewState | undefined
>(
(resolve) =>
new CompareVersionsModal({
plugin,
resolve,
modalCssClass: CssClass.ConfirmModal,
options: {
app: plugin.app,
cssClass: CssClass.ConfirmModal
},
utcOlderDateString: plugin.compareVersionsUtcOlderDate,
utcNewerDateString: plugin.compareVersionsUtcNewerDate
})
);
if (compareRepoCommitsViewState) {
// Close any existing COMPARE_REPO_STATES_VIEW views
removeCompareVersionsView(plugin);
plugin.compareVersionsUtcNewerDate =
compareRepoCommitsViewState.utcNewerDate;
plugin.compareVersionsUtcOlderDate =
compareRepoCommitsViewState.utcOlderDate;
await plugin.app.workspace.ensureSideLeaf(
COMPARE_REPO_COMMITS_VIEW_CONFIG.type,
'left',
{ reveal: true }
);
}
}
});
}

View file

@ -1,10 +1,27 @@
import type GitChangelogPlugin from 'main.ts';
import type { PluginTypesBase } from 'obsidian-dev-utils/obsidian/Plugin/PluginTypesBase';
import type { GitChangelogSettings } from 'settings/settings.ts';
import type { GitChangelogSettingsManager } from 'settings/settingsManager.ts';
import type { GitChangelogSettingsTab } from 'settings/settingsTab.ts';
export const PLUGIN_NAME = 'Git Changelog';
export const PLUGIN_NAME_SENTENCE_CASE = 'Git changelog';
export const MIN_COMPATIBLE_GIT_PLUGIN_VERSION = '2.31.1';
export const MAX_TESTED_GIT_PLUGIN_VERSION = '2.32.1';
export const MAX_TESTED_GIT_PLUGIN_VERSION = '2.34.0';
export interface GitChangelogPluginTypes extends PluginTypesBase {
plugin: GitChangelogPlugin;
pluginSettings: GitChangelogSettings;
pluginSettingsManager: GitChangelogSettingsManager;
pluginSettingsTab: GitChangelogSettingsTab;
}
// Strings
export const FEEDBACK_URL =
'https://github.com/shumadrid/obsidian-git-changelog/issues';
export const EXCLUDE_FILES_AND_FOLDERS = 'Exclude files and folders';
export const CHANGES_SINCE_LAST_CHECKPOINT =
'changes since the last checkpoint';
// Icons
export const ADDITIONS_ICON = 'list-plus';
@ -22,8 +39,25 @@ export const OPEN_FILE_ICON = 'file-input';
export const PLUS_ICON = 'plus';
export const MINUS_ICON = 'minus';
export const COPY_COMMIT_HASH_ICON = 'git-commit-horizontal';
export const COMPARED_VERSIONS_DATE_SEPARATOR_ICON = 'clock-10';
export const INFO_TOOLTIP_ICON = 'info';
export const CHANGELOG_LOAD_AMOUNT_BASE_MULTIPLIER = 35;
export const CHANGELOG_LOAD_AMOUNT_VERSIONS = 10;
export const FILE_VIEW_VERSIONS_MULTIPLIER = 2.4;
export const VAULT_MAX_COUNT_MULTIPLIER = 6;
// Settings
export const MIN_RENAME_DETECTION_STRICTNESS = 1;
export const MAX_RENAME_DETECTION_STRICTNESS = 100;
export const COMPARE_TO_CHECKPOINT_VIEW_CONFIG = {
icon: 'spline',
name: 'Vault changes since the last checkpoint',
type: 'compare-to-checkpoint-view'
};
export const COMPARE_REPO_COMMITS_VIEW_CONFIG = {
icon: 'spline',
name: "Vault's git history comparison",
type: 'vault-git-history-comparison-view'
};

View file

@ -8,7 +8,7 @@ import type {
export abstract class ChangelogEntry {
public constructor(
public timezoneAdjustedDate: Spacetime,
public timeZoneAdjustedDate: Spacetime,
public commitHash: string // Represents a single commit that's just the latest commit of a certain interval (day,week...).
) {}
@ -33,16 +33,16 @@ export class FileChangelogEntry extends ChangelogEntry implements DiffFile {
pathGitRelative,
status,
textDiffStats,
timezoneAdjustedDate
timeZoneAdjustedDate
}: {
commitHash: string;
fromPathGitRelative?: string;
pathGitRelative: string;
status: DiffFileStatus;
textDiffStats?: TextDiffStats;
timezoneAdjustedDate: Spacetime;
timeZoneAdjustedDate: Spacetime;
}) {
super(timezoneAdjustedDate, commitHash);
super(timeZoneAdjustedDate, commitHash);
this.pathGitRelative = pathGitRelative;
this.status = status;
this.fromPathGitRelative = fromPathGitRelative;
@ -75,25 +75,25 @@ export class VaultChangelogEntry extends ChangelogEntry {
binaryFiles,
binaryFilesSummaryCached,
commitHash,
previousDayLastCommitHash,
previousVersionLastCommitHash,
textFiles,
textFilesSummaryCached,
timezoneAdjustedDate
timeZoneAdjustedDate
}: {
binaryFiles: DiffFile[];
binaryFilesSummaryCached: FilesSummary;
commitHash: string;
previousDayLastCommitHash?: string;
previousVersionLastCommitHash?: string;
textFiles: DiffFile[];
textFilesSummaryCached: FilesSummary;
timezoneAdjustedDate: Spacetime;
timeZoneAdjustedDate: Spacetime;
}) {
super(timezoneAdjustedDate, commitHash);
super(timeZoneAdjustedDate, commitHash);
this.textFiles = textFiles;
this.binaryFiles = binaryFiles;
this.textFilesSummaryCached = textFilesSummaryCached;
this.binaryFilesSummaryCached = binaryFilesSummaryCached;
this.previousVersionCommitHash = previousDayLastCommitHash;
this.previousVersionCommitHash = previousVersionLastCommitHash;
}
public override getPotentialGitFilePath(): undefined {

View file

@ -1,6 +1,8 @@
import type { GitChangelogPluginTypes } from 'constants.ts';
import type { ChangelogEntry } from 'core/ChangelogEntry.svelte.ts';
import type GitChangelogPlugin from 'main.ts';
import type { GitChangelogPluginSettings } from 'settings/settings.ts';
import type { ExtractPluginSettingsWrapper } from 'obsidian-dev-utils/obsidian/Plugin/PluginTypesBase';
import type { GitChangelogSettings } from 'settings/settings.ts';
import type { Spacetime } from 'spacetime';
import type { TaskManager } from 'TaskManager.svelte.ts';
import type { ReadonlyDeep } from 'type-fest';
@ -12,6 +14,7 @@ import {
extractLastCommitsForInterval,
GIT_MAX_CONCURRENT_PROCESSES
} from 'core/helper.ts';
import { getTimeZone } from 'settings/ui/CustomTimeZone.ts';
import { AbortError, ChangelogInterval } from 'types.ts';
import { assertNotNull } from 'utils.ts';
@ -97,6 +100,8 @@ export abstract class ChangelogManager<T extends ChangelogEntry> {
// We want to immediately cancel all current operations for the changelog and schedule the operation in a queue.
const abortSignal = this.resetAndGetSignal();
// Abort controllers don't just serve to optimize performance by stopping the execution of cancelled functions, but they also serve to prevent those cancelled functions from mutating current state and introducing race conditions.
// All abort signals need to be created on call time, and also the plugin settings (it's not strictly necessary, because operations with outdated settings will always get cancelled anyway).
this.taskManager.enqueueSafely(async () => {
await this.computeChangelog(abortSignal);
});
@ -119,12 +124,14 @@ export abstract class ChangelogManager<T extends ChangelogEntry> {
});
}
public generationSettingsChanged(
oldSettings: ReadonlyDeep<GitChangelogPluginSettings>,
newSettings: GitChangelogPluginSettings
): boolean {
return this.getInterval(oldSettings) !== this.getInterval(newSettings);
}
public abstract specificSettingsChanged(
oldSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>,
newSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>
): boolean;
public resetAndGetSignal(): AbortSignal {
// Reset `visibleEntries` to undefined each time when you schedule a recompute so that the UI correctly updates to "loading" state while it waits for the stats to compute.
@ -141,7 +148,7 @@ export abstract class ChangelogManager<T extends ChangelogEntry> {
public abstract setNextInterval(): Promise<void>;
public abstract getInterval(
settings?: ReadonlyDeep<GitChangelogPluginSettings>
settings?: ReadonlyDeep<GitChangelogSettings>
): ChangelogInterval;
protected abstract updateEntries({
@ -162,21 +169,27 @@ export abstract class ChangelogManager<T extends ChangelogEntry> {
abortSignal: AbortSignal;
activeGitFile?: string;
}): Promise<T[]> {
// Terminology:
// ActiveGitFile: the current file path of some live file version.
// FilePath: the path of some file in history.
const git = await this.plugin.getGit();
// Gets all commits newer (>=) than the commit of the latest cached version.
const timezoneAdjustedLogs = await runLog({
const timeZoneAdjustedLogs = await runLog({
abortSignal,
filePath: activeGitFile,
lowerBoundaryCommit: this.latestCachedVersion?.commitHash,
maxCount: undefined,
plugin: this.plugin,
upperBoundaryCommit: undefined
upperBoundaryCommit: undefined,
git,
renameDetectionStrictness: this.plugin.settings.renameDetectionStrictness,
timeZone: getTimeZone(this.plugin)
});
const extractedVersions = await extractLastCommitsForInterval({
changelogGenerationSettings:
this.plugin.settings.changelogGenerationSettings,
dayStartHour: this.plugin.settings.dayStartHour,
interval: this.getInterval(),
timezoneAdjustedLogs
timeZoneAdjustedLogs
});
// Always recalculate the latest version in cached changelog (because it likely has outdated stats), but only if there are any versions to recalculate.
@ -188,7 +201,7 @@ export abstract class ChangelogManager<T extends ChangelogEntry> {
extractedVersions.push({
filePath: versionBeforeLatestCached.getPotentialGitFilePath(),
hash: versionBeforeLatestCached.commitHash,
timezoneAdjustedDate: versionBeforeLatestCached.timezoneAdjustedDate
timeZoneAdjustedDate: versionBeforeLatestCached.timeZoneAdjustedDate
});
}
@ -258,6 +271,7 @@ export abstract class ChangelogManager<T extends ChangelogEntry> {
});
} else {
// If necessary, retrieve additional entries (if there are any left) and then append.
// Check for sufficient versions when the task gets it's turn, not when it is added to the queue.
if (this.shouldRetrieveMoreReserveEntries()) {
await this.maybeRetrieveReserveEntries({ abortSignal });
}
@ -385,31 +399,34 @@ export abstract class ChangelogManager<T extends ChangelogEntry> {
) {
logCycles++;
const timezoneAdjustedLogs = await runLog({
const git = await this.plugin.getGit();
const timeZoneAdjustedLogs = await runLog({
abortSignal,
filePath: startingFilePath,
lowerBoundaryCommit: undefined,
maxCount: logMaxCount,
plugin: this.plugin,
git,
renameDetectionStrictness:
this.plugin.settings.renameDetectionStrictness,
timeZone: getTimeZone(this.plugin),
upperBoundaryCommit: startingCommit
});
// All we need from a version is its latest commit, not all commits included in that interval
const extractedVersions = await extractLastCommitsForInterval({
changelogGenerationSettings:
this.plugin.settings.changelogGenerationSettings,
dayStartHour: this.plugin.settings.dayStartHour,
interval,
previouslySeenFullyAdjustedDates: fullyAdjustedSeenDates,
timezoneAdjustedLogs
timeZoneAdjustedLogs
});
if (timezoneAdjustedLogs.length < logMaxCount) {
if (timeZoneAdjustedLogs.length < logMaxCount) {
reachedInitialCommit = true;
}
// If getting file changelog versions and need to loop many times, we need to track the file path across renames so that we can follow the target file across its whole history.
startingFilePath = timezoneAdjustedLogs.at(-1)?.filePath;
startingFilePath = timeZoneAdjustedLogs.at(-1)?.filePath;
startingCommit = timezoneAdjustedLogs.at(-1)?.hash;
startingCommit = timeZoneAdjustedLogs.at(-1)?.hash;
lastCommitsInEachVersion.push(...extractedVersions);

View file

@ -1,6 +1,8 @@
import type { GitChangelogPluginTypes } from 'constants.ts';
import type { FileChangelogEntry } from 'core/ChangelogEntry.svelte.ts';
import type GitChangelogPlugin from 'main.ts';
import type { GitChangelogPluginSettings } from 'settings/settings.ts';
import type { ExtractPluginSettingsWrapper } from 'obsidian-dev-utils/obsidian/Plugin/PluginTypesBase';
import type { GitChangelogSettings } from 'settings/settings.ts';
import type { TaskManager } from 'TaskManager.svelte.ts';
import type { ReadonlyDeep } from 'type-fest';
import type { ChangelogInterval, FileLogEntry } from 'types.ts';
@ -12,21 +14,18 @@ import {
} from 'constants.ts';
import { ChangelogManager } from 'core/ChangelogManager.svelte.ts';
import { runFileDiff } from 'core/gitOperations/runFileDiff.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { validateChangelogInterval } from 'settings/validation/changelogInterval.ts';
import { deepEqual } from 'obsidian-dev-utils/Object';
import { pickFileChangelogSettings } from 'settings/settings.ts';
export class FileChangelogManager extends ChangelogManager<FileChangelogEntry> {
public constructor({
// ActiveGitFile,
plugin,
taskManager
}: {
// ActiveGitFile?: string;
plugin: GitChangelogPlugin;
taskManager: TaskManager;
}) {
super({ plugin, taskManager });
// This.cachedActiveGitFile = activeGitFile;
}
/**
@ -47,23 +46,35 @@ export class FileChangelogManager extends ChangelogManager<FileChangelogEntry> {
}
public override async setNextInterval(): Promise<void> {
const newSettings = this.plugin.settingsClone;
await this.plugin.settingsManager.editAndSave(
(settings: GitChangelogSettings): void => {
settings.fileChangelogInterval = this.getNextInterval();
},
true
);
this.plugin.app.workspace.trigger(
'git-changelog:file-changelog-generation-settings-changed'
);
}
newSettings.fileChangelogInterval = this.getNextInterval();
public override specificSettingsChanged(
oldSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>,
newSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>
): boolean {
const oldVaultGenerationSettings = pickFileChangelogSettings(oldSettings);
const newVaultGenerationSettings = pickFileChangelogSettings(newSettings);
await this.plugin.saveSettings(newSettings, false);
return !deepEqual(oldVaultGenerationSettings, newVaultGenerationSettings);
}
public override getInterval(
settings: ReadonlyDeep<GitChangelogPluginSettings> = this.plugin.settings
settings: ReadonlyDeep<GitChangelogSettings> = this.plugin.settings
): ChangelogInterval {
const interval = settings.fileChangelogInterval;
if (!validateChangelogInterval(interval)) {
return DEFAULT_SETTINGS.fileChangelogInterval;
}
return interval;
return settings.fileChangelogInterval;
}
protected override async loadEntries({
@ -124,11 +135,17 @@ export class FileChangelogManager extends ChangelogManager<FileChangelogEntry> {
newCommit: FileLogEntry;
oldCommit?: FileLogEntry;
}): Promise<FileChangelogEntry | undefined> {
const git = await this.plugin.getGit();
return await runFileDiff({
abortSignal,
newCommit,
oldCommit,
plugin: this.plugin
plugin: this.plugin,
diffAlgorithm: this.plugin.settings.diffAlgorithm,
whitespaceIgnoreMode: this.plugin.settings.whitespaceIgnoreMode,
ignoreBlankLines: this.plugin.settings.ignoreBlankLines,
emptyTreeHash: await this.plugin.getEmptyTreeHash(),
git
});
}

View file

@ -1,6 +1,8 @@
import type { GitChangelogPluginTypes } from 'constants.ts';
import type { VaultChangelogEntry } from 'core/ChangelogEntry.svelte.ts';
import type GitChangelogPlugin from 'main.ts';
import type { GitChangelogPluginSettings } from 'settings/settings.ts';
import type { ExtractPluginSettingsWrapper } from 'obsidian-dev-utils/obsidian/Plugin/PluginTypesBase';
import type { GitChangelogSettings } from 'settings/settings.ts';
import type { TaskManager } from 'TaskManager.svelte.ts';
import type { ReadonlyDeep } from 'type-fest';
import type { ChangelogInterval, LogEntry } from 'types.ts';
@ -13,8 +15,7 @@ import {
import { ChangelogManager } from 'core/ChangelogManager.svelte.ts';
import { runRepoDiff } from 'core/gitOperations/runRepoDiff.ts';
import { deepEqual } from 'obsidian-dev-utils/Object';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { validateChangelogInterval } from 'settings/validation/changelogInterval.ts';
import { pickVaultChangelogSettings } from 'settings/settings.ts';
export class VaultChangelogManager extends ChangelogManager<VaultChangelogEntry> {
private collapseFirstVersion: boolean | undefined;
@ -48,40 +49,35 @@ export class VaultChangelogManager extends ChangelogManager<VaultChangelogEntry>
}
public override async setNextInterval(): Promise<void> {
const newSettings = this.plugin.settingsClone;
newSettings.vaultChangelogGenerationSettings.interval =
this.getNextInterval();
await this.plugin.saveSettings(newSettings, false);
await this.plugin.settingsManager.editAndSave(
(settings: GitChangelogSettings): void => {
settings.vaultChangelogInterval = this.getNextInterval();
},
true
);
this.plugin.app.workspace.trigger(
'git-changelog:vault-changelog-generation-settings-changed'
);
}
public override generationSettingsChanged(
oldSettings: ReadonlyDeep<GitChangelogPluginSettings>,
newSettings: GitChangelogPluginSettings
public override specificSettingsChanged(
oldSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>,
newSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>
): boolean {
if (
!deepEqual(
oldSettings.vaultChangelogGenerationSettings
.excludeFilesAndFoldersLines,
newSettings.vaultChangelogGenerationSettings.excludeFilesAndFoldersLines
)
) {
return true;
}
return super.generationSettingsChanged(oldSettings, newSettings);
const oldVaultGenerationSettings = pickVaultChangelogSettings(oldSettings);
const newVaultGenerationSettings = pickVaultChangelogSettings(newSettings);
return !deepEqual(oldVaultGenerationSettings, newVaultGenerationSettings);
}
public override getInterval(
settings: ReadonlyDeep<GitChangelogPluginSettings> = this.plugin.settings
settings: ReadonlyDeep<GitChangelogSettings> = this.plugin.settings
): ChangelogInterval {
const interval = settings.vaultChangelogGenerationSettings.interval;
if (!validateChangelogInterval(interval)) {
return DEFAULT_SETTINGS.vaultChangelogGenerationSettings.interval;
}
return interval;
return settings.vaultChangelogInterval;
}
protected override calculateVersionsToAppend(resetCache: boolean): number {
@ -99,11 +95,23 @@ export class VaultChangelogManager extends ChangelogManager<VaultChangelogEntry>
newCommit: LogEntry;
oldCommit?: LogEntry;
}): Promise<undefined | VaultChangelogEntry> {
const git = await this.plugin.getGit();
return await runRepoDiff({
abortSignal,
newCommit,
oldCommit,
plugin: this.plugin
plugin: this.plugin,
git,
diffAlgorithm: this.plugin.settings.diffAlgorithm,
renameLimit: this.plugin.settings.renameLimit,
renameDetectionStrictness: this.plugin.settings.renameDetectionStrictness,
emptyTreeHash: await this.plugin.getEmptyTreeHash(),
excludeFilesAndFoldersLines:
this.plugin.settings.excludeFilesAndFoldersLines,
enableExclusionList: this.plugin.settings.enableExclusionList,
convertToIncludeList: this.plugin.settings.convertToIncludeList,
whitespaceIgnoreMode: this.plugin.settings.whitespaceIgnoreMode,
ignoreBlankLines: this.plugin.settings.ignoreBlankLines
});
}

View file

@ -1,8 +1,7 @@
import type GitChangelogPlugin from 'main.ts';
import type { SimpleGit } from 'simple-git';
import type { LogEntry } from 'types.ts';
import { runLog } from 'core/gitOperations/runLog.ts';
import { getTimeZone } from 'settings/ui/CustomTimeZone.ts';
import spacetime from 'spacetime';
import { AbortError } from 'types.ts';
import { assertNotNull } from 'utils.ts';
@ -14,21 +13,23 @@ export async function findFirstFileCommitBefore({
abortSignal,
filePath,
minutes,
plugin
timeZone,
git,
renameDetectionStrictness
}: {
abortSignal: AbortSignal;
filePath: string;
minutes: number;
plugin: GitChangelogPlugin;
timeZone: string;
git: SimpleGit;
renameDetectionStrictness: number;
}): Promise<LogEntry | undefined> {
// eslint-disable-next-line no-magic-numbers
const maxCount = Math.ceil(minutes / AVERAGE_COMMIT_FREQUENCY_MINUTES) + 20;
let firstEntriesOutsideInterval: LogEntry[] = [];
let startingFilePath = filePath;
const currentTime = spacetime.now(
getTimeZone(plugin.settings.changelogGenerationSettings, plugin)
);
const currentTime = spacetime.now(timeZone);
let startingCommit: string | undefined;
while (
@ -36,7 +37,7 @@ export async function findFirstFileCommitBefore({
!firstEntriesOutsideInterval.at(-1) ||
// Only continue if commit(s) that happened before the specified interval aren't reached yet.
assertNotNull(firstEntriesOutsideInterval.at(-1)).timezoneAdjustedDate.diff(
assertNotNull(firstEntriesOutsideInterval.at(-1)).timeZoneAdjustedDate.diff(
currentTime,
'minutes'
@ -49,8 +50,10 @@ export async function findFirstFileCommitBefore({
filePath: startingFilePath,
lowerBoundaryCommit: undefined,
maxCount,
plugin,
upperBoundaryCommit: startingCommit
upperBoundaryCommit: startingCommit,
git,
renameDetectionStrictness,
timeZone
});
if (firstEntriesOutsideInterval.length < maxCount) {
@ -73,7 +76,7 @@ export async function findFirstFileCommitBefore({
// We just need to get the most recent commit that's still outside the interval.
for (const entry of firstEntriesOutsideInterval) {
if (entry.timezoneAdjustedDate.diff(currentTime, 'minutes') >= minutes) {
if (entry.timeZoneAdjustedDate.diff(currentTime, 'minutes') >= minutes) {
return entry;
}
}

View file

@ -1,23 +1,44 @@
import type GitChangelogPlugin from 'main.ts';
import type { LogResult, SimpleGit } from 'simple-git';
import type { LogEntry } from 'types.ts';
import { getTimeZone } from 'settings/ui/CustomTimeZone.ts';
import spacetime from 'spacetime';
import { AbortError } from 'types.ts';
import { assertNotNull } from 'utils.ts';
/**
* Returns the first commit before the specified date or the specified number of minutes.
* If no commits are found, returns undefined.
*
* Either `minutes` or `isoString` must be provided.
*
* @param abortSignal - The abort signal to cancel the operation.
* @param minutes - The number of minutes to look back from now.
* @param isoString - The ISO string to look back from.
* @param git - The SimpleGit instance.
* @param timeZone - The time zone to adjust the commit date to.
*/
export async function findFirstCommitBefore({
abortSignal,
minutes,
plugin
isoString,
git,
timeZone
}: {
abortSignal: AbortSignal;
minutes: number;
plugin: GitChangelogPlugin;
minutes?: number;
isoString?: string;
git: SimpleGit;
timeZone: string;
}): Promise<LogEntry | undefined> {
if (abortSignal.aborted) {
throw new AbortError();
}
const options: Record<string, unknown> = {
// "--no-patch": null,
// eslint-disable-next-line no-magic-numbers
'--before': `${minutes * 60 - 3} seconds ago`,
'--before': isoString ?? `${assertNotNull(minutes) * 60 - 3} seconds ago`,
'--diff-merges': 'first-parent',
format: {
date: '%cI',
@ -28,15 +49,13 @@ export async function findFirstCommitBefore({
strictDate: true
};
if (abortSignal.aborted) {
throw new AbortError();
let result: LogResult;
try {
result = await git.log(options);
} catch {
// E.g. error when there are no commits in the repo
return undefined;
}
const git = await plugin.getGit();
const result = await git.log(options);
const timezone = getTimeZone(
plugin.settings.changelogGenerationSettings,
plugin
);
if (abortSignal.aborted) {
throw new AbortError();
@ -47,9 +66,11 @@ export async function findFirstCommitBefore({
return undefined;
}
return result.all.map<LogEntry>((entry) => ({
filePath: undefined,
hash: entry.hash,
timezoneAdjustedDate: spacetime(entry.date).goto(timezone)
}))[0];
return result.all
.map<LogEntry>((entry) => ({
filePath: undefined,
hash: entry.hash,
timeZoneAdjustedDate: spacetime(entry.date).goto(timeZone)
}))
.at(0);
}

View file

@ -0,0 +1,63 @@
import type { LogResult, SimpleGit } from 'simple-git';
import type { LogEntry } from 'types.ts';
import spacetime from 'spacetime';
import { AbortError } from 'types.ts';
/**
* Returns undefined if an error happens during a git log. For example, passed a non-existent commit hash or if there are no commits in the repo.
*/
export async function getCommitTimestampOrUndefined({
abortSignal,
commitHash,
git,
timeZone
}: {
abortSignal: AbortSignal;
commitHash?: string;
git: SimpleGit;
timeZone: string;
}): Promise<LogEntry | undefined> {
if (abortSignal.aborted) {
throw new AbortError();
}
const options: Record<string, unknown> = {
// "--no-patch": null,
'--diff-merges': 'first-parent',
format: {
date: '%cI',
hash: '%H'
},
maxCount: 1,
// Splitter: '\0',
strictDate: true
};
if (commitHash) {
options[commitHash] = null;
}
let result: LogResult;
try {
result = await git.log(options);
} catch {
return undefined;
}
// eslint-disable-next-line eqeqeq
if (result?.latest == null) {
return undefined;
}
if (abortSignal.aborted) {
throw new AbortError();
}
return result.all
.map<LogEntry>((entry) => ({
filePath: undefined,
hash: entry.hash,
timeZoneAdjustedDate: spacetime(entry.date).goto(timeZone)
}))
.at(0);
}

View file

@ -1,32 +0,0 @@
import type GitChangelogPlugin from 'main.ts';
async function runHashObjectEmptyTree({
plugin
}: {
plugin: GitChangelogPlugin;
}): Promise<string> {
const git = await plugin.getGit();
const emptyTreeHash = await git.raw([
'hash-object',
'-t',
'tree',
'/dev/null'
]);
return emptyTreeHash.trim();
}
export async function getEmptyTreeHash({
plugin
}: {
plugin: GitChangelogPlugin;
}): Promise<string> {
if (plugin.emptyTreeHash) {
return plugin.emptyTreeHash;
}
const emptyTreeHash = await runHashObjectEmptyTree({ plugin });
plugin.emptyTreeHash ??= emptyTreeHash;
return plugin.emptyTreeHash;
}

View file

@ -1,9 +1,6 @@
import type GitChangelogPlugin from 'main.ts';
import type { DiffFile, FilesSummary } from 'types.ts';
import { normalizePath } from 'obsidian';
import { getDiffAlgorithm } from 'settings/ui/DiffAlgorithmOptions.ts';
import { getWhitespaceIgnoreMode } from 'settings/ui/WhitespaceIgnoreMode.ts';
import { DiffAlgorithm, DiffFileStatus, WhitespaceIgnoreMode } from 'types.ts';
import { getFileNameFromPath } from 'utils.ts';
import { getDisplayExtensionFromPath } from 'Views/formatters.ts';
@ -23,11 +20,14 @@ export function addFileStatusToSummary(
}
}
export function assignDiffAlgorithm(
arguments_: string[],
plugin: GitChangelogPlugin
): void {
switch (getDiffAlgorithm(plugin.settings.changelogGenerationSettings)) {
export function assignDiffAlgorithm({
arguments_,
diffAlgorithm
}: {
arguments_: string[];
diffAlgorithm: DiffAlgorithm;
}): void {
switch (diffAlgorithm) {
case DiffAlgorithm.Default: {
arguments_.push('--diff-algorithm=default');
break;
@ -44,13 +44,15 @@ export function assignDiffAlgorithm(
}
}
export function assignWhitespaceIgnoreSettings(
arguments_: string[],
plugin: GitChangelogPlugin
): void {
const whitespaceIgnoreMode = getWhitespaceIgnoreMode(
plugin.settings.changelogGenerationSettings
);
export function assignWhitespaceIgnoreSettings({
arguments_,
whitespaceIgnoreMode,
ignoreBlankLines
}: {
arguments_: string[];
whitespaceIgnoreMode: WhitespaceIgnoreMode;
ignoreBlankLines: boolean;
}): void {
switch (whitespaceIgnoreMode) {
case WhitespaceIgnoreMode.None: {
break;
@ -69,7 +71,7 @@ export function assignWhitespaceIgnoreSettings(
}
}
if (plugin.settings.changelogGenerationSettings.ignoreBlankLines) {
if (ignoreBlankLines) {
arguments_.push('--ignore-blank-lines');
}
}

View file

@ -1,4 +1,4 @@
import type GitChangelogPlugin from 'main.ts';
import type { SimpleGit } from 'simple-git';
/**
* Doesn't work because of the way SimpleGit instance is set up in Git plugin.
@ -6,16 +6,15 @@ import type GitChangelogPlugin from 'main.ts';
export async function isAncestorOf({
newCommit,
oldCommit,
plugin
git
}: {
newCommit: string;
oldCommit: string;
plugin: GitChangelogPlugin;
git: SimpleGit;
}): Promise<boolean> {
if (oldCommit === newCommit) {
return true;
}
const git = await plugin.getGit();
const result = await git.raw([
'merge-base',
@ -23,7 +22,6 @@ export async function isAncestorOf({
oldCommit,
newCommit
]);
// Plugin.consoleDebug(result);
if (result === '1') {
return true;

View file

@ -1,22 +1,20 @@
import type GitChangelogPlugin from 'main.ts';
import type { SimpleGit } from 'simple-git';
import { AbortError } from 'types.ts';
export async function runCheckIgnore({
abortSignal,
activeGitFile,
plugin
git
}: {
abortSignal: AbortSignal;
activeGitFile: string;
plugin: GitChangelogPlugin;
git: SimpleGit;
}): Promise<boolean> {
if (abortSignal.aborted) {
throw new AbortError();
}
const gitCheckIgnoreResult = await plugin
.getGitPlugin()
.gitManager.git.checkIgnore(activeGitFile);
const gitCheckIgnoreResult = await git.checkIgnore(activeGitFile);
if (abortSignal.aborted) {
throw new AbortError();

View file

@ -1,8 +1,12 @@
import type GitChangelogPlugin from 'main.ts';
import type { FileLogEntry } from 'types.ts';
import type { SimpleGit } from 'simple-git';
import type {
DiffAlgorithm,
FileLogEntry,
WhitespaceIgnoreMode
} from 'types.ts';
import { FileChangelogEntry } from 'core/ChangelogEntry.svelte.ts';
import { getEmptyTreeHash } from 'core/gitOperations/getEmptyTreeHash.ts';
import {
assignDiffAlgorithm,
assignWhitespaceIgnoreSettings,
@ -14,19 +18,33 @@ export async function runFileDiff({
abortSignal,
newCommit,
oldCommit,
plugin
plugin,
git,
diffAlgorithm,
whitespaceIgnoreMode,
ignoreBlankLines,
emptyTreeHash
}: {
abortSignal: AbortSignal;
newCommit: FileLogEntry;
oldCommit?: FileLogEntry;
plugin: GitChangelogPlugin;
plugin?: GitChangelogPlugin;
git: SimpleGit;
diffAlgorithm: DiffAlgorithm;
whitespaceIgnoreMode: WhitespaceIgnoreMode;
ignoreBlankLines: boolean;
emptyTreeHash: string;
}): Promise<FileChangelogEntry | undefined> {
if (abortSignal.aborted) {
throw new AbortError();
}
const oldVersionIsEmpty =
oldCommit === undefined || oldCommit.fileDeleted === true;
if (oldVersionIsEmpty && newCommit.fileDeleted) {
// I assumed that the other should always be defined if one is undefined, since newCommit.hash is only undefined for commits where the file was deleted, and it can't get deleted if it didn't exist before, but these are statuses calculated from comparing neighboring commits, but we are diffing selected commits only, so maybe it's possible that we get in a situation where we compare some initial version commit (that isn't the actual initial commit, so that commit could be a deletion of that file, if a file was newly added and then deleted in the same interval) with an empty state
plugin.consoleDebug(
plugin?.consoleDebug(
'oldCommit and newCommit are both undefined, assumption is wrong'
);
@ -39,13 +57,15 @@ export async function runFileDiff({
'--no-renames'
// `--exit-code`,
];
assignDiffAlgorithm(numstatArguments, plugin);
assignWhitespaceIgnoreSettings(numstatArguments, plugin);
assignDiffAlgorithm({ arguments_: numstatArguments, diffAlgorithm });
assignWhitespaceIgnoreSettings({
arguments_: numstatArguments,
whitespaceIgnoreMode,
ignoreBlankLines
});
// Only one of these can be true at the same time since we are returning early if they are both true.
if (oldVersionIsEmpty || newCommit.fileDeleted) {
const emptyTreeHash = await getEmptyTreeHash({ plugin });
numstatArguments.push(
emptyTreeHash,
oldVersionIsEmpty ? newCommit.hash : oldCommit.hash,
@ -77,11 +97,6 @@ export async function runFileDiff({
);
}
if (abortSignal.aborted) {
throw new AbortError();
}
const git = await plugin.getGit();
const diffNumstatResult = await git.diffSummary(numstatArguments);
if (
@ -113,7 +128,7 @@ export async function runFileDiff({
pathGitRelative: newCommit.filePath, // Passing oldCommit.filePath or undefined for fileDeleted case could be more logical, but not compatible with use in git commands.
status: fileStatus,
textDiffStats,
timezoneAdjustedDate: newCommit.timezoneAdjustedDate
timeZoneAdjustedDate: newCommit.timeZoneAdjustedDate
});
return fileEntry;
}

View file

@ -0,0 +1,17 @@
import type { SimpleGit } from 'simple-git';
export async function runHashObjectEmptyTree({
git
}: {
git: SimpleGit;
}): Promise<string> {
const emptyTreeHash = await git.raw([
'hash-object',
'-t',
'tree',
'/dev/null'
]);
// Trimming is required.
return emptyTreeHash.trim();
}

View file

@ -1,9 +1,7 @@
import type GitChangelogPlugin from 'main.ts';
import type { SimpleGit } from 'simple-git';
import type { LogEntry } from 'types.ts';
import { unescapeGitFileOutput } from 'core/gitOperations/helper.ts';
import { getTimeZone } from 'settings/ui/CustomTimeZone.ts';
import { getRenameDetectionStrictness } from 'settings/ui/RenameDetectionStrictnessSlider.ts';
import spacetime from 'spacetime';
import { AbortError } from 'types.ts';
import { assertNotNull } from 'utils.ts';
@ -18,16 +16,23 @@ export async function runLog({
filePath,
lowerBoundaryCommit,
maxCount,
plugin,
upperBoundaryCommit
upperBoundaryCommit,
timeZone,
git,
renameDetectionStrictness
}: {
abortSignal: AbortSignal;
filePath: string | undefined;
lowerBoundaryCommit: string | undefined;
maxCount?: number;
plugin: GitChangelogPlugin;
upperBoundaryCommit: string | undefined;
git: SimpleGit;
timeZone: string;
renameDetectionStrictness: number;
}): Promise<LogEntry[]> {
if (abortSignal.aborted) {
throw new AbortError();
}
// This is confusing, and could be accidentally broken in the future
const retrievingNewLogs = lowerBoundaryCommit !== undefined;
const options: Record<string, unknown> = {
@ -50,8 +55,7 @@ export async function runLog({
// `--follow` does not work well on non-linear history. It does not work for files that were just renamed in the working directory but haven't been committed yet. It needs commit information to track renames.
// This problem can be solved by running a separate git diff name-status command before running git log, to detect potential renames and get the last committed filename of the current file, but the performance impact is not worth it.
options['--follow'] = null;
options['--find-renames'] =
`${getRenameDetectionStrictness(plugin.settings.changelogGenerationSettings)}%`;
options['--find-renames'] = `${renameDetectionStrictness}%`;
}
if (upperBoundaryCommit) {
@ -60,15 +64,8 @@ export async function runLog({
options['--boundary'] = null;
options[`${lowerBoundaryCommit}..HEAD`] = null;
}
if (abortSignal.aborted) {
throw new AbortError();
}
const git = await plugin.getGit();
const result = await git.log(options);
const timezone = getTimeZone(
plugin.settings.changelogGenerationSettings,
plugin
);
const logs: LogEntry[] = [];
for (const entry of result.all) {
@ -109,7 +106,7 @@ export async function runLog({
: undefined,
hash: entry.hash,
fileDeleted,
timezoneAdjustedDate: spacetime(entry.date).goto(timezone)
timeZoneAdjustedDate: spacetime(entry.date).goto(timeZone)
});
}
return logs;

View file

@ -1,9 +1,16 @@
/* eslint-disable no-magic-numbers */
import type GitChangelogPlugin from 'main.ts';
import type { DiffFile, FilesSummary, LogEntry, TextDiffFile } from 'types.ts';
import type { SimpleGit } from 'simple-git';
import type {
DiffAlgorithm,
DiffFile,
FilesSummary,
LogEntry,
TextDiffFile,
WhitespaceIgnoreMode
} from 'types.ts';
import { VaultChangelogEntry } from 'core/ChangelogEntry.svelte.ts';
import { getEmptyTreeHash } from 'core/gitOperations/getEmptyTreeHash.ts';
import {
addFileStatusToSummary,
assignDiffAlgorithm,
@ -11,8 +18,6 @@ import {
calculateFileStatusRenamedOrMoved
} from 'core/gitOperations/helper.ts';
import { convertGitIgnoreToPathspec } from 'settings/ui/ExcludeFilesAndFolders.ts';
import { getRenameLimit } from 'settings/ui/RenameDetectionFileLimit.ts';
import { getRenameDetectionStrictness } from 'settings/ui/RenameDetectionStrictnessSlider.ts';
import { AbortError, DiffFileStatus } from 'types.ts';
import { assertNotNull, insertSorted, parseContentChange } from 'utils.ts';
@ -54,65 +59,94 @@ export function compareTextFiles(
return leftFile.pathGitRelative.localeCompare(rightFile.pathGitRelative);
}
// eslint-disable-next-line complexity
export async function runRepoDiff({
abortSignal,
newCommit,
oldCommit,
plugin
git,
plugin,
excludeFilesAndFoldersLines,
convertToIncludeList,
renameLimit,
renameDetectionStrictness,
diffAlgorithm,
whitespaceIgnoreMode,
ignoreBlankLines,
emptyTreeHash,
enableExclusionList
}: {
abortSignal: AbortSignal;
newCommit: LogEntry;
oldCommit?: LogEntry;
plugin: GitChangelogPlugin;
diffAlgorithm: DiffAlgorithm;
git: SimpleGit;
excludeFilesAndFoldersLines: readonly string[];
enableExclusionList: boolean;
plugin?: GitChangelogPlugin;
convertToIncludeList: boolean;
renameLimit: number;
emptyTreeHash: string;
renameDetectionStrictness: number;
ignoreBlankLines: boolean;
whitespaceIgnoreMode: WhitespaceIgnoreMode;
}): Promise<undefined | VaultChangelogEntry> {
if (newCommit === undefined) {
plugin.consoleDebug('newCommit is undefined');
plugin?.consoleDebug('newCommit is undefined');
}
if (abortSignal.aborted) {
throw new AbortError();
}
const pathSpec = convertGitIgnoreToPathspec(
plugin.settings.vaultChangelogGenerationSettings.excludeFilesAndFoldersLines
);
const pathSpec = enableExclusionList
? convertGitIgnoreToPathspec(
excludeFilesAndFoldersLines,
convertToIncludeList
)
: undefined;
const numstatArguments = [
'--numstat',
`-l${getRenameLimit(plugin.settings.changelogGenerationSettings)}`,
`--find-renames=${getRenameDetectionStrictness(plugin.settings.changelogGenerationSettings)}%`,
`-l${renameLimit}`,
`--find-renames=${renameDetectionStrictness}%`,
'--color-moved=no',
// Don't use empty files as rename candidates. If you delete any empty file and add a new empty file, that file will be considered a rename unless this flag is used.
'--no-rename-empty',
'-z'
];
assignDiffAlgorithm(numstatArguments, plugin);
assignWhitespaceIgnoreSettings(numstatArguments, plugin);
assignDiffAlgorithm({ arguments_: numstatArguments, diffAlgorithm });
assignWhitespaceIgnoreSettings({
arguments_: numstatArguments,
whitespaceIgnoreMode,
ignoreBlankLines
});
let statusResult: Record<string, DiffFileStatus> | undefined;
if (oldCommit === undefined) {
const emptyTreeHash = await getEmptyTreeHash({ plugin });
numstatArguments.push(emptyTreeHash, newCommit.hash);
} else {
statusResult = await runRepoDiffStatus({
newCommit: newCommit.hash,
oldCommit: oldCommit.hash,
pathSpec,
plugin
plugin,
abortSignal,
git
});
numstatArguments.push(oldCommit.hash, newCommit.hash);
}
if (pathSpec.length > 0) {
if (pathSpec && pathSpec.length > 0) {
numstatArguments.push('--', ...pathSpec);
}
const diffNumstatResult = await git.diff(numstatArguments);
if (abortSignal.aborted) {
throw new AbortError();
}
const git = await plugin.getGit();
const diffNumstatResult = await git.diff(numstatArguments);
const records = diffNumstatResult.split('\0').filter((token) => token !== '');
@ -169,7 +203,7 @@ export async function runRepoDiff({
status = DiffFileStatus.Added;
} else if (oldPath) {
if (typeof oldPath !== 'string') {
plugin.consoleDebug('oldPath is not a string', oldPath);
plugin?.consoleDebug('oldPath is not a string', oldPath);
}
status = calculateFileStatusRenamedOrMoved(oldPath, filePath);
} else if (assertNotNull(statusResult)[filePath]) {
@ -210,10 +244,10 @@ export async function runRepoDiff({
binaryFiles,
binaryFilesSummaryCached: binaryFilesSummary,
commitHash: newCommit.hash,
previousDayLastCommitHash: oldCommit?.hash,
previousVersionLastCommitHash: oldCommit?.hash,
textFiles,
textFilesSummaryCached: textFilesSummary,
timezoneAdjustedDate: newCommit.timezoneAdjustedDate
timeZoneAdjustedDate: newCommit.timeZoneAdjustedDate
});
return dayEntry;

View file

@ -1,6 +1,7 @@
import type GitChangelogPlugin from 'main.ts';
import type { SimpleGit } from 'simple-git';
import { DiffFileStatus } from 'types.ts';
import { AbortError, DiffFileStatus } from 'types.ts';
import type { DiffResultNameStatusFile } from './simpleGitTypes.ts';
@ -13,13 +14,21 @@ export async function runRepoDiffStatus({
newCommit,
oldCommit,
pathSpec,
plugin
git,
plugin,
abortSignal
}: {
newCommit: string;
oldCommit?: string;
pathSpec: string[];
plugin: GitChangelogPlugin;
pathSpec: string[] | undefined;
plugin?: GitChangelogPlugin;
abortSignal: AbortSignal;
git: SimpleGit;
}): Promise<Record<string, DiffFileStatus> | undefined> {
if (abortSignal.aborted) {
throw new AbortError();
}
if (oldCommit === undefined) {
return undefined;
}
@ -35,10 +44,9 @@ export async function runRepoDiffStatus({
// If after applying the diff settings, some changed files in runRepoDiff become identical, the runRepoDiff function will simply skip those, and those same files that were detected as changes in this function are never going to be accessed, so they can't return incorrect file statuses.
// Also, crossing the rename threshold because of diff settings mismatch isn't a concern since this function isn't used to determine renamed file statuses.
if (pathSpec.length > 0) {
if (pathSpec && pathSpec.length > 0) {
diffStatusArguments.push('--', ...pathSpec);
}
const git = await plugin.getGit();
const diffStatusResult = await git.diffSummary(diffStatusArguments);
const changedFilesMap: Record<string, DiffFileStatus> = {};
@ -60,7 +68,7 @@ export async function runRepoDiffStatus({
file.status ?? DiffNameStatus.MODIFIED
)
) {
plugin.consoleDebug(
plugin?.consoleDebug(
`Unexpected file status of ${file.file}:`,
file.status
);

View file

@ -1,6 +1,11 @@
/* eslint-disable unicorn/prevent-abbreviations */
import type GitChangelogPlugin from 'main.ts';
import type { LogEntry, TextDiffBaseStats } from 'types.ts';
import type { SimpleGit } from 'simple-git';
import type {
DiffAlgorithm,
LogEntry,
TextDiffBaseStats,
WhitespaceIgnoreMode
} from 'types.ts';
import {
assignDiffAlgorithm,
@ -14,32 +19,41 @@ import { AbortError } from 'types.ts';
export async function runWorkingDirFileDiff({
abortSignal,
oldCommit,
plugin,
activeGitFile
activeGitFile,
git,
diffAlgorithm,
whitespaceIgnoreMode,
ignoreBlankLines
}: {
diffAlgorithm: DiffAlgorithm;
abortSignal: AbortSignal;
oldCommit: LogEntry;
activeGitFile: string;
plugin: GitChangelogPlugin;
git: SimpleGit;
whitespaceIgnoreMode: WhitespaceIgnoreMode;
ignoreBlankLines: boolean;
}): Promise<TextDiffBaseStats | undefined> {
if (abortSignal.aborted) {
throw new AbortError();
}
// Status bar calculations should handle cases of undefined oldCommit and oldCommit.fileDeleted === true before reaching this function
const numstatArguments = ['--numstat', '--color-moved=no', '--no-renames'];
// Must come before the commit hashes and file paths
assignDiffAlgorithm(numstatArguments, plugin);
assignWhitespaceIgnoreSettings(numstatArguments, plugin);
assignDiffAlgorithm({ arguments_: numstatArguments, diffAlgorithm });
assignWhitespaceIgnoreSettings({
arguments_: numstatArguments,
whitespaceIgnoreMode,
ignoreBlankLines
});
numstatArguments.push(
`${oldCommit.hash}:${oldCommit.filePath}`,
activeGitFile
);
if (abortSignal.aborted) {
throw new AbortError();
}
const git = await plugin.getGit();
const diffNumstatResult = await git.diffSummary(numstatArguments);
const textDiffStats =

View file

@ -1,9 +1,12 @@
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
import type { GitChangelogPluginTypes } from 'constants.ts';
import type { ExtractPluginSettingsWrapper } from 'obsidian-dev-utils/obsidian/Plugin/PluginTypesBase';
import type { Spacetime, TimeUnit } from 'spacetime';
import type { ReadonlyDeep } from 'type-fest';
import type { ChangelogInterval, FilesSummary, LogEntry } from 'types.ts';
import { getDayStartTime } from 'settings/ui/DayStartTime.ts';
import { applyDayStartTimeSetting } from 'timeUtils.ts';
import { deepEqual } from 'obsidian-dev-utils/Object';
import { pickGeneralChangelogSettings } from 'settings/settings.ts';
import { applyDayStartHourSetting } from 'timeUtils.ts';
export const GIT_MAX_CONCURRENT_PROCESSES = 6;
@ -68,24 +71,24 @@ export async function isSameAsync({
}
export async function extractLastCommitsForInterval({
changelogGenerationSettings,
interval,
previouslySeenFullyAdjustedDates,
timezoneAdjustedLogs
timeZoneAdjustedLogs,
dayStartHour
}: {
changelogGenerationSettings: ChangelogGenerationSettings;
interval: ChangelogInterval;
previouslySeenFullyAdjustedDates?: Set<Spacetime>;
timezoneAdjustedLogs: LogEntry[];
timeZoneAdjustedLogs: LogEntry[];
dayStartHour: number;
}): Promise<LogEntry[]> {
const lastCommitsInEachInterval: LogEntry[] = [];
const fullyAdjustedSeenDates =
previouslySeenFullyAdjustedDates ?? new Set<Spacetime>();
for (const log of timezoneAdjustedLogs) {
const fullyAdjustedLogDate = applyDayStartTimeSetting({
dayStartTime: getDayStartTime(changelogGenerationSettings),
timezoneAdjustedDate: log.timezoneAdjustedDate
for (const log of timeZoneAdjustedLogs) {
const fullyAdjustedLogDate = applyDayStartHourSetting({
dayStartHour,
timeZoneAdjustedDate: log.timeZoneAdjustedDate
});
const logDateAlreadySeen = await dateAlreadySeen({
@ -102,3 +105,24 @@ export async function extractLastCommitsForInterval({
return lastCommitsInEachInterval;
}
export function changelogGenerationSettingsChanged({
newSettings,
oldSettings
}: {
newSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>;
oldSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>;
}): boolean {
const oldVaultGenerationSettings = pickGeneralChangelogSettings(oldSettings);
const newVaultGenerationSettings = pickGeneralChangelogSettings(newSettings);
// IsAncestor run
// Don't have to check if the detected system time zone or detected locale changed since they're only assigned once at startup.
return !deepEqual(oldVaultGenerationSettings, newVaultGenerationSettings);
}

View file

@ -1,5 +1,6 @@
import type GitChangelogPlugin from 'main.ts';
import type { MenuItem, WorkspaceLeaf } from 'obsidian';
import type { WorkspaceLeaf } from 'obsidian';
import type { GitChangelogSettings } from 'settings/settings.ts';
import { COPY_COMMIT_HASH_ICON, PLUGIN_NAME_SENTENCE_CASE } from 'constants.ts';
import { Menu, TFolder } from 'obsidian';
@ -14,17 +15,15 @@ import { VAULT_CHANGELOG_VIEW_CONFIG } from 'Views/VaultChangelog/VaultChangelog
export function addContextMenuItems(plugin: GitChangelogPlugin): void {
plugin.registerEvent(
plugin.app.workspace.on('file-menu', (menu, file) => {
menu.addItem((item) => {
const gitRelativePath = plugin
.getGitPlugin()
.gitManager.getRelativeRepoPath(file.path, true);
const gitRelativePath = plugin
.getGitPlugin()
.gitManager.getRelativeRepoPath(file.path, true);
addExcludeMenuItem({
item,
isFolder: file instanceof TFolder,
gitRelativePath,
plugin
});
addExcludeMenuItem({
menu,
isFolder: file instanceof TFolder,
gitRelativePath,
plugin
});
})
);
@ -97,41 +96,78 @@ export function mayTriggerChangelogMenu({
}
}
/**
* Check if the path is a relative path that goes above the root of the repository.
*
* If it starts with any number of /../, that means it's above the root.
*
* This is parsing the output of getRelativeRepoPath function.
*
* "../" is acceptable. (Non-absolute path)
*/
function isAbsoluteGitIgnoreRuleAboveRoot({
absoluteGitIgnoreRule
}: {
absoluteGitIgnoreRule: string;
}): boolean {
return (
absoluteGitIgnoreRule.startsWith('/../') ||
// Case when path is the root folder itself
absoluteGitIgnoreRule.startsWith('//')
);
}
export function addExcludeMenuItem({
item,
menu,
isFolder,
plugin,
gitRelativePath
}: {
item: MenuItem;
menu: Menu;
isFolder: boolean;
gitRelativePath: string;
plugin: GitChangelogPlugin;
}): void {
// The ExcludeFilesAndFolders rules are applied relative to the git repo.
// Only check absolute rules, we don't want to modify any relative rules that also affect other files
const lineNumber = isAbsolutePathInExcludeFilesAndFolders({
const absoluteGitIgnoreRule = convertPathToAbsoluteGitIgnoreRule({
isFolder,
gitRelativePath,
plugin
gitRelativePath
});
const ruleAlreadyExists = lineNumber !== -1;
const actionTitle = ruleAlreadyExists ? 'Reinclude' : 'Exclude';
// Don't add the menu item if the path is above the root of the repository. Otherwise git would throw this error when trying to use this rule in pathspec:
// Fatal: :(exclude,glob)../xx/**: '../xx/**' is outside repository at '/path/to/vault/repo'
if (isAbsoluteGitIgnoreRuleAboveRoot({ absoluteGitIgnoreRule })) {
return;
}
item
.setSection('action')
.setTitle(`${PLUGIN_NAME_SENTENCE_CASE}: ${actionTitle}`)
.setIcon(VAULT_CHANGELOG_VIEW_CONFIG.icon)
.onClick(async () => {
await (ruleAlreadyExists
? removeExcludeFilesAndFoldersItem(lineNumber, plugin)
: addExcludeFilesAndFoldersItem({
gitRelativePath,
isFolder,
plugin
}));
menu.addItem((item) => {
// The ExcludeFilesAndFolders rules are applied relative to the git repo.
// Only check absolute rules, we don't want to modify any relative rules that also affect other files
const lineNumber = isAbsoluteGitIgnoreRuleInExcludeFilesAndFolders({
absoluteGitIgnoreRule,
plugin
});
const ruleAlreadyExists = lineNumber !== -1;
const isIncludeList = plugin.settings.convertToIncludeList;
let actionTitle: string;
if (isIncludeList) {
actionTitle = ruleAlreadyExists ? 'Re-exclude' : 'Include';
} else {
actionTitle = ruleAlreadyExists ? 'Reinclude' : 'Exclude';
}
item
.setSection('action')
.setTitle(`${PLUGIN_NAME_SENTENCE_CASE}: ${actionTitle}`)
.setIcon(VAULT_CHANGELOG_VIEW_CONFIG.icon)
.onClick(async () => {
await (ruleAlreadyExists
? removeExcludeFilesAndFoldersItem(lineNumber, plugin)
: addExcludeFilesAndFoldersItem({
path: absoluteGitIgnoreRule,
plugin
}));
});
});
}
export function handleChangelogViewContextMenu({
@ -149,13 +185,11 @@ export function handleChangelogViewContextMenu({
}): void {
// Skip adding the "Git changelog: Exclude" item again if the usual file menu is shown.
if (!inFileMenu && gitRelativePath) {
menu.addItem((item) => {
addExcludeMenuItem({
item,
isFolder: false,
gitRelativePath,
plugin
});
addExcludeMenuItem({
menu,
isFolder: false,
gitRelativePath,
plugin
});
}
@ -205,59 +239,48 @@ export function convertPathToAbsoluteGitIgnoreRule({
return convertPathToGitIgnoreRule(composedPath);
}
export function isAbsolutePathInExcludeFilesAndFolders({
isFolder,
gitRelativePath,
/**
* Checks if a given absolute gitignore rule exists in the plugin's exclude files and folders settings
* @param gitIgnoreAbsoluteRule - The absolute gitignore rule to check for
* @param plugin - The GitChangelogPlugin instance
* @returns The line number (index) where the rule was found, or -1 if not found
*/
export function isAbsoluteGitIgnoreRuleInExcludeFilesAndFolders({
absoluteGitIgnoreRule,
plugin
}: {
isFolder: boolean;
gitRelativePath: string;
absoluteGitIgnoreRule: string;
plugin: GitChangelogPlugin;
}): number {
const gitIgnoreAbsoluteRule = convertPathToAbsoluteGitIgnoreRule({
isFolder,
gitRelativePath
});
const existingLines =
plugin.settingsClone.vaultChangelogGenerationSettings
.excludeFilesAndFoldersLines;
const existingLines = plugin.settings.excludeFilesAndFoldersLines;
// Trim unescaped trailing white space from existing lines, since it gets trimmed by git anyways.
// By doing this we won't miss already existing lines that only differ in trailing white space.
const existingRules = existingLines.map((line) => parseGitIgnoreLine(line));
return existingRules.indexOf(gitIgnoreAbsoluteRule);
return existingRules.indexOf(absoluteGitIgnoreRule);
}
export async function removeExcludeFilesAndFoldersItem(
lineNumber: number,
plugin: GitChangelogPlugin
): Promise<void> {
const newSettings = plugin.settingsClone;
newSettings.vaultChangelogGenerationSettings.excludeFilesAndFoldersLines.splice(
lineNumber,
1
await plugin.settingsManager.editAndSave(
(settings: GitChangelogSettings): void => {
settings.excludeFilesAndFoldersLines.splice(lineNumber, 1);
}
);
await plugin.saveSettings(newSettings);
}
export async function addExcludeFilesAndFoldersItem({
gitRelativePath,
isFolder,
path,
plugin
}: {
gitRelativePath: string;
isFolder: boolean;
path: string;
plugin: GitChangelogPlugin;
}): Promise<void> {
const gitIgnoreRule = convertPathToAbsoluteGitIgnoreRule({
gitRelativePath,
isFolder
});
const newSettings = plugin.settingsClone;
newSettings.vaultChangelogGenerationSettings.excludeFilesAndFoldersLines.push(
gitIgnoreRule
await plugin.settingsManager.editAndSave(
(settings: GitChangelogSettings): void => {
settings.excludeFilesAndFoldersLines.push(path);
}
);
await plugin.saveSettings(newSettings);
}

View file

@ -1,38 +1,25 @@
import type GitChangelogPlugin from 'main.ts';
import type { TextComponent } from 'obsidian';
import type {
ChangelogGenerationSettings,
IGitChangelogSettings
} from 'settings/settings.ts';
import type { GitChangelogSettingsTab } from 'settings/settingsTab.ts';
import { moment } from 'obsidian';
import { NumberComponent } from 'obsidian-dev-utils/obsidian/Components/NumberComponent';
import { TimeComponent } from 'obsidian-dev-utils/obsidian/Components/TimeComponent';
import { SettingEx } from 'obsidian-dev-utils/obsidian/SettingEx';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
export abstract class GitChangelogSetting {
export abstract class SettingComponent {
protected containerEl: HTMLElement;
protected disabled: boolean;
protected plugin: GitChangelogPlugin;
protected settingTab?: GitChangelogSettingsTab;
protected settingTab: GitChangelogSettingsTab;
public constructor({
containerEl,
disabled = false,
plugin,
settingTab
plugin
}: {
containerEl: HTMLElement;
disabled?: boolean;
plugin: GitChangelogPlugin;
settingTab?: GitChangelogSettingsTab;
}) {
this.plugin = plugin;
this.containerEl = containerEl;
this.disabled = disabled;
this.settingTab = settingTab;
this.settingTab = this.plugin.settingsTab;
this.containerEl = this.settingTab.containerEl;
}
public abstract display(): void;
@ -53,46 +40,9 @@ export abstract class GitChangelogSetting {
*/
protected refreshDisplayWithDelay(timeout = 80): void {
if (this.settingTab) {
setTimeout(() => this.settingTab?.display(), timeout);
}
}
/**
* Sets the value in the textbox for a given setting only if the saved value differs from the default value.
* If the saved value is the default value, it probably wasn't defined by the user, so it's better to display it as a placeholder.
*/
protected setNonDefaultValue({
diffSettingsProperty,
settingsProperty,
text
}: {
diffSettingsProperty?: keyof ChangelogGenerationSettings;
settingsProperty: keyof IGitChangelogSettings;
text: NumberComponent | TextComponent | TimeComponent;
}): void {
const storedValue = diffSettingsProperty
? (this.plugin.settings[settingsProperty] as ChangelogGenerationSettings)[
diffSettingsProperty
]
: this.plugin.settings[settingsProperty];
const defaultValue = diffSettingsProperty
? (DEFAULT_SETTINGS[settingsProperty] as ChangelogGenerationSettings)[
diffSettingsProperty
]
: DEFAULT_SETTINGS[settingsProperty];
if (defaultValue !== storedValue) {
if (text instanceof NumberComponent) {
text.setValue(Number(storedValue));
} else if (text instanceof TimeComponent) {
text.setValue(moment.duration({ hours: Number(storedValue) }));
} else {
text.setValue(
typeof storedValue === 'object'
? JSON.stringify(storedValue)
: String(storedValue)
);
}
setTimeout(() => {
this.settingTab?.display();
}, timeout);
}
}
}

View file

@ -13,23 +13,23 @@ export class TimeZoneSuggest extends AbstractInputSuggest<string> {
public getSuggestions(inputString: string): string[] {
const lowerCaseInputString = inputString.toLowerCase();
const timezones: string[] = [];
const timeZones: string[] = [];
for (const timezone of TIME_ZONES_LIST) {
if (timezone.toLowerCase().contains(lowerCaseInputString)) {
timezones.push(timezone);
for (const timeZone of TIME_ZONES_LIST) {
if (timeZone.toLowerCase().contains(lowerCaseInputString)) {
timeZones.push(timeZone);
}
}
return timezones;
return timeZones;
}
public renderSuggestion(timezone: string, element: HTMLElement): void {
element.setText(timezone);
public renderSuggestion(timeZone: string, element: HTMLElement): void {
element.setText(timeZone);
}
public override selectSuggestion(timezone: string): void {
this.inputEl.value = timezone;
public override selectSuggestion(timeZone: string): void {
this.inputEl.value = timeZone;
this.inputEl.trigger('input');
this.close();
}

View file

@ -1,37 +0,0 @@
import type GitChangelogPlugin from 'main.ts';
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
import { deepEqual } from 'obsidian-dev-utils/Object';
import {
systemTimeZoneUnchanged,
validateCustomTimeZone
} from 'settings/ui/CustomTimeZone.ts';
export function changelogGenerationSettingsChanged({
newChangelogSettings,
oldChangelogSettings,
plugin
}: {
newChangelogSettings: ChangelogGenerationSettings;
oldChangelogSettings: ChangelogGenerationSettings;
plugin: GitChangelogPlugin;
}): boolean {
if (!oldChangelogSettings) {
return true;
}
// IsAncestor run
if (
!validateCustomTimeZone(newChangelogSettings.timezone) &&
!systemTimeZoneUnchanged(plugin)
) {
return true;
}
if (deepEqual(oldChangelogSettings, newChangelogSettings)) {
return false;
}
return true;
}

View file

@ -1,11 +1,14 @@
import { PluginSettingsBase } from 'obsidian-dev-utils/obsidian/Plugin/PluginSettingsBase';
import type { GitChangelogPluginTypes } from 'constants.ts';
import type { ExtractPluginSettingsWrapper } from 'obsidian-dev-utils/obsidian/Plugin/PluginTypesBase';
import type { Except, ReadonlyDeep } from 'type-fest';
import spacetime from 'spacetime';
import {
ChangelogInterval,
DiffAlgorithm,
DiffMeasurementUnit,
FileExplorerStats,
FilesSummariesDisplayMode,
FileSummariesDisplayMode,
WhitespaceIgnoreMode
} from 'types.ts';
@ -15,140 +18,186 @@ export const TIME_ZONES_LIST = new Set(Object.keys(spacetime().timezones));
export const MAX_SUPPORTED_INTERVAL = 99_999; // ~69 days
export const AUTO_DETECT_PLACEHOLDER = 'Auto-detect';
/**
* Each change in these settings triggers a recalculation of the changelogs statistics.
*/
export interface ChangelogGenerationSettings {
// Time settings
dayStartHour: number;
// Diff settings
detectMovedContent: boolean;
diffAlgorithm: DiffAlgorithm;
measurementUnit: DiffMeasurementUnit;
renameDetectionStrictness: number;
renameLimit: string;
timezone: string;
locale: string;
whitespaceIgnoreMode: WhitespaceIgnoreMode;
ignoreBlankLines: boolean;
}
export interface VaultChangelogGenerationSettings {
excludeFilesAndFoldersLines: string[];
interval: ChangelogInterval;
}
export interface IGitChangelogSettings {
autoCommitDisabledWarningDismissed: boolean;
changelogGenerationSettings: ChangelogGenerationSettings;
contentDeletionsAndMovesWarningThreshold: string;
dedicatedFileTypeSummaries: string[];
fileChangelogInterval: ChangelogInterval;
fileExplorerInterval: string;
fileExplorerStats: FileExplorerStats;
filesChangesWarningThreshold: string;
fileSummariesDisplayMode: FilesSummariesDisplayMode;
firstStartup: boolean;
notifyOnContentDeletionsAndMovesThresholdReached: boolean;
notifyOnFilesChangesThresholdReached: boolean;
statusBarInterval: string;
statusBarStats: boolean;
vaultChangelogGenerationSettings: VaultChangelogGenerationSettings;
}
export class GitChangelogPluginSettings
extends PluginSettingsBase
implements IGitChangelogSettings
{
// State
public autoCommitDisabledWarningDismissed: boolean =
DEFAULT_SETTINGS.autoCommitDisabledWarningDismissed;
public firstStartup: boolean = DEFAULT_SETTINGS.firstStartup;
public changelogGenerationSettings: ChangelogGenerationSettings =
DEFAULT_CHANGELOG_GENERATION_SETTINGS;
/**
* The number refers to either words or lines depending on what the changelog is set up to count
*/
public contentDeletionsAndMovesWarningThreshold: string =
DEFAULT_SETTINGS.contentDeletionsAndMovesWarningThreshold;
export class GitChangelogSettings {
// Plugin state
public autoCommitDisabledWarningDismissed = false;
public firstStartup = true;
public activeMinutesPassedSinceLastCheckpoint = 0;
// ShowFilesSummaryCountOptions[]; //Set<ShowFilesSummaryCountOptions>;
// VaultChangelogFilesVisibility: VaultChangelogFilesVisibility;
// NotifyOnLargeCommitAdditions: boolean;
// NotifyOnLargeCommitAdditionsWarningThreshold: string;
public dedicatedFileTypeSummaries: string[] = [
...DEFAULT_SETTINGS.dedicatedFileTypeSummaries
];
public dedicatedFileTypeSummaries: string[] = [];
public fileSummariesDisplayMode: FileSummariesDisplayMode =
FileSummariesDisplayMode.Total;
public fileChangelogInterval: ChangelogInterval =
DEFAULT_SETTINGS.fileChangelogInterval;
public fileExplorerInterval = '4320'; // In mins
public fileExplorerStats: FileExplorerStats = FileExplorerStats.Disabled;
public fileExplorerInterval: string = DEFAULT_SETTINGS.fileExplorerInterval;
public fileExplorerStats: FileExplorerStats =
DEFAULT_SETTINGS.fileExplorerStats;
public notifyOnHighContentDeletionsAndMoves = true;
/**
* The number refers to either words or lines depending on what the changelog is set up to count
*/
public contentDeletionsAndMovesWarningThreshold = '2000';
public filesChangesWarningThreshold: string =
DEFAULT_SETTINGS.filesChangesWarningThreshold;
public notifyOnHighFilesChanged = false;
public filesChangedWarningThreshold = '50';
public fileSummariesDisplayMode: FilesSummariesDisplayMode =
DEFAULT_SETTINGS.fileSummariesDisplayMode;
public checkpointCommits: string[] = [];
public reviewChangesReminderInterval = 0;
public notifyOnContentDeletionsAndMovesThresholdReached: boolean =
DEFAULT_SETTINGS.notifyOnContentDeletionsAndMovesThresholdReached;
public statusBarInterval = 30; // In mins
public showStatusBarStats = false;
public notifyOnFilesChangesThresholdReached: boolean =
DEFAULT_SETTINGS.notifyOnFilesChangesThresholdReached;
// FileGenerationSettings
public fileChangelogInterval: ChangelogInterval = ChangelogInterval.Daily;
public statusBarInterval: string = DEFAULT_SETTINGS.statusBarInterval;
public statusBarStats: boolean = DEFAULT_SETTINGS.statusBarStats;
// Specific Changelog Generation Settings
public vaultChangelogGenerationSettings: VaultChangelogGenerationSettings =
DEFAULT_VAULT_CHANGELOG_GENERATION_SETTINGS;
// VaultGenerationSettings
public excludeFilesAndFoldersLines: string[] = [];
public enableExclusionList = true;
public convertToIncludeList = false;
public vaultChangelogInterval = ChangelogInterval.Daily;
public constructor(data: unknown) {
super();
// Object.assign(this, DEFAULT_SETTINGS);
this.init(data);
this._shouldSaveAfterLoad = true;
}
/**
* Each change in these settings triggers a recalculation of all the changelogs statistics.
*/
// Time settings
public dayStartHour = 0;
// Diff settings
public detectMovedContent = true;
public diffAlgorithm = DiffAlgorithm.Inherit;
public diffMeasurementUnit = DiffMeasurementUnit.Words;
public renameDetectionStrictness = 50;
public renameLimit = 1000;
public timeZone = AUTO_DETECT_PLACEHOLDER;
public locale = AUTO_DETECT_PLACEHOLDER;
public whitespaceIgnoreMode = WhitespaceIgnoreMode.None;
public ignoreBlankLines = false;
}
export const DEFAULT_VAULT_CHANGELOG_GENERATION_SETTINGS: VaultChangelogGenerationSettings =
{
excludeFilesAndFoldersLines: [],
interval: ChangelogInterval.Daily
} as const;
// This is needed for checking if the specific generation settings have changed. And on each new added setting, the developer will have to explicitly include or exclude the added setting from all of these categories.
export const DEFAULT_CHANGELOG_GENERATION_SETTINGS: ChangelogGenerationSettings =
{
dayStartHour: 0,
detectMovedContent: true,
diffAlgorithm: DiffAlgorithm.Inherit,
measurementUnit: DiffMeasurementUnit.Words,
renameDetectionStrictness: 50,
renameLimit: '1000',
timezone: AUTO_DETECT_PLACEHOLDER,
locale: AUTO_DETECT_PLACEHOLDER,
whitespaceIgnoreMode: WhitespaceIgnoreMode.None,
ignoreBlankLines: false
} as const;
export const DEFAULT_SETTINGS: IGitChangelogSettings = {
autoCommitDisabledWarningDismissed: false,
changelogGenerationSettings: DEFAULT_CHANGELOG_GENERATION_SETTINGS,
vaultChangelogGenerationSettings: DEFAULT_VAULT_CHANGELOG_GENERATION_SETTINGS,
contentDeletionsAndMovesWarningThreshold: '2000',
dedicatedFileTypeSummaries: [] as const,
fileChangelogInterval: ChangelogInterval.Daily,
fileExplorerInterval: '4320', // In mins
fileExplorerStats: FileExplorerStats.Disabled,
filesChangesWarningThreshold: '50',
fileSummariesDisplayMode: FilesSummariesDisplayMode.Total,
firstStartup: true,
notifyOnContentDeletionsAndMovesThresholdReached: true,
notifyOnFilesChangesThresholdReached: false,
statusBarInterval: '30', // In mins
statusBarStats: false
} as const;
export function pickVaultChangelogSettings(
settings: ReadonlyDeep<ExtractPluginSettingsWrapper<GitChangelogPluginTypes>>
): ReadonlyDeep<VaultGenerationSettings> {
return {
excludeFilesAndFoldersLines:
settings.safeSettings.excludeFilesAndFoldersLines,
convertToIncludeList: settings.safeSettings.convertToIncludeList,
vaultChangelogInterval: settings.safeSettings.vaultChangelogInterval,
enableExclusionList: settings.safeSettings.enableExclusionList
};
}
export function pickFileChangelogSettings(
settings: ReadonlyDeep<ExtractPluginSettingsWrapper<GitChangelogPluginTypes>>
): ReadonlyDeep<FileGenerationSettings> {
return {
fileChangelogInterval: settings.safeSettings.fileChangelogInterval
};
}
export function pickGeneralChangelogSettings(
settings: ReadonlyDeep<ExtractPluginSettingsWrapper<GitChangelogPluginTypes>>
): ReadonlyDeep<GenerationSettings> {
return {
dayStartHour: settings.safeSettings.dayStartHour,
detectMovedContent: settings.safeSettings.detectMovedContent,
diffAlgorithm: settings.safeSettings.diffAlgorithm,
diffMeasurementUnit: settings.safeSettings.diffMeasurementUnit,
renameDetectionStrictness: settings.safeSettings.renameDetectionStrictness,
renameLimit: settings.safeSettings.renameLimit,
timeZone: settings.safeSettings.timeZone,
whitespaceIgnoreMode: settings.safeSettings.whitespaceIgnoreMode,
ignoreBlankLines: settings.safeSettings.ignoreBlankLines
};
}
type VaultGenerationSettings = Except<
GitChangelogSettings,
| 'activeMinutesPassedSinceLastCheckpoint'
| 'autoCommitDisabledWarningDismissed'
| 'checkpointCommits'
| 'contentDeletionsAndMovesWarningThreshold'
| 'dayStartHour'
| 'dedicatedFileTypeSummaries'
| 'detectMovedContent'
| 'diffAlgorithm'
| 'diffMeasurementUnit'
| 'fileChangelogInterval'
| 'fileExplorerInterval'
| 'fileExplorerStats'
| 'filesChangedWarningThreshold'
| 'fileSummariesDisplayMode'
| 'firstStartup'
| 'ignoreBlankLines'
| 'locale'
| 'notifyOnHighContentDeletionsAndMoves'
| 'notifyOnHighFilesChanged'
| 'renameDetectionStrictness'
| 'renameLimit'
| 'reviewChangesReminderInterval'
| 'showStatusBarStats'
| 'statusBarInterval'
| 'timeZone'
| 'whitespaceIgnoreMode'
>;
type FileGenerationSettings = Except<
GitChangelogSettings,
| 'activeMinutesPassedSinceLastCheckpoint'
| 'autoCommitDisabledWarningDismissed'
| 'checkpointCommits'
| 'contentDeletionsAndMovesWarningThreshold'
| 'convertToIncludeList'
| 'dayStartHour'
| 'dedicatedFileTypeSummaries'
| 'detectMovedContent'
| 'diffAlgorithm'
| 'diffMeasurementUnit'
| 'enableExclusionList'
| 'excludeFilesAndFoldersLines'
| 'fileExplorerInterval'
| 'fileExplorerStats'
| 'filesChangedWarningThreshold'
| 'fileSummariesDisplayMode'
| 'firstStartup'
| 'ignoreBlankLines'
| 'locale'
| 'notifyOnHighContentDeletionsAndMoves'
| 'notifyOnHighFilesChanged'
| 'renameDetectionStrictness'
| 'renameLimit'
| 'reviewChangesReminderInterval'
| 'showStatusBarStats'
| 'statusBarInterval'
| 'timeZone'
| 'vaultChangelogInterval'
| 'whitespaceIgnoreMode'
>;
type GenerationSettings = Except<
GitChangelogSettings,
| 'activeMinutesPassedSinceLastCheckpoint'
| 'autoCommitDisabledWarningDismissed'
| 'checkpointCommits'
| 'contentDeletionsAndMovesWarningThreshold'
| 'convertToIncludeList'
| 'dedicatedFileTypeSummaries'
| 'enableExclusionList'
| 'excludeFilesAndFoldersLines'
| 'fileChangelogInterval'
| 'fileExplorerInterval'
| 'fileExplorerStats'
| 'filesChangedWarningThreshold'
| 'fileSummariesDisplayMode'
| 'firstStartup'
| 'locale'
| 'notifyOnHighContentDeletionsAndMoves'
| 'notifyOnHighFilesChanged'
| 'reviewChangesReminderInterval'
| 'showStatusBarStats'
| 'statusBarInterval'
| 'vaultChangelogInterval'
>;

View file

@ -0,0 +1,277 @@
import type { GitChangelogPluginTypes } from 'constants.ts';
import type { MaybeReturn } from 'obsidian-dev-utils/Type';
import {
MAX_RENAME_DETECTION_STRICTNESS,
MIN_RENAME_DETECTION_STRICTNESS
} from 'constants.ts';
import { Notice } from 'obsidian';
import { PluginSettingsManagerBase } from 'obsidian-dev-utils/obsidian/Plugin/PluginSettingsManagerBase';
import {
GitChangelogSettings,
MAX_SUPPORTED_INTERVAL
} from 'settings/settings.ts';
import { validateLocale } from 'settings/ui/CustomLocale.ts';
import { validateCustomTimeZone } from 'settings/ui/CustomTimeZone.ts';
import {
ChangelogInterval,
DiffAlgorithm,
DiffMeasurementUnit,
FileExplorerStats,
WhitespaceIgnoreMode
} from 'types.ts';
export class GitChangelogSettingsManager extends PluginSettingsManagerBase<GitChangelogPluginTypes> {
// eslint-disable-next-line @typescript-eslint/require-await
protected override async onLoadRecord(
record: Record<string, unknown>
): Promise<void> {
// Only migrate if this is legacy data - check for the existence of the old settings structure
if ('vaultChangelogGenerationSettings' in record) {
// Check if the legacy excludeFilesAndFoldersLines data exists
const vaultSettings = record.vaultChangelogGenerationSettings as
| Record<string, unknown>
| undefined;
const legacyExcludeLines = vaultSettings?.excludeFilesAndFoldersLines;
// Check if we need to migrate (legacy data exists)
if (
legacyExcludeLines &&
Array.isArray(legacyExcludeLines) &&
legacyExcludeLines.length > 0 &&
(record.excludeFilesAndFoldersLines === undefined ||
record.excludeFilesAndFoldersLines === null ||
!Array.isArray(record.excludeFilesAndFoldersLines) ||
record.excludeFilesAndFoldersLines.length === 0)
) {
// Migrate the data
record.excludeFilesAndFoldersLines = legacyExcludeLines;
// Remove the old settings structure to prevent future migrations
delete record.vaultChangelogGenerationSettings;
// We are assuming that the user is updating their plugin version, so we show the "what's changed" notification and alert the user that some of their settings broke.
const whatsNewFragment = createFragment((element) => {
element.createEl('p', {
text: 'Git changelog:\nA new version has been installed.\n\nSome of your settings for this plugin have been reset!'
});
element.createEl('button', { text: 'Close' });
const seeButton = element.createEl('button', { text: "What's new?" });
seeButton.onClickEvent(() => {
window.open(
'https://github.com/shumadrid/obsidian-git-changelog/releases'
);
});
seeButton.addClass('git-changelog-left-padding');
});
new Notice(whatsNewFragment, 0);
}
}
}
protected override createDefaultSettings(): GitChangelogSettings {
return new GitChangelogSettings();
}
protected override registerValidators(): void {
super.registerValidators();
// If the active minutes cache is corrupted then just reset it.
this.registerValidator(
'activeMinutesPassedSinceLastCheckpoint',
(activeMinutesPassedSinceLastCheckpoint): MaybeReturn<string> => {
if (
!Number.isInteger(activeMinutesPassedSinceLastCheckpoint) ||
activeMinutesPassedSinceLastCheckpoint < 0
) {
// Reset to 0 if corrupted
return 'Corrupted value detected. Resetting to 0.';
}
}
);
this.registerValidator(
'diffMeasurementUnit',
(measurementUnit): MaybeReturn<string> => {
if (!Object.values(DiffMeasurementUnit).includes(measurementUnit)) {
return 'Choose a valid option.';
}
}
);
this.registerValidator(
'contentDeletionsAndMovesWarningThreshold',
(contentDeletionsAndMovesWarningThreshold): MaybeReturn<string> => {
if (
!Number.isInteger(Number(contentDeletionsAndMovesWarningThreshold)) ||
Number(contentDeletionsAndMovesWarningThreshold) < 1
) {
return 'Pick a positive whole number.';
}
}
);
this.registerValidator('locale', (locale): MaybeReturn<string> => {
if (!validateLocale(locale) && locale !== this.defaultSettings.locale) {
return 'Invalid locale code.';
}
});
this.registerValidator('timeZone', (timeZone): MaybeReturn<string> => {
if (
!validateCustomTimeZone(timeZone) &&
timeZone !== this.defaultSettings.timeZone
) {
return 'Invalid timezone.';
}
});
const ONE_DAY_IN_HOURS = 24;
this.registerValidator(
'dayStartHour',
(dayStartHour): MaybeReturn<string> => {
if (
!Number.isInteger(dayStartHour) ||
dayStartHour < 0 ||
dayStartHour >= ONE_DAY_IN_HOURS
) {
return 'Invalid time.';
}
}
);
this.registerValidator(
'diffAlgorithm',
(diffAlgorithm): MaybeReturn<string> => {
if (!Object.values(DiffAlgorithm).includes(diffAlgorithm)) {
return 'Choose a valid option.';
}
}
);
this.registerValidator(
'filesChangedWarningThreshold',
(filesChangedWarningThreshold): MaybeReturn<string> => {
if (
!Number.isInteger(Number(filesChangedWarningThreshold)) ||
Number(filesChangedWarningThreshold) < 1
) {
return 'Pick a positive whole number.';
}
}
);
this.registerValidator(
'fileExplorerStats',
(fileExplorerStats): MaybeReturn<string> => {
if (!Object.values(FileExplorerStats).includes(fileExplorerStats)) {
return 'Choose a valid option.';
}
}
);
this.registerValidator(
'fileExplorerInterval',
(fileExplorerInterval): MaybeReturn<string> => {
if (
!Number.isInteger(Number(fileExplorerInterval)) ||
Number(fileExplorerInterval) < 1 ||
Number(fileExplorerInterval) > MAX_SUPPORTED_INTERVAL
) {
return `Pick a positive whole number not greater than ${MAX_SUPPORTED_INTERVAL}.`;
}
}
);
this.registerValidator(
'renameLimit',
(renameLimit): MaybeReturn<string> => {
if (
!(
Number.isInteger(renameLimit) &&
Number(renameLimit) >= 0 &&
// eslint-disable-next-line no-magic-numbers
Number(renameLimit) <= 99_999_999_999_999_999_999n
)
) {
return 'Pick a non-negative whole number.';
}
}
);
this.registerValidator(
'reviewChangesReminderInterval',
(reviewChangesReminderInterval): MaybeReturn<string> => {
if (
!(
Number.isInteger(reviewChangesReminderInterval) &&
Number(reviewChangesReminderInterval) >= 0 &&
// eslint-disable-next-line no-magic-numbers
Number(reviewChangesReminderInterval) <= 999_999_999
)
) {
return 'Pick a non-negative whole number.';
}
}
);
this.registerValidator(
'renameDetectionStrictness',
(renameDetectionStrictness): MaybeReturn<string> => {
if (
!Number.isInteger(renameDetectionStrictness) ||
renameDetectionStrictness < MIN_RENAME_DETECTION_STRICTNESS ||
renameDetectionStrictness > MAX_RENAME_DETECTION_STRICTNESS
) {
return `Pick a whole number between ${MIN_RENAME_DETECTION_STRICTNESS} and ${MAX_RENAME_DETECTION_STRICTNESS}.`;
}
}
);
this.registerValidator(
'statusBarInterval',
(statusBarInterval): MaybeReturn<string> => {
if (
!Number.isInteger(Number(statusBarInterval)) ||
Number(statusBarInterval) < 1 ||
Number(statusBarInterval) > MAX_SUPPORTED_INTERVAL
) {
return `Pick a positive whole number not greater than ${MAX_SUPPORTED_INTERVAL}.`;
}
}
);
this.registerValidator(
'whitespaceIgnoreMode',
(whitespaceIgnoreMode): MaybeReturn<string> => {
if (
!Object.values(WhitespaceIgnoreMode).includes(whitespaceIgnoreMode)
) {
return 'Choose a valid option.';
}
}
);
this.registerValidator(
'fileChangelogInterval',
(fileChangelogInterval): MaybeReturn<string> => {
if (!Object.values(ChangelogInterval).includes(fileChangelogInterval)) {
return 'Choose a valid option.';
}
}
);
this.registerValidator(
'vaultChangelogInterval',
(vaultChangelogInterval): MaybeReturn<string> => {
if (
!Object.values(ChangelogInterval).includes(vaultChangelogInterval)
) {
return 'Choose a valid option.';
}
}
);
}
}

View file

@ -1,25 +1,27 @@
import type { GitChangelogPlugin } from 'GitChangelogPlugin.svelte.ts';
import type { GitChangelogPluginTypes } from 'constants.ts';
import { PluginSettingsTabBase } from 'obsidian-dev-utils/obsidian/Plugin/PluginSettingsTabBase';
import { CustomLocale } from 'settings/ui/CustomLocale.ts';
import { DayStartHour } from 'settings/ui/DayStartTime.ts';
import { DiffAlgorithmOptions } from 'settings/ui/DiffAlgorithmOptions.ts';
import { IgnoreBlankLinesToggle } from 'settings/ui/IgnoreBlankLinesToggle.ts';
import { IncludeItemsToggle } from 'settings/ui/IncludeItemsToggle.ts';
import { MiscellaneousButtons } from 'settings/ui/MiscellaneousButtons.ts';
import { WhitespaceIgnoreModeOptions } from 'settings/ui/WhitespaceIgnoreMode.ts';
import { WhitespaceSettingsHeading } from 'settings/ui/WhitespaceSettingsHeading.ts';
import { AutoCommitDisabledWarning } from './ui/AutoCommitDisabledWarning.ts';
import { CustomTimeZone } from './ui/CustomTimeZone.ts';
import { DayStartTime } from './ui/DayStartTime.ts';
import { ExcludeFilesAndFolders } from './ui/ExcludeFilesAndFolders.ts';
import { GitPluginWarning } from './ui/GitPluginWarning.ts';
import { RenameDetectionFileLimit } from './ui/RenameDetectionFileLimit.ts';
import { RenameDetectionStrictnessSlider } from './ui/RenameDetectionStrictnessSlider.ts';
import { ReviewChangesReminderInterval } from './ui/ReviewChangesReminderInterval.ts';
import { StatusBarInterval } from './ui/StatusBarInterval.ts';
import { StatusBarStatsToggle } from './ui/StatusBarStatsToggle.ts';
// Commented-out settings are for features that will be implemented later
export class GitChangelogSettingsTab extends PluginSettingsTabBase<GitChangelogPlugin> {
export class GitChangelogSettingsTab extends PluginSettingsTabBase<GitChangelogPluginTypes> {
public override display(): void {
const { containerEl, plugin } = this;
@ -28,88 +30,62 @@ export class GitChangelogSettingsTab extends PluginSettingsTabBase<GitChangelogP
// Plugin.settings.notifyIfContentDeletionsAndMovesThresholdReached ??
// DEFAULT_SETTINGS.notifyIfContentDeletionsAndMovesThresholdReached;
new GitPluginWarning({ containerEl, plugin }).display();
new GitPluginWarning({ plugin }).display();
new AutoCommitDisabledWarning({
containerEl,
plugin
}).display();
new AutoCommitDisabledWarning({ plugin }).display();
new DayStartTime({ containerEl, plugin }).display();
new DayStartHour({ plugin }).display();
new CustomTimeZone({ containerEl, plugin }).display();
new CustomTimeZone({ plugin }).display();
new CustomLocale({ containerEl, plugin }).display();
new CustomLocale({ plugin }).display();
new DiffAlgorithmOptions({
containerEl,
plugin,
settingTab: this
}).display();
new DiffAlgorithmOptions({ plugin }).display();
// New DeletionsNotificationThreshold(plugin, containerEl, false, this).display();
// New DeletionsNotificationThreshold(plugin, false, this).display();
// New configureDeletionsMovesAlert(
// Plugin,
// ContainerEl,
//
// !notifyOnLargeChanges
// ).display();
// New FileChangesNotificationThreshold(
// Plugin,
// ContainerEl,
//
// NotifyOnLargeChanges
// ).display();
// New ChangelogStatsInFileExplorerOptions(plugin, containerEl, false, this).display();
// New ChangelogStatsInFileExplorerOptions(plugin, false, this).display();
// New FileExplorerStatsInterval(
// Plugin,
// ContainerEl,
//
// (plugin.settings?.fileExplorerChangelogStats ??
// DEFAULT_SETTINGS.fileExplorerChangelogStats) ===
// FileExplorerChangelogStats.Disabled
// ).display();
new ExcludeFilesAndFolders({ containerEl, plugin }).display();
new ExcludeFilesAndFolders({ plugin }).display();
new RenameDetectionStrictnessSlider({
containerEl,
plugin
}).display();
new IncludeItemsToggle({ plugin }).display();
new RenameDetectionFileLimit({
containerEl,
plugin
}).display();
new RenameDetectionStrictnessSlider({ plugin }).display();
new StatusBarStatsToggle({
containerEl,
plugin,
settingTab: this
}).display();
new RenameDetectionFileLimit({ plugin }).display();
new StatusBarStatsToggle({ plugin }).display();
new StatusBarInterval({
containerEl,
disabled: !plugin.settings.statusBarStats,
disabled: !plugin.settings.showStatusBarStats,
plugin
}).display();
new WhitespaceSettingsHeading({
containerEl,
plugin
}).display();
new ReviewChangesReminderInterval({ plugin }).display();
new WhitespaceIgnoreModeOptions({
containerEl,
plugin
}).display();
new WhitespaceSettingsHeading({ plugin }).display();
new IgnoreBlankLinesToggle({
containerEl,
plugin
}).display();
new WhitespaceIgnoreModeOptions({ plugin }).display();
new MiscellaneousButtons({
containerEl,
plugin
}).display();
new IgnoreBlankLinesToggle({ plugin }).display();
new MiscellaneousButtons({ plugin }).display();
}
// New DetectMovedContentToggle(plugin, containerEl).display();
// New ChangelogMeasurementUnit(plugin, containerEl).display();

View file

@ -1,6 +1,8 @@
import { GitChangelogSetting } from 'settings/components/setting.ts';
import type { GitChangelogSettings } from 'settings/settings.ts';
export class AutoCommitDisabledWarning extends GitChangelogSetting {
import { SettingComponent } from 'settings/components/setting.ts';
export class AutoCommitDisabledWarning extends SettingComponent {
public display(): void {
try {
const gitPlugin = this.plugin.getGitPlugin();
@ -19,10 +21,12 @@ export class AutoCommitDisabledWarning extends GitChangelogSetting {
button.onClick(() => {
warningSetting.settingEl.remove();
const newSettings = this.plugin.settingsClone;
newSettings.autoCommitDisabledWarningDismissed = true;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
this.plugin.settingsManager.editAndSave(
(settings: GitChangelogSettings): void => {
settings.autoCommitDisabledWarningDismissed = true;
}
);
});
});
}

View file

@ -1,48 +1,14 @@
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { SettingComponent } from 'settings/components/setting.ts';
import { DiffMeasurementUnit } from 'types.ts';
export class ChangelogMeasurementUnit extends GitChangelogSetting {
export class ChangelogMeasurementUnit extends SettingComponent {
public display(): void {
this.createSetting()
.setName('Changelog measurement unit')
.addDropdown((dropdown) => {
const options = {
[DiffMeasurementUnit.Lines]: 'Lines',
[DiffMeasurementUnit.Words]: 'Words'
};
dropdown.addOptions(options);
dropdown.setValue(
getMeasurementUnit(this.plugin.settings.changelogGenerationSettings)
);
dropdown.onChange((value: DiffMeasurementUnit) => {
const newSettings = this.plugin.settingsClone;
newSettings.changelogGenerationSettings.measurementUnit = value;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
});
.addTypedDropdown((dropdown) => {
dropdown.addOption(DiffMeasurementUnit.Lines, 'Lines');
dropdown.addOption(DiffMeasurementUnit.Words, 'Words');
this.settingTab.bind(dropdown, 'diffMeasurementUnit');
});
}
}
export function getMeasurementUnit(
changelogGenerationSettings: ChangelogGenerationSettings
): DiffMeasurementUnit {
return DiffMeasurementUnit.Lines;
if (!validateMeasurementUnit(changelogGenerationSettings.measurementUnit)) {
return DEFAULT_SETTINGS.changelogGenerationSettings.measurementUnit;
}
return changelogGenerationSettings.measurementUnit;
}
export function validateMeasurementUnit(
measurementUnit: DiffMeasurementUnit
): boolean {
if (Object.values(DiffMeasurementUnit).includes(measurementUnit)) {
return true;
}
return false;
}

View file

@ -1,29 +1,23 @@
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { SettingComponent } from 'settings/components/setting.ts';
import { FileExplorerStats } from 'types.ts';
export class ChangelogStatsInFileExplorerOptions extends GitChangelogSetting {
export class ChangelogStatsInFileExplorerOptions extends SettingComponent {
public display(): void {
this.createSetting()
.setName('Show changelog stats in file explorer')
.addDropdown((dropdown) => {
const options = {
[FileExplorerStats.Disabled]: 'Disabled',
[FileExplorerStats.Folders]: 'Folders',
[FileExplorerStats.FoldersAndNotes]: 'Folders and notes'
};
dropdown.addOptions(options);
dropdown.setValue(
this.plugin.settings.fileExplorerStats ??
DEFAULT_SETTINGS.fileExplorerStats
.addTypedDropdown((dropdown) => {
dropdown.addOption(FileExplorerStats.Disabled, 'Disabled');
dropdown.addOption(FileExplorerStats.Folders, 'Folders');
dropdown.addOption(
FileExplorerStats.FoldersAndNotes,
'Folders and notes'
);
dropdown.onChange((value: FileExplorerStats) => {
this.refreshDisplayWithDelay(0);
const newSettings = this.plugin.settingsClone;
newSettings.fileExplorerStats = value;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
this.settingTab.bind(dropdown, 'fileExplorerStats', {
onChanged: () => {
// eslint-disable-next-line no-magic-numbers
this.refreshDisplayWithDelay(30);
}
});
});
}

View file

@ -1,7 +1,6 @@
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { SettingComponent } from 'settings/components/setting.ts';
export class ContentDeletionsMovesThreshold extends GitChangelogSetting {
export class ContentDeletionsMovesThreshold extends SettingComponent {
public display(): void {
this.createSetting()
.setName('Custom threshold for deletions/moves alert')
@ -9,33 +8,10 @@ export class ContentDeletionsMovesThreshold extends GitChangelogSetting {
"Acceptable amount of deletions and moves between commits. Represents either words or lines, depending on your setup. Note that this doesn't mean between each interval but between the actual commits, meaning if your auto-commit interval is five minutes, this will trigger only if you manage to delete that many files inside those five minutes, which usually signals corruption or data loss."
)
.addText((text) => {
text.setDisabled(this.disabled).onChange((value) => {
const newSettings = this.plugin.settingsClone;
newSettings.contentDeletionsAndMovesWarningThreshold =
validateContentDeletionsMovesThreshold(value)
? value
: DEFAULT_SETTINGS.contentDeletionsAndMovesWarningThreshold;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
});
text.setDisabled(this.disabled);
// This.restrictToPositiveIntegerInput(text);
this.setNonDefaultValue({
settingsProperty: 'contentDeletionsAndMovesWarningThreshold',
text
});
this.settingTab.bind(text, 'contentDeletionsAndMovesWarningThreshold');
});
}
}
export function validateContentDeletionsMovesThreshold(
contentDeletionsMovesThreshold: string
): boolean {
if (
!Number.isInteger(Number(contentDeletionsMovesThreshold)) ||
Number(contentDeletionsMovesThreshold) < 1
) {
return false;
}
return true;
}

View file

@ -1,50 +1,63 @@
import type GitChangelogPlugin from 'main.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { SettingComponent } from 'settings/components/setting.ts';
export class CustomLocale extends GitChangelogSetting {
export class CustomLocale extends SettingComponent {
public display(): void {
this.createSetting()
.setName('Date format locale')
.setDesc(`Accepts a locale code (e.g. "en-US").`)
.addText((text) => {
text.inputEl.maxLength = 30;
text
.setPlaceholder(DEFAULT_SETTINGS.changelogGenerationSettings.locale)
.onChange((value) => {
const newSettings = this.plugin.settingsClone;
newSettings.changelogGenerationSettings.locale = value;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
});
this.setNonDefaultValue({
settingsProperty: 'changelogGenerationSettings',
diffSettingsProperty: 'locale',
text
this.settingTab.bind(text, 'locale', {
onChanged: () => {
// Without this check, plugin fails on startup
if (this.plugin.settingsManager) {
this.plugin.localeSafe = getLocaleToAssign(this.plugin);
}
}
});
});
}
}
export function getUserLocale(plugin: GitChangelogPlugin): string {
const locale = plugin.settings.changelogGenerationSettings.locale;
if (validateLocale(locale)) {
return locale;
function getSystemLocale(plugin: GitChangelogPlugin): string {
if (plugin.detectedLocale === undefined) {
// Detect the system locale using Intl API and save it for the current Obsidian session.
const systemLocale = Intl.DateTimeFormat().resolvedOptions().locale;
if (validateLocale(systemLocale)) {
plugin.detectedLocale = systemLocale;
} else {
plugin.displayNotice(
"Couldn't detect a valid system locale: Obsidian installer version might be too old.\nFallback to en-US."
);
plugin.detectedLocale = 'en-US';
}
}
// Decided against using the new Obsidian language API so that the plugin is compatible with older versions of Obsidian (for now, will update later).
return Intl.DateTimeFormat().resolvedOptions().locale;
return plugin.detectedLocale;
}
export function validateLocale(locale?: string): boolean {
export function getLocaleToAssign(plugin: GitChangelogPlugin): string {
return plugin.settings.locale ===
plugin.settingsManager.defaultSettings.locale
? getSystemLocale(plugin)
: plugin.settings.locale;
}
export function validateLocale(locale: string): boolean {
try {
if (!locale || typeof locale !== 'string') {
return false;
}
new Intl.Locale(locale);
return Intl.DateTimeFormat.supportedLocalesOf([locale]).length > 0;
if (Intl.DateTimeFormat.supportedLocalesOf([locale]).length === 0) {
return false;
}
} catch {
return false;
}
return true;
}

View file

@ -1,77 +1,48 @@
import type GitChangelogPlugin from 'main.ts';
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
import { Notice } from 'obsidian';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { SettingComponent } from 'settings/components/setting.ts';
import { TimeZoneSuggest } from 'settings/components/suggest.ts';
import { DEFAULT_SETTINGS, TIME_ZONES_LIST } from 'settings/settings.ts';
import { TIME_ZONES_LIST } from 'settings/settings.ts';
export class CustomTimeZone extends GitChangelogSetting {
export class CustomTimeZone extends SettingComponent {
public display(): void {
this.createSetting()
.setName('Timezone')
.addText((text) => {
text
.setPlaceholder(DEFAULT_SETTINGS.changelogGenerationSettings.timezone)
.onChange((value) => {
const newSettings = this.plugin.settingsClone;
newSettings.changelogGenerationSettings.timezone = value;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
});
this.setNonDefaultValue({
diffSettingsProperty: 'timezone',
settingsProperty: 'changelogGenerationSettings',
text
});
this.settingTab.bind(text, 'timeZone');
new TimeZoneSuggest(this.plugin.app, text.inputEl);
});
}
}
export function detectSystemTimeZone(): string {
return Intl.DateTimeFormat().resolvedOptions().timeZone.toLowerCase();
}
function getSystemTimeZone(plugin: GitChangelogPlugin): string {
if (plugin.detectedTimeZone === undefined) {
// Detect the system time zone using Intl API and save it for the current Obsidian session.
const systemTimeZone = Intl.DateTimeFormat()
.resolvedOptions()
.timeZone.toLowerCase();
export function getSystemTimeZone(plugin: GitChangelogPlugin): string {
if (plugin.detectedTimeZone !== undefined) {
return plugin.detectedTimeZone;
if (validateCustomTimeZone(systemTimeZone)) {
plugin.detectedTimeZone = systemTimeZone;
} else {
plugin.displayNotice(
"Couldn't detect a valid system time zone: Obsidian installer version might be too old.\nFallback to UTC."
);
plugin.detectedTimeZone = 'utc';
}
}
const systemTimeZone = detectSystemTimeZone();
if (validateCustomTimeZone(systemTimeZone)) {
plugin.detectedTimeZone = systemTimeZone;
} else {
new Notice(
"Couldn't detect a valid system time zone: Obsidian installer version might be too old.\nFallback to UTC."
);
plugin.detectedTimeZone = 'utc';
return 'utc';
}
return plugin.detectedTimeZone;
}
export function getTimeZone(
changelogGenerationSettings: ChangelogGenerationSettings,
plugin: GitChangelogPlugin
): string {
return validateCustomTimeZone(changelogGenerationSettings.timezone)
? changelogGenerationSettings.timezone
: getSystemTimeZone(plugin);
export function getTimeZone(plugin: GitChangelogPlugin): string {
return plugin.settings.timeZone ===
plugin.settingsManager.defaultSettings.timeZone
? getSystemTimeZone(plugin)
: plugin.settings.timeZone;
}
export function systemTimeZoneUnchanged(plugin: GitChangelogPlugin): boolean {
const systemTimeZone = detectSystemTimeZone();
const cachedSystemTimeZone = plugin.detectedTimeZone;
if (systemTimeZone !== cachedSystemTimeZone) {
plugin.detectedTimeZone = systemTimeZone;
return false;
}
return true;
}
export function validateCustomTimeZone(timezone: string): boolean {
return TIME_ZONES_LIST.has(timezone.toLowerCase());
export function validateCustomTimeZone(timeZone: string): boolean {
return TIME_ZONES_LIST.has(timeZone.toLowerCase());
}

View file

@ -1,60 +1,32 @@
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
import { moment } from 'obsidian';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { SettingComponent } from 'settings/components/setting.ts';
export class DayStartTime extends GitChangelogSetting {
export class DayStartHour extends SettingComponent {
public display(): void {
this.createSetting()
.setName('Day start time')
.setDesc('Adjust the day based on your schedule.')
.setDesc(
'Adjust the day based on your schedule. Applies exclusively to the day interval in the changelog views.'
)
.addTime((text) => {
text
.setValue(
moment.duration({
hours:
this.plugin.settings.changelogGenerationSettings.dayStartHour
})
)
.onChange((value) => {
this.settingTab.bind(text, 'dayStartHour', {
componentToPluginSettingsValueConverter: (
uiValue: moment.Duration
) => {
// Clip any minutes. The smallest possible interval is an hour and this value should be clipped to that.
// Allowing the day start time to be specified in minutes doesn't make sense because then you would need to handle the half an hour that belongs to the previous day and the other half an hour that belongs to the next day separately.
text.setValue(
moment.duration({
hours: value.hours()
})
);
const newSettings = this.plugin.settingsClone;
newSettings.changelogGenerationSettings.dayStartHour =
value.hours();
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
});
text.inputEl.step = '3600';
// Allowing the day start time to be specified in minutes doesn't make sense because then e.g. you would need to handle the half an hour that belongs to the previous day and the other half an hour that belongs to the next day separately.
return uiValue.hours();
},
onChanged: (value) => {
text.setValue(moment.duration(value, 'hours'));
},
shouldShowValidationMessage: false,
pluginSettingsToComponentValueConverter: (
pluginSettingsValue: number
) => moment.duration(pluginSettingsValue, 'hours')
});
// eslint-disable-next-line no-magic-numbers
text.setStep(3600);
});
}
}
export function getDayStartTime(
changelogGenerationSettings: ChangelogGenerationSettings
): number {
return validateDayStartTime(changelogGenerationSettings.dayStartHour)
? changelogGenerationSettings.dayStartHour
: DEFAULT_SETTINGS.changelogGenerationSettings.dayStartHour;
}
export const ONE_DAY_IN_HOURS = 24;
export function validateDayStartTime(dayStartTime: number): boolean {
if (
!Number.isInteger(dayStartTime) ||
dayStartTime < 0 ||
dayStartTime >= ONE_DAY_IN_HOURS
) {
return false;
}
return true;
}

View file

@ -1,27 +1,18 @@
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { SettingComponent } from 'settings/components/setting.ts';
export class DeletionsNotificationThreshold extends GitChangelogSetting {
export class DeletionsNotificationThreshold extends SettingComponent {
public display(): void {
this.createSetting()
.setName('Notify on large amount of changes.')
.setDesc(
'Notify if changes between neighboring commits exceed a threshold, which can be a sign of data loss or corruption.'
)
.addToggle((toggle) =>
toggle
.setValue(
this.plugin.settings
.notifyOnContentDeletionsAndMovesThresholdReached
)
.onChange((value) => {
const newSettings = this.plugin.settingsClone;
newSettings.notifyOnContentDeletionsAndMovesThresholdReached =
value;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
.addToggle((toggle) => {
this.settingTab.bind(toggle, 'notifyOnHighContentDeletionsAndMoves', {
onChanged: () => {
this.refreshDisplayWithDelay();
})
);
}
});
});
}
}

View file

@ -1,6 +1,6 @@
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { SettingComponent } from 'settings/components/setting.ts';
export class DetectMovedContentToggle extends GitChangelogSetting {
export class DetectMovedContentToggle extends SettingComponent {
public display(): void {
this.createSetting()
.setName('Detect moved lines/words')
@ -8,16 +8,7 @@ export class DetectMovedContentToggle extends GitChangelogSetting {
`If enabled, changelog will also track all moved words or lines between files or moved to another location in the same file. Adds significant computational overhead that increases with the number and size of changes.`
)
.addToggle((toggle) =>
toggle
.setValue(
this.plugin.settings.changelogGenerationSettings.detectMovedContent
)
.onChange((value) => {
const newSettings = this.plugin.settingsClone;
newSettings.changelogGenerationSettings.detectMovedContent = value;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
})
this.settingTab.bind(toggle, 'detectMovedContent')
);
}
}

View file

@ -1,14 +1,12 @@
import type GitChangelogPlugin from 'main.ts';
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
import { appendCodeBlock } from 'obsidian-dev-utils/HTMLElement';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { SettingComponent } from 'settings/components/setting.ts';
import { DiffAlgorithm } from 'types.ts';
const GIT_CONFIG_PATH = '.git/config';
export class DiffAlgorithmOptions extends GitChangelogSetting {
export class DiffAlgorithmOptions extends SettingComponent {
public display(): void {
this.createSetting()
.setName('Difference detection algorithm')
@ -27,9 +25,7 @@ export class DiffAlgorithmOptions extends GitChangelogSetting {
button.setButtonText('Apply');
button.setDisabled(shouldDisableApplyButton(this.plugin));
button.onClick(async () => {
const diffAlgorithm = getDiffAlgorithm(
this.plugin.settings.changelogGenerationSettings
);
const diffAlgorithm = this.plugin.settings.diffAlgorithm;
if (diffAlgorithm !== DiffAlgorithm.Inherit) {
try {
const git = await this.plugin.getGit();
@ -45,51 +41,24 @@ export class DiffAlgorithmOptions extends GitChangelogSetting {
}
});
})
.addDropdown((dropdown) => {
const options = {
[DiffAlgorithm.Inherit]: 'Inherit git config',
[DiffAlgorithm.Default]: 'Default (Faster)',
[DiffAlgorithm.Minimal]: 'Minimal (More precise)'
} as const;
dropdown.addOptions(options);
dropdown.setValue(
getDiffAlgorithm(this.plugin.settings.changelogGenerationSettings)
);
dropdown.onChange((value: DiffAlgorithm) => {
const newSettings = this.plugin.settingsClone;
newSettings.changelogGenerationSettings.diffAlgorithm = value;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings).then(() => {
.addTypedDropdown((dropdown) => {
dropdown.addOption(DiffAlgorithm.Inherit, 'Inherit git config');
dropdown.addOption(DiffAlgorithm.Default, 'Default (Faster)');
dropdown.addOption(DiffAlgorithm.Minimal, 'Minimal (More precise)');
this.settingTab.bind(dropdown, 'diffAlgorithm', {
onChanged: () => {
// eslint-disable-next-line no-magic-numbers
this.refreshDisplayWithDelay(30);
});
}
});
});
}
}
function shouldDisableApplyButton(plugin: GitChangelogPlugin): boolean {
const diffAlgorithm = getDiffAlgorithm(
plugin.settings.changelogGenerationSettings
);
const diffAlgorithm = plugin.settings.diffAlgorithm;
if (diffAlgorithm === DiffAlgorithm.Inherit) {
return true;
}
return false;
}
export function getDiffAlgorithm(
changelogGenerationSettings: ChangelogGenerationSettings
): DiffAlgorithm {
if (
!Object.values(DiffAlgorithm).includes(
changelogGenerationSettings.diffAlgorithm
)
) {
return DEFAULT_SETTINGS.changelogGenerationSettings.diffAlgorithm;
}
return changelogGenerationSettings.diffAlgorithm;
}

View file

@ -2,15 +2,15 @@
import type { ReadonlyDeep } from 'type-fest';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { EXCLUDE_FILES_AND_FOLDERS } from 'constants.ts';
import { SettingComponent } from 'settings/components/setting.ts';
export class ExcludeFilesAndFolders extends GitChangelogSetting {
export class ExcludeFilesAndFolders extends SettingComponent {
public display(): void {
this.createSetting()
.setName(
createFragment((fragment) => {
fragment.appendText(`Exclude files and folders`);
fragment.appendText(EXCLUDE_FILES_AND_FOLDERS);
fragment
.createEl('span', {
cls: 'nav-file-tag git-changelog-experimental'
@ -38,23 +38,30 @@ export class ExcludeFilesAndFolders extends GitChangelogSetting {
fragment.appendText("Don't forget to put .md for markdown files.");
})
)
.addToggle((toggle) => {
this.settingTab.bind(toggle, 'enableExclusionList', {
onChanged: () => {
this.refreshDisplayWithDelay();
}
});
toggle.setTooltip(
`List is ${toggle.getValue() ? 'enabled' : 'temporarily disabled'}`
);
})
.addTextArea((text) => {
text
.setValue(
joinExcludeItems(
this.plugin.settingsClone.vaultChangelogGenerationSettings
.excludeFilesAndFoldersLines ??
DEFAULT_SETTINGS.vaultChangelogGenerationSettings
.excludeFilesAndFoldersLines
)
)
.onChange((value) => {
const newSettings = this.plugin.settingsClone;
newSettings.vaultChangelogGenerationSettings.excludeFilesAndFoldersLines =
splitExcludeItems(value);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
});
text.setDisabled(!this.plugin.settings.enableExclusionList);
if (!this.plugin.settings.enableExclusionList) {
text.inputEl.addClass('git-changelog-disabled');
}
this.settingTab.bind(text, 'excludeFilesAndFoldersLines', {
componentToPluginSettingsValueConverter: (uiValue) =>
splitExcludeItems(uiValue),
pluginSettingsToComponentValueConverter: (pluginSettingsValue) =>
joinExcludeItems(pluginSettingsValue)
});
text.inputEl.classList.add('git-changelog-text-area');
});
}
@ -69,7 +76,7 @@ export function convertPathToGitIgnoreRule(path: string): string {
return escaped.replaceAll(/\s(?=\s*$)/g, String.raw`\ `);
}
export function joinExcludeItems(items: string[]): string {
export function joinExcludeItems(items: readonly string[]): string {
return items.join('\n');
}
@ -86,11 +93,14 @@ export function parseGitIgnoreLine(gitIgnoreLine: string): string {
}
export function convertGitIgnoreToPathspec(
gitIgnoreRules: ReadonlyDeep<string[]>
gitIgnoreRules: ReadonlyDeep<string[]>,
include: boolean
): string[] {
try {
// Always exclude .git directory
const excludes: string[] = [':(exclude,glob)**/.git/**'];
const items: string[] = [];
// eslint-disable-next-line @typescript-eslint/no-unnecessary-boolean-literal-compare
const excludePrefix = include === true ? '' : 'exclude,';
for (const line of gitIgnoreRules.map((element) =>
parseGitIgnoreLine(element)
@ -104,21 +114,20 @@ export function convertGitIgnoreToPathspec(
// Handle patterns differently based on their format:
if (line.endsWith('/*')) {
// Single-level match
excludes.push(`:(exclude,glob)${formatted}`);
items.push(`:(${excludePrefix}glob)${formatted}`);
} else if (line.endsWith('/**') || line.endsWith('/')) {
// Recursive match
excludes.push(`:(exclude,glob)${formatted}`);
items.push(`:(${excludePrefix}glob)${formatted}`);
} else {
// All other patterns - match both item and contents
// Regardless of whether they contain special characters
excludes.push(
`:(exclude,glob)${formatted}`,
`:(exclude,glob)${formatted}/**`
items.push(
`:(${excludePrefix}glob)${formatted}`,
`:(${excludePrefix}glob)${formatted}/**`
);
}
}
return excludes;
return items;
} catch {
return [];
}

View file

@ -1,39 +1,15 @@
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { SettingComponent } from 'settings/components/setting.ts';
export class FileChangesNotificationThreshold extends GitChangelogSetting {
export class FileChangesNotificationThreshold extends SettingComponent {
public display(): void {
this.createSetting()
.setName('Custom threshold for file changes alert')
.addText((text) => {
text.setDisabled(this.disabled).onChange((value) => {
const newSettings = this.plugin.settingsClone;
newSettings.contentDeletionsAndMovesWarningThreshold =
validateFileChangesNotificationThreshold(value)
? value
: DEFAULT_SETTINGS.contentDeletionsAndMovesWarningThreshold;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
});
// This.restrictToPositiveIntegerInput(text);
this.settingTab.bind(text, 'filesChangedWarningThreshold');
this.setNonDefaultValue({
settingsProperty: 'filesChangesWarningThreshold',
text
});
text.setDisabled(this.disabled);
// This.restrictToPositiveIntegerInput(text);
});
}
}
export function validateFileChangesNotificationThreshold(
fileChangesNotificationThreshold: string
): boolean {
if (
!Number.isInteger(Number(fileChangesNotificationThreshold)) ||
Number(fileChangesNotificationThreshold) < 1
) {
return false;
}
return true;
}

View file

@ -1,42 +1,13 @@
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS, MAX_SUPPORTED_INTERVAL } from 'settings/settings.ts';
import { SettingComponent } from 'settings/components/setting.ts';
export class FileExplorerStatsInterval extends GitChangelogSetting {
export class FileExplorerStatsInterval extends SettingComponent {
public display(): void {
this.createSetting()
.setName('Interval for file explorer stats (minutes)')
.addText((text) => {
text.setDisabled(this.disabled).onChange((value) => {
const newSettings = this.plugin.settingsClone;
newSettings.fileExplorerInterval = validateFileExplorerStatsInterval(
value
)
? value
: DEFAULT_SETTINGS.fileExplorerInterval;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
});
this.settingTab.bind(text, 'fileExplorerInterval');
// This.restrictToPositiveIntegerInput(text, 5);
this.setNonDefaultValue({
settingsProperty: 'fileExplorerInterval',
text
});
text.setDisabled(this.disabled);
});
}
}
export function validateFileExplorerStatsInterval(
fileExplorerStatsInterval: string
): boolean {
if (
!Number.isInteger(Number(fileExplorerStatsInterval)) ||
Number(fileExplorerStatsInterval) < 1 ||
Number(fileExplorerStatsInterval) > MAX_SUPPORTED_INTERVAL
) {
return false;
}
return true;
}

View file

@ -6,10 +6,10 @@ import {
MAX_TESTED_GIT_PLUGIN_VERSION,
MIN_COMPATIBLE_GIT_PLUGIN_VERSION
} from 'constants.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { SettingComponent } from 'settings/components/setting.ts';
import { GitPluginState } from 'types.ts';
export class GitPluginWarning extends GitChangelogSetting {
export class GitPluginWarning extends SettingComponent {
public display(): void {
let desc: DocumentFragment | string;
let setting: Setting;

View file

@ -1,28 +1,16 @@
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { SettingComponent } from 'settings/components/setting.ts';
export class IgnoreBlankLinesToggle extends GitChangelogSetting {
export class IgnoreBlankLinesToggle extends SettingComponent {
public display(): void {
this.createSetting()
.setName(
createFragment((fragment) => {
fragment.appendText(`Ignore blank lines`);
fragment
.createEl('span', { cls: 'nav-file-tag git-changelog-new' })
.setText('NEW');
fragment.appendText(`Ignore changes whose lines are all blank`);
})
)
.setDesc('Ignore the additions and removals of completely empty lines.')
.addToggle((toggle) =>
toggle
.setValue(
this.plugin.settings.changelogGenerationSettings.ignoreBlankLines
)
.onChange((value) => {
const newSettings = this.plugin.settingsClone;
newSettings.changelogGenerationSettings.ignoreBlankLines = value;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
})
);
.setDesc(
"Doesn't show a file as changed if the only changes are blank lines."
)
.addToggle((toggle) => this.settingTab.bind(toggle, 'ignoreBlankLines'));
}
}

View file

@ -0,0 +1,26 @@
import { EXCLUDE_FILES_AND_FOLDERS } from 'constants.ts';
import { appendCodeBlock } from 'obsidian-dev-utils/HTMLElement';
import { SettingComponent } from 'settings/components/setting.ts';
export class IncludeItemsToggle extends SettingComponent {
public display(): void {
this.createSetting()
.setName(
createFragment((fragment) => {
fragment.appendText(`Include items instead`);
})
)
.setDesc(
createFragment((fragment) => {
fragment.appendText('Include the items listed in ');
appendCodeBlock(fragment, EXCLUDE_FILES_AND_FOLDERS);
fragment.appendText(
` instead of excluding them, and exclude everything else.`
);
})
)
.addToggle((toggle) =>
this.settingTab.bind(toggle, 'convertToIncludeList')
);
}
}

View file

@ -1,7 +1,7 @@
import { FEEDBACK_URL } from 'constants.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { SettingComponent } from 'settings/components/setting.ts';
export class MiscellaneousButtons extends GitChangelogSetting {
export class MiscellaneousButtons extends SettingComponent {
public display(): void {
const bugReportDiv = this.createSetting();
bugReportDiv.addButton((button) => {

View file

@ -1,10 +1,7 @@
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { SettingComponent } from 'settings/components/setting.ts';
// https://github.com/git/git/blob/58b5801aa94ad5031978f8e42c1be1230b3d352f/diff.c#L58 - 1000 default
export class RenameDetectionFileLimit extends GitChangelogSetting {
export class RenameDetectionFileLimit extends SettingComponent {
public display(): void {
this.createSetting()
@ -20,42 +17,8 @@ export class RenameDetectionFileLimit extends GitChangelogSetting {
);
})
)
.addText((text) => {
text.inputEl.pattern = '[0-9]*';
text.inputEl.maxLength = 20;
text.inputEl.inputMode = 'numeric';
text
.setPlaceholder(
DEFAULT_SETTINGS.changelogGenerationSettings.renameLimit
)
.onChange((value) => {
const newSettings = this.plugin.settingsClone;
newSettings.changelogGenerationSettings.renameLimit = String(value);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
});
// This.restrictToPositiveIntegerInput(text);
this.setNonDefaultValue({
diffSettingsProperty: 'renameLimit',
settingsProperty: 'changelogGenerationSettings',
text
});
.addNumber((text) => {
this.settingTab.bind(text, 'renameLimit');
});
}
}
export function getRenameLimit(
changelogGenerationSettings: ChangelogGenerationSettings
): number {
if (!validateRenameLimit(changelogGenerationSettings.renameLimit)) {
return Number(DEFAULT_SETTINGS.changelogGenerationSettings.renameLimit);
}
return Number(changelogGenerationSettings.renameLimit);
}
export function validateRenameLimit(renameLimit: string): boolean {
return Number(renameLimit) >= 0 && Number.isInteger(renameLimit);
}

View file

@ -1,16 +1,12 @@
import type { SliderComponent } from 'obsidian';
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
import {
MAX_RENAME_DETECTION_STRICTNESS,
MIN_RENAME_DETECTION_STRICTNESS
} from 'constants.ts';
import { ResetButton } from 'settings/components/resetButton.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { SettingComponent } from 'settings/components/setting.ts';
const MIN_RENAME_DETECTION_STRICTNESS = 1;
const MAX_RENAME_DETECTION_STRICTNESS = 100;
export class RenameDetectionStrictnessSlider extends GitChangelogSetting {
export class RenameDetectionStrictnessSlider extends SettingComponent {
public display(): void {
let slider: SliderComponent;
const setting = this.createSetting()
.setName('File move/rename detection strictness')
.setDesc(
@ -26,50 +22,28 @@ export class RenameDetectionStrictnessSlider extends GitChangelogSetting {
);
new ResetButton(setting.controlEl).onClick(() => {
slider.setValue(
DEFAULT_SETTINGS.changelogGenerationSettings.renameDetectionStrictness
const defaultValue =
this.plugin.settingsManager.defaultSettings.renameDetectionStrictness;
// It saves to file, which we don't want to wait for
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.settingsManager.setProperty(
'renameDetectionStrictness',
defaultValue
);
this.refreshDisplayWithDelay(0);
});
setting.addSlider((percent) => {
slider = percent;
this.settingTab.bind(percent, 'renameDetectionStrictness');
percent
.setValue(
getRenameDetectionStrictness(
this.plugin.settings.changelogGenerationSettings
)
)
.setLimits(
MIN_RENAME_DETECTION_STRICTNESS,
MAX_RENAME_DETECTION_STRICTNESS,
1
)
.onChange((value) => {
const newSettings = this.plugin.settingsClone;
newSettings.changelogGenerationSettings.renameDetectionStrictness =
value;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
})
.setDynamicTooltip();
});
}
}
export function getRenameDetectionStrictness(
changelogGenerationSettings: ChangelogGenerationSettings
): number {
if (
!Number.isInteger(changelogGenerationSettings.renameDetectionStrictness) ||
changelogGenerationSettings.renameDetectionStrictness <
MIN_RENAME_DETECTION_STRICTNESS ||
changelogGenerationSettings.renameDetectionStrictness >
MAX_RENAME_DETECTION_STRICTNESS
) {
return DEFAULT_SETTINGS.changelogGenerationSettings
.renameDetectionStrictness;
}
return changelogGenerationSettings.renameDetectionStrictness;
}

View file

@ -0,0 +1,139 @@
import type GitChangelogPlugin from 'main.ts';
import { COMPARE_TO_CHECKPOINT_VIEW_CONFIG } from 'constants.ts';
import { Notice } from 'obsidian';
import { invokeAsyncSafely } from 'obsidian-dev-utils/Async';
import { SettingComponent } from 'settings/components/setting.ts';
import { removeCompareVersionsView } from 'utils.ts';
export class ReviewChangesReminderInterval extends SettingComponent {
public display(): void {
this.createSetting()
.setName(
createFragment((fragment) => {
fragment.appendText('Review changes reminder interval');
fragment
.createEl('span', {
cls: 'nav-file-tag git-changelog-new'
})
.setText('NEW');
})
)
.setDesc(
createFragment((fragment) => {
fragment.appendText(
'How often to remind you to review changes made inside the vault (minutes).'
);
fragment.createEl('br');
fragment.appendText('Set 0 to disable reminders.');
})
)
.addNumber((text) => {
this.settingTab.bind(text, 'reviewChangesReminderInterval');
});
}
}
/**
* Dismisses the checkpoint reminder notification if present.
*/
export async function dismissCheckpointReminder(
plugin: GitChangelogPlugin,
hide: boolean
): Promise<void> {
if (plugin.checkpointReminderNotice) {
if (hide) {
plugin.checkpointReminderNotice.hide();
}
plugin.checkpointReminderNotice = undefined;
}
await resetCheckpointReminderCounter(plugin);
}
/**
* Resets the activeMinutesPassedSinceLastCheckpoint counter in settings.
*/
export async function resetCheckpointReminderCounter(
plugin: GitChangelogPlugin
): Promise<void> {
await plugin.settingsManager.editAndSave((settings) => {
settings.activeMinutesPassedSinceLastCheckpoint = 0;
});
}
/**
* Handles the minute interval for checkpoint reminders.
*/
export async function handleReviewChangesReminderInterval(
plugin: GitChangelogPlugin
): Promise<void> {
const { reviewChangesReminderInterval } = plugin.settings;
if (!reviewChangesReminderInterval || reviewChangesReminderInterval <= 0) {
await dismissCheckpointReminder(plugin, true);
return;
}
// Don't show if already open
if (plugin.checkpointReminderNotice) return;
// Increment counter in settings
await plugin.settingsManager.editAndSave((settings) => {
settings.activeMinutesPassedSinceLastCheckpoint =
(settings.activeMinutesPassedSinceLastCheckpoint || 0) + 1;
});
if (
plugin.settings.activeMinutesPassedSinceLastCheckpoint >=
reviewChangesReminderInterval
) {
showCheckpointReminder(plugin);
}
}
/**
* Shows the checkpoint reminder notification if not already shown.
*/
export function showCheckpointReminder(plugin: GitChangelogPlugin): void {
if (plugin.checkpointReminderNotice) return;
const frag = createFragment((element) => {
element.createEl('span', {
text: `Git changelog:\nIt's time to review the changes made to your vault. 🧐`
});
element.createEl('br');
const openButton = element.createEl('button', {
text: 'Review'
});
openButton.style.marginTop = '8px';
openButton.classList.add('mod-cta');
openButton.addEventListener('click', () => {
invokeAsyncSafely(() => openCompareToCheckpointView(plugin, false));
});
const dismissButton = element.createEl('button', {
text: 'Remind me later'
});
dismissButton.style.marginLeft = '8px';
dismissButton.addEventListener('click', () => {
invokeAsyncSafely(() => dismissCheckpointReminder(plugin, false));
});
});
plugin.checkpointReminderNotice = new Notice(frag, 0);
}
export async function openCompareToCheckpointView(
plugin: GitChangelogPlugin,
hideCheckpointReminder = true
): Promise<void> {
// First close any existing COMPARE_REPO_STATES_VIEW views
removeCompareVersionsView(plugin);
await plugin.app.workspace.ensureSideLeaf(
COMPARE_TO_CHECKPOINT_VIEW_CONFIG.type,
'left',
{ reveal: true }
);
invokeAsyncSafely(() =>
dismissCheckpointReminder(plugin, hideCheckpointReminder)
);
}

View file

@ -1,60 +1,16 @@
import type { GitChangelogPluginSettings } from 'settings/settings.ts';
import type { ReadonlyDeep } from 'type-fest';
import { SettingComponent } from 'settings/components/setting.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS, MAX_SUPPORTED_INTERVAL } from 'settings/settings.ts';
export class StatusBarInterval extends GitChangelogSetting {
export class StatusBarInterval extends SettingComponent {
public display(): void {
this.createSetting()
.setName('Interval for status bar stats (minutes)')
.setDesc(
'Works by comparing the live file version against the first commit before the interval.'
)
.addText((text) => {
text.inputEl.pattern = '[1-9][0-9]*';
text.inputEl.maxLength = MAX_SUPPORTED_INTERVAL.toString().length;
text.inputEl.inputMode = 'numeric';
text
.setDisabled(this.disabled)
.setPlaceholder(DEFAULT_SETTINGS.statusBarInterval)
.onChange((value) => {
const newSettings = this.plugin.settingsClone;
newSettings.statusBarInterval = validateStatusBarInterval(
String(value)
)
? String(value)
: DEFAULT_SETTINGS.statusBarInterval;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
});
.addNumber((text) => {
this.settingTab.bind(text, 'statusBarInterval');
this.setNonDefaultValue({
settingsProperty: 'statusBarInterval',
text
});
text.setDisabled(this.disabled);
});
}
}
export function getStatusBarInterval(
settings: ReadonlyDeep<GitChangelogPluginSettings>
): number {
if (!validateStatusBarInterval(settings.statusBarInterval)) {
return Number(DEFAULT_SETTINGS.statusBarInterval);
}
return Number(settings.statusBarInterval);
}
export function validateStatusBarInterval(
statusBarAlternateInterval: string
): boolean {
if (
!Number.isInteger(Number(statusBarAlternateInterval)) ||
Number(statusBarAlternateInterval) < 1 ||
Number(statusBarAlternateInterval) > MAX_SUPPORTED_INTERVAL
) {
return false;
}
return true;
}

View file

@ -1,27 +1,15 @@
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { SettingComponent } from 'settings/components/setting.ts';
export class StatusBarStatsToggle extends GitChangelogSetting {
export class StatusBarStatsToggle extends SettingComponent {
public display(): void {
this.createSetting()
.setName('Active note live status bar stats')
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.statusBarStats)
.onChange((value) => {
.addToggle((toggle) => {
this.settingTab.bind(toggle, 'showStatusBarStats', {
onChanged: () => {
this.refreshDisplayWithDelay();
const newSettings = this.plugin.settingsClone;
newSettings.statusBarStats = value;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
if (value) {
this.plugin.initStatusBar();
} else {
this.plugin.statusBarStats?.destroy?.();
this.plugin.statusBarStats = undefined;
}
})
);
}
});
});
}
}

View file

@ -1,57 +1,32 @@
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { SettingComponent } from 'settings/components/setting.ts';
import { WhitespaceIgnoreMode } from 'types.ts';
export class WhitespaceIgnoreModeOptions extends GitChangelogSetting {
export class WhitespaceIgnoreModeOptions extends SettingComponent {
public display(): void {
this.createSetting()
.setName(
createFragment((fragment) => {
fragment.appendText(`Whitespace changes detection`);
fragment
.createEl('span', { cls: 'nav-file-tag git-changelog-new' })
.setText('NEW');
})
)
.addDropdown((dropdown) => {
const options = {
[WhitespaceIgnoreMode.None]: 'Track all whitespace changes',
[WhitespaceIgnoreMode.SpaceAtEol]:
'Ignore whitespace changes at end of line',
[WhitespaceIgnoreMode.SpaceChange]:
'Ignore changes to pre-existing whitespace',
[WhitespaceIgnoreMode.AllSpace]: 'Ignore all whitespace changes'
} as const;
dropdown.addOptions(options);
dropdown.setValue(
getWhitespaceIgnoreMode(
this.plugin.settings.changelogGenerationSettings
)
.addTypedDropdown((dropdown) => {
dropdown.addOption(
WhitespaceIgnoreMode.None,
'Track all whitespace changes'
);
dropdown.onChange((value: WhitespaceIgnoreMode) => {
const newSettings = this.plugin.settingsClone;
newSettings.changelogGenerationSettings.whitespaceIgnoreMode = value;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
});
dropdown.addOption(
WhitespaceIgnoreMode.SpaceAtEol,
'Ignore whitespace changes at end of line'
);
dropdown.addOption(
WhitespaceIgnoreMode.SpaceChange,
'Ignore changes to pre-existing whitespace'
);
dropdown.addOption(
WhitespaceIgnoreMode.AllSpace,
'Ignore all whitespace changes per line'
);
this.settingTab.bind(dropdown, 'whitespaceIgnoreMode');
});
}
}
export function getWhitespaceIgnoreMode(
changelogGenerationSettings: ChangelogGenerationSettings
): WhitespaceIgnoreMode {
if (
!Object.values(WhitespaceIgnoreMode).includes(
changelogGenerationSettings.whitespaceIgnoreMode
)
) {
return DEFAULT_SETTINGS.changelogGenerationSettings.whitespaceIgnoreMode;
}
return changelogGenerationSettings.whitespaceIgnoreMode;
}

View file

@ -1,12 +1,12 @@
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { SettingComponent } from 'settings/components/setting.ts';
export class WhitespaceSettingsHeading extends GitChangelogSetting {
export class WhitespaceSettingsHeading extends SettingComponent {
public display(): void {
this.createSetting()
.setHeading()
.setName('Whitespace settings')
.setDesc(
`Note that adjusting these settings will make the generated stats to slightly differ from the diff view, because unlike the diff algorithm, these settings can't be applied globally.`
`Note that adjusting these settings will make the generated stats slightly differ from the diff view, because unlike the diff algorithm, these settings can't be applied globally.`
);
}
}

View file

@ -1,32 +0,0 @@
import type GitChangelogPlugin from 'main.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { ChangelogInterval } from 'types.ts';
// Redundant currently
export function getChangelogIntervalFromSettings(
plugin: GitChangelogPlugin,
fileOrVault: 'file' | 'vault'
): ChangelogInterval {
const interval =
fileOrVault === 'file'
? plugin.settings.fileChangelogInterval
: plugin.settings.vaultChangelogGenerationSettings.interval;
if (!validateChangelogInterval(interval)) {
return fileOrVault === 'file'
? DEFAULT_SETTINGS.fileChangelogInterval
: DEFAULT_SETTINGS.vaultChangelogGenerationSettings.interval;
}
return interval;
}
export function validateChangelogInterval(
changelogInterval: ChangelogInterval
): boolean {
if (Object.values(ChangelogInterval).includes(changelogInterval)) {
return true;
}
return false;
}

View file

@ -1,4 +1,5 @@
import type { GitChangelogPluginSettings } from 'settings/settings.ts';
import type { GitChangelogPluginTypes } from 'constants.ts';
import type { ExtractPluginSettingsWrapper } from 'obsidian-dev-utils/obsidian/Plugin/PluginTypesBase';
import type { TaskManager } from 'TaskManager.svelte.ts';
import type { ReadonlyDeep } from 'type-fest';
@ -6,8 +7,6 @@ import { findFirstFileCommitBefore } from 'core/findFirstFileCommitBefore.ts';
import { runCheckIgnore } from 'core/gitOperations/runCheckIgnore.ts';
import { runWorkingDirFileDiff } from 'core/gitOperations/runWorkingDirFileDiff.ts';
import { MarkdownView } from 'obsidian';
import { getMeasurementUnit } from 'settings/ui/ChangelogMeasurementUnit.ts';
import { getStatusBarInterval } from 'settings/ui/StatusBarInterval.ts';
import { AbortError, DiffMeasurementUnit } from 'types.ts';
import { getGitRelativeFilePath } from 'Views/helper.ts';
@ -68,11 +67,16 @@ export class StatusBarStats {
}
public static generationSettingsChanged(
oldSettings: ReadonlyDeep<GitChangelogPluginSettings>,
newSettings: GitChangelogPluginSettings
oldSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>,
newSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>
): boolean {
return (
getStatusBarInterval(oldSettings) !== getStatusBarInterval(newSettings)
oldSettings.safeSettings.statusBarInterval !==
newSettings.safeSettings.statusBarInterval
);
}
@ -90,7 +94,7 @@ export class StatusBarStats {
if (abortSignal.aborted) {
throw new AbortError();
}
if (this.plugin.settings.statusBarStats) {
if (this.plugin.settings.showStatusBarStats) {
const result = await this.calculateStatsForActiveFile(
this.plugin.app.workspace.getActiveViewOfType(MarkdownView),
abortSignal
@ -133,11 +137,15 @@ export class StatusBarStats {
let additions = 0;
let deletions = 0;
const git = await this.plugin.getGit();
const oldCommit = await findFirstFileCommitBefore({
abortSignal,
filePath: activeGitFile,
minutes: getStatusBarInterval(this.plugin.settings),
plugin: this.plugin
minutes: this.plugin.settings.statusBarInterval,
timeZone: await this.plugin.getEmptyTreeHash(),
git,
renameDetectionStrictness: this.plugin.settings.renameDetectionStrictness
});
if (oldCommit && oldCommit.fileDeleted !== true) {
@ -145,7 +153,10 @@ export class StatusBarStats {
abortSignal,
oldCommit,
activeGitFile,
plugin: this.plugin
git,
diffAlgorithm: this.plugin.settings.diffAlgorithm,
whitespaceIgnoreMode: this.plugin.settings.whitespaceIgnoreMode,
ignoreBlankLines: this.plugin.settings.ignoreBlankLines
});
if (baseStats) {
additions = baseStats.additions;
@ -160,15 +171,13 @@ export class StatusBarStats {
const fileIsGitIgnored = await runCheckIgnore({
abortSignal,
activeGitFile,
plugin: this.plugin
git
});
if (fileIsGitIgnored) {
return 'In .gitignore';
}
const measurementUnit = getMeasurementUnit(
this.plugin.settings.changelogGenerationSettings
);
const measurementUnit = this.plugin.settings.diffMeasurementUnit;
if (measurementUnit === DiffMeasurementUnit.Lines) {
additions = activeFileView.editor.lineCount();

View file

@ -17,6 +17,28 @@
border-bottom: 1px solid var(--text-warning);
}
.git-changelog-top-margin {
margin-top: var(--size-4-1);
}
.git-changelog-on-checkpoint-commit-icon {
vertical-align: middle;
}
.git-changelog-compared-versions-container {
display: flex;
flex-direction: column;
gap: var(--size-4-1);
margin-bottom: var(--size-4-1);
justify-content: center;
align-items: center;
margin-top: var(--size-2-1);
}
.git-changelog-force-center {
align-self: center !important;
}
.git-changelog-align-file {
align-items: center;
width: 100%;
@ -105,7 +127,6 @@
.git-changelog-view {
--git-changelog-opacity: 0.84;
display: flex;
flex-direction: column;
position: relative;
@ -113,6 +134,18 @@
padding-bottom: calc(2 * var(--size-4-1));
}
.git-changelog-checkpoint-modal {
align-items: center;
flex-direction: column;
justify-content: center;
align-content: center;
display: flex;
}
.git-changelog-approve-button {
align-self: center;
}
.git-changelog-entry-title {
@extend .git-changelog-one-line;
color: var(--text-accent);
@ -121,6 +154,16 @@
margin-bottom: var(--size-4-1);
}
.git-changelog-compared-version-title {
@extend .git-changelog-one-line;
color: var(--text-muted);
font-size: var(--font-smaller);
}
.git-changelog-compared-version-title-arrow {
color: var(--text-faint);
}
.git-changelog-initial-version-tag {
@extend .git-changelog-one-line;
font-size: 0.75em;
@ -195,6 +238,8 @@
/* Sticky view header and padding fixes */
.workspace-leaf-content {
&[data-type='vault-changelog-view'] .view-content,
&[data-type='vault-git-history-comparison-view'] .view-content,
&[data-type='compare-to-checkpoint-view'] .view-content,
&[data-type='file-changelog-view'] .view-content {
padding: 0;
}

View file

@ -3,32 +3,35 @@ import type { Spacetime } from 'spacetime';
import type { LogEntry } from 'types.ts';
/**
* This function produces "fullyAdjusted" dates, which are dates that have the "day start time" setting applied to a "timeAdjustedDate". timezoneAdjustedDate is a date adjusted with the timezone setting specified in the settings tab.
* This function produces "fullyAdjusted" dates, which are dates that have the "day start time" setting applied to a "timeAdjustedDate". timeZoneAdjustedDate is a date adjusted with the timeZone setting specified in the settings tab.
*/
export function applyDayStartTimeSetting({
dayStartTime,
timezoneAdjustedDate
export function applyDayStartHourSetting({
dayStartHour,
timeZoneAdjustedDate
}: {
dayStartTime: number;
timezoneAdjustedDate: Spacetime;
dayStartHour: number;
timeZoneAdjustedDate: Spacetime;
}): Spacetime {
return timezoneAdjustedDate.subtract(dayStartTime, 'hours');
return timeZoneAdjustedDate.subtract(dayStartHour, 'hours');
}
export function getDayStartTimeAdjustedLogs(
export function getDayStartHourAdjustedLogs(
logEntries: LogEntry[],
dayStartTime: number
dayStartHour: number
): LogEntry[] {
if (dayStartTime === 0) {
if (dayStartHour === 0) {
return logEntries;
}
return logEntries.map((entry) => {
return {
...entry,
fullyAdjustedDate: applyDayStartTimeSetting({
dayStartTime,
timezoneAdjustedDate: entry.timezoneAdjustedDate
fullyAdjustedDate: applyDayStartHourSetting({
dayStartHour,
timeZoneAdjustedDate: entry.timeZoneAdjustedDate
})
};
});
}
export function formatDateHour(date: Spacetime): string {
return date.startOf('hour').format('iso-utc');
}

View file

@ -135,7 +135,7 @@ export enum FileExplorerStats {
FoldersAndNotes = 'FoldersAndNotes'
}
export enum FilesSummariesDisplayMode {
export enum FileSummariesDisplayMode {
TextAndBinary = 'Text and binary',
Total = 'Total'
// Binary = "Binary",
@ -171,10 +171,15 @@ export interface FilesSummary {
renamedAndMovedFiles: number;
}
export interface CompareRepoCommitsViewState {
utcOlderDate: string;
utcNewerDate: string;
}
export interface LogEntry {
// Can be null for file logs, if the file was deleted in some commit
hash: string;
timezoneAdjustedDate: Spacetime;
timeZoneAdjustedDate: Spacetime;
// For file git logs only:
// To track file renames through history

View file

@ -1,10 +1,15 @@
/* eslint-disable unicorn/prevent-abbreviations */
import type { GitChangelogPlugin } from 'GitChangelogPlugin.svelte.ts';
import type { App, WorkspaceLeaf } from 'obsidian';
import type { DiffFile, TextDiffStats } from 'types.ts';
import { FEEDBACK_URL } from 'constants.ts';
import {
COMPARE_REPO_COMMITS_VIEW_CONFIG,
COMPARE_TO_CHECKPOINT_VIEW_CONFIG,
FEEDBACK_URL
} from 'constants.ts';
// Import * as cssColorConverter from "css-color-converter";
import { Keymap } from 'obsidian';
import { Keymap, Notice } from 'obsidian';
import { DiffFileStatus, NullValueError } from 'types.ts';
export function getFileNameFromPath({
@ -96,7 +101,7 @@ export function assertNotNull<T>(value: null | T | undefined): T {
const error = new NullValueError();
const stack = error.stack ?? '';
const message = `Git changelog:\nNon-nullable value is null or undefined`;
console.error(message);
console.error(`${message}\n${stack}`);
const fragment = createFragment((el) => {
el.createEl('p', {
text: 'Git changelog:\nHey, some null error happened that shouldn`t have.\nCan you please copy the error info and report it to the Github issues page so that it can get fixed.\nJust paste the copied info, nothing more'
@ -120,3 +125,14 @@ export function assertNotNull<T>(value: null | T | undefined): T {
}
return value;
}
export function removeCompareVersionsView(plugin: GitChangelogPlugin): void {
// Close any existing temporary views
plugin.app.workspace.detachLeavesOfType(
COMPARE_TO_CHECKPOINT_VIEW_CONFIG.type
);
plugin.app.workspace.detachLeavesOfType(
COMPARE_REPO_COMMITS_VIEW_CONFIG.type
);
}

View file

@ -1,7 +1,10 @@
{
"0.1.0": "1.7.2",
"0.2.0": "1.7.2",
"0.2.1": "1.7.2",
"0.3.0": "1.7.2",
"0.4.0": "1.7.2"
"0.1.0": "1.8.9",
"0.2.0": "1.8.9",
"0.2.1": "1.8.9",
"0.3.0": "1.8.9",
"0.4.0": "1.8.9",
"0.5.0": "1.8.9",
"0.5.1": "1.8.10",
"0.6.0": "1.8.10"
}