Compare commits

..

No commits in common. "main" and "0.4.0" have entirely different histories.
main ... 0.4.0

85 changed files with 2624 additions and 5930 deletions

View file

@ -1 +0,0 @@
OBSIDIAN_CONFIG_FOLDER=

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

View file

@ -1,46 +1,5 @@
# 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

216
README.md
View file

@ -1,104 +1,66 @@
# Git Changelog
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.
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.
![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
[Download](https://obsidian.md/plugins?id=git-changelog) the plugin from the official Community Plugins repository.
Install the plugin from [the official Community Plugins repository](https://obsidian.md/plugins?id=git-changelog).
> [!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. If some saved settings were broken, they will be mentioned in the changelog.
> This plugin is currently in beta and still under development, so your existing settings may break after each update.
## 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
![Vault Changelog View](.github/vault-changelog-view.webp)
- 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.
- 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).
- The files are sorted from most number of lines changed to least.
- **Exclude Files and Folders:**
- Usually you specify files and folders you want to exclude from your Git repository in the `.gitignore` file.
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).
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.
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.
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.
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.
**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.
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.
![Vault Changelog View](.github/vault-changelog-view.webp)
### 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.
![File Changelog View](.github/file-changelog-view.webp)
> [!WARNING]
> Showing a lot of versions and files will reduce view performance. This will be fixed soon.
> Using the "Expand all" toggle 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.
- Easily switch between hourly, daily, weekly, and monthly intervals.
- Choose from 5 options to ignore whitespace changes with varying intensity.
- Choose to view hourly, daily, weekly, or monthly intervals.
- **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
@ -109,35 +71,7 @@ To easily see the what's new in future updates, it's recommended to use the [Plu
- 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.
### 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.
> Currently only the "Split" diff view works. The "Unified" view shows inaccurate changes.
## Data Loss Monitoring
@ -149,63 +83,43 @@ 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.
The result of all of this can be you asking yourself:
### How to Use
> Wait, didnt this note have more lines yesterday? 🤔
This plugin was not designed to accumulate all changes made inside an interval.
This plugin tries it's best to help you answer that question. 😎
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.
- 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.
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.
### How it works
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.
- This plugin was not designed to accumulate all changes made inside an interval.
A "Copy commit hash" context menu option is provided so that you can further investigate the commit tied to some suspicious version.
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.
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).
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.
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.
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.
Use the [Version History Diff](https://github.com/kometenstaub/obsidian-version-history-diff) plugin for easier navigation through those versions.
- A "Copy commit hash" context menu option is provided so that you can further investigate the commit tied to some suspicious version.
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:
- 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
```
```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
@ -221,79 +135,47 @@ This plugin tries it's best to help you answer that question. 😎
- [ ] Code cleanup and refactoring.
- [ ] Improve README.
- [ ] Folder stats in the Vault changelog view.
- [x] Command to compare any two points in the vault (repo) history.
- [ ] Command to compare the current state of the vault (repo) to any point in 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 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.
If you don't want to depend on Git, check out the [Vault Changelog](https://github.com/philoserf/obsidian-vault-changelog) plugin.
## FAQ
- Why is the File changelog view showing inaccurate history for some files?
### Will this plugin alter my Git repository/config?
- Most common cases for this are: **The file had its file path changed (renamed/moved or one of its parent folders was renamed/moved)**...
- 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.
1. and the change isn't committed yet.
### 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?
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.
- No. 😔
## 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/obsidian-dev-utils?tab=readme-ov-file#build-development-version) a `OBSIDIAN_CONFIG_FOLDER` variable and run `npm run dev`.
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`.
## Credits

View file

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

View file

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

View file

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

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.6.0",
"version": "0.4.0",
"description": "Uses Git to display dynamic vault and file changelogs in the sidebar, useful for spotting data loss.",
"keywords": [],
"license": "MIT",
@ -37,21 +37,20 @@
"eslint-plugin-svelte": "^3.2.2",
"eslint-plugin-unicorn": "^57.0.0",
"globals": "^16.0.0",
"obsidian": "latest",
"obsidian-dev-utils": "26.4.0",
"obsidian-typings": "latest",
"obsidian": "^1.8.7",
"obsidian-dev-utils": "^21.0.0",
"obsidian-typings": "^2.35.0",
"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"
"typescript-eslint": "^8.25.0",
"simple-git": "^3.27.0"
},
"overrides": {
"boolean": "npm:dry-uninstall"

View file

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

View file

@ -1,8 +1,8 @@
import { getFolderName } from 'obsidian-dev-utils/Path';
import { getDirname } from 'obsidian-dev-utils/Path';
import { existsSync } from 'obsidian-dev-utils/ScriptUtils/NodeModules';
import {
execFromRoot,
getRootFolder,
getRootDir,
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 = getRootFolder(getFolderName(import.meta.url));
const packageDirectory = getRootDir(getDirname(import.meta.url));
if (!packageDirectory) {
throw new Error('Could not find package directory.');
}

View file

@ -1,41 +1,28 @@
import type { GitChangelogPluginTypes } from 'constants.ts';
import type { ObsidianGitPlugin } from 'gitPluginTypes.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 { Debouncer, PluginSettingTab } from 'obsidian';
import type { ChangelogGenerationSettings } 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, Notice } from 'obsidian';
import { invokeAsyncSafely } from 'obsidian-dev-utils/Async';
import { debounce, ItemView, Notice } from 'obsidian';
import { PluginBase } from 'obsidian-dev-utils/obsidian/Plugin/PluginBase';
import { GitChangelogSettingsManager } from 'settings/settingsManager.ts';
import { getLocaleToAssign } from 'settings/ui/CustomLocale.ts';
import { changelogGenerationSettingsChanged } from 'settings/helper.ts';
import { GitChangelogPluginSettings } from 'settings/settings.ts';
import { getTimeZone } from 'settings/ui/CustomTimeZone.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, isDiffViewVisible } from 'Views/helper.ts';
import { getActiveGitRelativeFile, isDiffView } from 'Views/helper.ts';
import {
VAULT_CHANGELOG_VIEW_CONFIG,
VaultChangelogView
@ -51,26 +38,26 @@ import {
GitRepoMissingError
} from './types.ts';
export class GitChangelogPlugin extends PluginBase<GitChangelogPluginTypes> {
export class GitChangelogPlugin extends PluginBase<GitChangelogPluginSettings> {
public debouncedChangelogSettingsChangedCheck:
| Debouncer<
[
oldSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>,
newSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>
oldSettings: ReadonlyDeep<GitChangelogPluginSettings>,
newSettings: ReadonlyDeep<GitChangelogPluginSettings>
],
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 dependenciesReady = $derived(
(this.gitPluginState === GitPluginState.Enabled ||
this.gitPluginState === GitPluginState.UntestedVersion) &&
@ -78,31 +65,14 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginTypes> {
);
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,
@ -136,16 +106,8 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginTypes> {
this.consoleDebug(`Error:`, error.stack);
}
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;
}
// eslint-disable-next-line no-magic-numbers
public displayNotice(message: string, timeout: number = 3 * 1000): void {
new Notice(`${this.manifest.name}:\n${message}`, timeout);
}
@ -180,60 +142,40 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginTypes> {
}
}
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;
}
// 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
public override async saveSettings(
newSettings: GitChangelogPluginSettings,
debounceOnSettingsSave = true
): Promise<void> {
// If the local setting was modified externally, we need to update the localeSafe property.
this.localeSafe = getLocaleToAssign(this);
if (skipCheck === true) {
return;
const oldSettings = this.settings;
await super.saveSettings(newSettings);
if (debounceOnSettingsSave) {
this.debouncedChangelogSettingsChangedCheck?.(oldSettings, newSettings);
} else {
this.onSettingsSave(oldSettings, newSettings);
}
this.debouncedChangelogSettingsChangedCheck?.(_oldSettings, _newSettings);
}
protected override createSettingsTab(): GitChangelogSettingsTab {
protected override createPluginSettings(
data: unknown
): GitChangelogPluginSettings {
return new GitChangelogPluginSettings(data);
}
protected override createPluginSettingsTab(): null | PluginSettingTab {
return new GitChangelogSettingsTab(this);
}
protected override createSettingsManager(): GitChangelogSettingsManager {
return new GitChangelogSettingsManager(this);
}
// Functions below are from obsidian-dev-utils (https://github.com/mnaoumov/obsidian-dev-utils/blob/main/src/obsidian/Plugin/PluginBase.ts)
// 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();
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();
});
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);
});
@ -242,33 +184,16 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginTypes> {
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: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>,
newSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>
oldSettings: GitChangelogPluginSettings,
newSettings: GitChangelogPluginSettings
) => {
this.onSaveSettingsCheck(oldSettings, newSettings);
this.onSettingsSave(oldSettings, newSettings);
},
// eslint-disable-next-line no-magic-numbers
700,
@ -277,11 +202,6 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginTypes> {
}
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,
@ -292,12 +212,12 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginTypes> {
taskManager: new TaskManager(this)
});
if (this.settings.showStatusBarStats) {
if (this.settings.statusBarStats) {
this.initStatusBar();
}
this.registerEvent(
this.app.workspace.on('active-leaf-change', () => {
this.app.workspace.on('file-open', () => {
this.updateActiveGitFile();
})
);
@ -309,19 +229,18 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginTypes> {
})
);
// Every 5 minutes it checks if it's a new day in order to update the potentially outdated interval labels.
this.registerInterval(
window.setInterval(
() => {
// 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));
const timezone = getTimeZone(
this.settings.changelogGenerationSettings,
this
);
this.currentDay = spacetime.now(timezone).format('day');
},
// eslint-disable-next-line no-magic-numbers
60 * 1000
5 * 60 * 1000
)
);
@ -335,17 +254,70 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginTypes> {
await this.addVaultChangelogView();
await this.addFileChangelogView();
await this.settingsManager.editAndSave(
(settings: GitChangelogSettings): void => {
settings.firstStartup = false;
}
);
const newSettings = this.settingsClone;
newSettings.firstStartup = false;
await this.saveSettings(newSettings, 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;
@ -364,83 +336,16 @@ export class GitChangelogPlugin extends PluginBase<GitChangelogPluginTypes> {
if (currentActiveGitFile) {
this.setNewActiveGitFile(currentActiveGitFile);
} 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 */
}
}
} else {
const currentActiveView =
this.app.workspace.getActiveViewOfType(ItemView);
/**
* 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;
// 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;
}
}
// 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'
);
this.setNewActiveGitFile(undefined);
}
} catch {
/* Empty */

View file

@ -1,154 +0,0 @@
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

@ -1,212 +0,0 @@
<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

@ -1,87 +0,0 @@
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

@ -1,276 +0,0 @@
<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

@ -1,70 +0,0 @@
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,9 +2,6 @@
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';
@ -34,14 +31,12 @@
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>();
let changelogState = $derived.by(() => {
const changelogState = $derived.by(() => {
if (!changelogManager) {
return FileChangelogState.Initializing;
}
@ -62,43 +57,10 @@
if (!plugin.cachedActiveGitFile) {
return FileChangelogState.NoMarkdownFileOpen;
}
//
untrack(() => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
checkFileInGitIgnore();
});
// Set a loading state while checkFileInGitIgnore is in progress
return FileChangelogState.Recomputing;
return FileChangelogState.EmptyHistory;
});
// 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(
@ -138,15 +100,6 @@
}
});
$effect(() => {
if (infoTooltipIcon) {
setIcon(
infoTooltipIcon,
assertNotNull(infoTooltipIcon.getAttr('data-icon'))
);
}
});
$effect.pre(() => {
setIntervalAdjective();
});
@ -209,25 +162,7 @@
{:else if changelogState === FileChangelogState.NoMarkdownFileOpen}
<div class="pane-empty">No file opened.</div>
{:else if changelogState === FileChangelogState.EmptyHistory}
<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>
<div class="pane-empty">File has no Git history.</div>
{/if}
<!-- if changelogState === FileChangelogState.Initializing, show nothing -->
</div>
@ -235,18 +170,4 @@
</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,7 +58,6 @@ 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,7 +5,6 @@
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';
@ -27,19 +26,6 @@
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();
@ -47,7 +33,8 @@
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 ?? plugin.emptyTreeHashUnsafe,
aReference:
previousEntry?.commitHash ?? assertNotNull(plugin.emptyTreeHash),
bReference: entry.commitHash,
event,
file: entry,
@ -86,6 +73,17 @@
})
);
}
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,13 +2,12 @@
// 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 { FileSummariesDisplayMode } from 'types.ts';
import { FilesSummariesDisplayMode } from 'types.ts';
import { assertNotNull } from 'utils.ts';
import { getIntervalAdjectiveString } from 'Views/formatters.ts';
@ -142,17 +141,16 @@
collapseButton = undefined;
});
async function toggleFilesSummaryOption(): Promise<void> {
function toggleFilesSummaryOption(): void {
showFilesCountSummariesMode =
showFilesCountSummariesMode === FileSummariesDisplayMode.Total
? FileSummariesDisplayMode.TextAndBinary
: FileSummariesDisplayMode.Total;
showFilesCountSummariesMode === FilesSummariesDisplayMode.Total
? FilesSummariesDisplayMode.TextAndBinary
: FilesSummariesDisplayMode.Total;
await plugin.settingsManager.editAndSave(
(settings: GitChangelogSettings): void => {
settings.fileSummariesDisplayMode = showFilesCountSummariesMode;
}
);
const newSettings = plugin.settingsClone;
newSettings.fileSummariesDisplayMode = showFilesCountSummariesMode;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
plugin.saveSettings(newSettings);
}
function toggleCollapsedState(): void {
@ -169,7 +167,7 @@
entry.isCollapsed = !everythingCollapsed;
} else {
plugin.displayNotice(
`Too many versions. Unable to expand them all because of the impact on performance.`,
`Too many entries. Can't expand all because of performance reasons.`,
// eslint-disable-next-line no-magic-numbers
1500
);
@ -208,7 +206,7 @@
data-icon={TOGGLE_FILES_SUMMARY_OPTION_ICON}
aria-disabled={changelogState !== VaultChangelogState.HasEntries}
aria-label={showFilesCountSummariesMode ===
FileSummariesDisplayMode.Total
FilesSummariesDisplayMode.Total
? 'Text/media summary stats'
: 'Total files summary stats'}
bind:this={filesSummaryDisplayModeButton}

View file

@ -57,7 +57,6 @@ 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,7 +54,8 @@
if (!isClickable) return;
changelogFileClick({
aReference: previousVersionCommitHash ?? plugin.emptyTreeHashUnsafe,
aReference:
previousVersionCommitHash ?? assertNotNull(plugin.emptyTreeHash),
bReference: currentVersionCommitHash,
event,
file,

View file

@ -3,9 +3,8 @@
import type GitChangelogPlugin from 'main.ts';
import { mayTriggerChangelogMenu } from 'menu.ts';
import { getTimeZone } from 'settings/ui/CustomTimeZone.ts';
import { slide } from 'svelte/transition';
import { FileSummariesDisplayMode } from 'types.ts';
import { FilesSummariesDisplayMode } from 'types.ts';
import { composeVersionTitle } from 'Views/formatters.ts';
import { VaultChangelogView } from 'Views/VaultChangelog/VaultChangelog.ts';
@ -15,29 +14,20 @@
interface Properties {
plugin: GitChangelogPlugin;
showFilesCountSummaries: FileSummariesDisplayMode;
showFilesCountSummaries: FilesSummariesDisplayMode;
version: VaultChangelogEntry;
hideTitleAndMakeUncollapsible?: boolean;
}
const {
plugin,
showFilesCountSummaries,
version,
hideTitleAndMakeUncollapsible: hideTitleAndCollapseIcon
}: Properties = $props();
const { plugin, showFilesCountSummaries, version }: Properties = $props();
const formattedVersionDateLabel = $derived.by(() => {
// Doing it this way to ensure they're properly reacted to if changed.
const currentDate = plugin.utcCurrentDateHour;
const locale = plugin.localeSafe;
// CurrentDay just used to trigger updates
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const currentDay = plugin.currentDay;
return composeVersionTitle({
interval: plugin.settings.vaultChangelogInterval,
dayStartHour: plugin.settings.dayStartHour,
locale,
timeZone: getTimeZone(plugin),
utcCurrentDateHour: currentDate,
timeZoneAdjustedEntryDate: version.timeZoneAdjustedDate
interval: plugin.settings.vaultChangelogGenerationSettings.interval,
plugin,
timezoneAdjustedEntryDate: version.timezoneAdjustedDate
});
});
</script>
@ -45,17 +35,15 @@
<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div
class:is-collapsed={hideTitleAndCollapseIcon ? false : version.isCollapsed}
class:is-collapsed={version.isCollapsed}
class="git-changelog-bottom-padding"
>
<div
class={`tree-item-self${hideTitleAndCollapseIcon ? '' : ' is-clickable'}`}
class="tree-item-self is-clickable"
data-tooltip-position="bottom"
onclick={hideTitleAndCollapseIcon
? undefined
: () => {
version.isCollapsed = !version.isCollapsed;
}}
onclick={() => {
version.isCollapsed = !version.isCollapsed;
}}
onauxclick={(event) => {
event.stopPropagation();
// eslint-disable-next-line eqeqeq
@ -73,40 +61,36 @@
}
}}
>
{#if !hideTitleAndCollapseIcon}
<div
class="tree-item-icon nav-folder-collapse-indicator collapse-icon"
class:is-collapsed={version.isCollapsed}
<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
>
<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>
<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}
<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 more than one option is selected then show labels -->
{#if showFilesCountSummaries === FileSummariesDisplayMode.Total}
{#if showFilesCountSummaries === FilesSummariesDisplayMode.Total}
<div class="git-changelog-stat">
<DayFilesStatusComponent
filesSummary={version.getChangelogFilesSummary()}
@ -114,7 +98,7 @@
</div>
{/if}
{#if showFilesCountSummaries === FileSummariesDisplayMode.TextAndBinary}
{#if showFilesCountSummaries === FilesSummariesDisplayMode.TextAndBinary}
{#if version.binaryFiles.length > 0}
<div class="git-changelog-stat">
<DayFilesStatusComponent
@ -148,7 +132,7 @@
/>
</div>
</div>
{#if hideTitleAndCollapseIcon ? true : !version.isCollapsed}
{#if !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,9 +1,13 @@
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 { applyDayStartHourSetting } from 'timeUtils.ts';
import { applyDayStartTimeSetting } from 'timeUtils.ts';
import { ChangelogInterval } from 'types.ts';
import {
assertNotNull,
@ -56,27 +60,14 @@ export function getIntervalAdjectiveString(
}
export function composeDailyVersionDisplayText({
timeZoneAdjustedCurrentDate,
locale,
timeZone,
timeZoneAdjustedEntryDate,
dayStartHour
fullyAdjustedCurrentDate,
fullyAdjustedEntryDate,
plugin
}: {
timeZoneAdjustedCurrentDate: Spacetime;
timeZoneAdjustedEntryDate: Spacetime;
locale: string;
dayStartHour: number;
timeZone: string;
fullyAdjustedCurrentDate: Spacetime;
fullyAdjustedEntryDate: Spacetime;
plugin: GitChangelogPlugin;
}): string {
const fullyAdjustedEntryDate = applyDayStartHourSetting({
dayStartHour,
timeZoneAdjustedDate: timeZoneAdjustedEntryDate
});
const fullyAdjustedCurrentDate = applyDayStartHourSetting({
dayStartHour,
timeZoneAdjustedDate: timeZoneAdjustedCurrentDate
});
const isToday = fullyAdjustedEntryDate.isSame(
fullyAdjustedCurrentDate,
'day'
@ -93,152 +84,163 @@ export function composeDailyVersionDisplayText({
return 'Yesterday';
}
return formatDate(fullyAdjustedEntryDate.toNativeDate(), locale, timeZone);
return formatDate(
fullyAdjustedEntryDate.toNativeDate(),
getUserLocale(plugin),
getTimeZone(plugin.settings.changelogGenerationSettings, plugin)
);
}
// Only for composing the UI string
export function applyDayDisplayOffset({
dayStartHour,
timeZoneAdjustedDate
dayStartTime,
timezoneAdjustedDate
}: {
dayStartHour: number;
timeZoneAdjustedDate: Spacetime;
dayStartTime: number;
timezoneAdjustedDate: Spacetime;
}): Spacetime {
const dayOffset = timeZoneAdjustedDate.hour() < dayStartHour ? 1 : 0;
return timeZoneAdjustedDate.clone().subtract(dayOffset, 'day');
const dayOffset = timezoneAdjustedDate.hour() < dayStartTime ? 1 : 0;
return timezoneAdjustedDate.clone().subtract(dayOffset, 'day');
}
export function composeHourlyVersionDisplayText({
timeZoneAdjustedEntryDate,
locale,
timeZone,
timeZoneAdjustedCurrentDate
fullyAdjustedCurrentDate,
fullyAdjustedEntryDate,
timezoneAdjustedEntryDate,
plugin
}: {
timeZoneAdjustedEntryDate: Spacetime;
locale: string;
timeZoneAdjustedCurrentDate: Spacetime;
timeZone: string;
fullyAdjustedCurrentDate: Spacetime;
fullyAdjustedEntryDate: Spacetime;
timezoneAdjustedEntryDate: Spacetime;
plugin: GitChangelogPlugin;
}): string {
const isToday = timeZoneAdjustedEntryDate.isSame(
timeZoneAdjustedCurrentDate,
// 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,
'day'
);
const isYesterday = timeZoneAdjustedEntryDate.isSame(
timeZoneAdjustedCurrentDate.clone().subtract(1, 'days'),
const isYesterday = fullyAdjustedEntryDate.isSame(
fullyAdjustedCurrentDate.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(locale, {
const timeFormatter = new Intl.DateTimeFormat(userLocale, {
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(locale, {
const formatter = new Intl.DateTimeFormat(userLocale, {
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(
timeZoneAdjustedEntryDate.startOf('hour').toNativeDate()
timezoneAdjustedEntryDateWithDayOffset.startOf('hour').toNativeDate()
);
}
export function composeMonthlyVersionDisplayText({
timeZoneAdjustedEntryDate,
locale,
timeZone
fullyAdjustedEntryDate,
plugin
}: {
timeZoneAdjustedEntryDate: Spacetime;
locale: string;
timeZone: string;
fullyAdjustedEntryDate: Spacetime;
plugin: GitChangelogPlugin;
}): string {
return formatMonthYear(
timeZoneAdjustedEntryDate.toNativeDate(),
locale,
timeZone
fullyAdjustedEntryDate.toNativeDate(),
getUserLocale(plugin),
getTimeZone(plugin.settings.changelogGenerationSettings, plugin)
);
}
export function composeVersionTitle({
interval,
dayStartHour,
locale,
timeZone,
timeZoneAdjustedEntryDate,
utcCurrentDateHour
plugin,
timezoneAdjustedEntryDate
}: {
interval: ChangelogInterval;
dayStartHour: number;
locale: string;
utcCurrentDateHour: string;
timeZone: string;
timeZoneAdjustedEntryDate: Spacetime;
plugin: GitChangelogPlugin;
timezoneAdjustedEntryDate: Spacetime;
}): string {
// Clipped to the hour
const timeZoneAdjustedCurrentDate =
spacetime(utcCurrentDateHour).goto(timeZone);
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
});
switch (interval) {
case ChangelogInterval.Hourly: {
return composeHourlyVersionDisplayText({
timeZoneAdjustedEntryDate,
timeZoneAdjustedCurrentDate,
locale,
timeZone
fullyAdjustedCurrentDate,
fullyAdjustedEntryDate,
timezoneAdjustedEntryDate,
plugin
});
}
case ChangelogInterval.Daily: {
return composeDailyVersionDisplayText({
timeZoneAdjustedEntryDate,
timeZoneAdjustedCurrentDate,
dayStartHour,
locale,
timeZone
fullyAdjustedCurrentDate,
fullyAdjustedEntryDate,
plugin
});
}
case ChangelogInterval.Weekly: {
return composeWeeklyVersionDisplayText({
timeZoneAdjustedEntryDate,
timeZoneAdjustedCurrentDate,
locale,
timeZone
fullyAdjustedCurrentDate,
fullyAdjustedEntryDate,
plugin
});
}
case ChangelogInterval.Monthly: {
return composeMonthlyVersionDisplayText({
timeZoneAdjustedEntryDate,
locale,
timeZone
fullyAdjustedEntryDate,
plugin
});
}
}
}
export function composeWeeklyVersionDisplayText({
timeZoneAdjustedEntryDate,
timeZoneAdjustedCurrentDate,
locale,
timeZone
fullyAdjustedCurrentDate,
fullyAdjustedEntryDate,
plugin
}: {
timeZoneAdjustedCurrentDate: Spacetime;
timeZoneAdjustedEntryDate: Spacetime;
locale: string;
timeZone: string;
fullyAdjustedCurrentDate: Spacetime;
fullyAdjustedEntryDate: Spacetime;
plugin: GitChangelogPlugin;
}): string {
const timeZoneAdjustedEntryWeek = timeZoneAdjustedEntryDate.startOf('week');
const fullyAdjustedEntryWeek = fullyAdjustedEntryDate.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'),
// 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'),
'weeks'
);
@ -249,29 +251,34 @@ export function composeWeeklyVersionDisplayText({
return 'Last week';
}
const weekNumber = timeZoneAdjustedEntryDate.week();
const userLocale = getUserLocale(plugin);
const isCurrentYear = timeZoneAdjustedEntryDate.isSame(
timeZoneAdjustedCurrentDate,
const weekNumber = fullyAdjustedEntryDate.week();
const isCurrentYear = fullyAdjustedEntryDate.isSame(
fullyAdjustedCurrentDate,
'year'
);
const nativeTimeZoneAdjustedEntryWeek =
timeZoneAdjustedEntryWeek.toNativeDate();
const nativeFullyAdjustedEntryWeek = fullyAdjustedEntryWeek.toNativeDate();
const timeZone = getTimeZone(
plugin.settings.changelogGenerationSettings,
plugin
);
if (isCurrentYear) {
const monthString = new Intl.DateTimeFormat(locale, {
const monthString = new Intl.DateTimeFormat(userLocale, {
month: 'short',
timeZone
}).format(nativeTimeZoneAdjustedEntryWeek);
}).format(nativeFullyAdjustedEntryWeek);
return `Week ${weekNumber}, ${monthString}`;
}
const monthAndYearString = new Intl.DateTimeFormat(locale, {
const monthAndYearString = new Intl.DateTimeFormat(userLocale, {
month: 'short',
year: '2-digit',
timeZone
}).format(nativeTimeZoneAdjustedEntryWeek);
}).format(nativeFullyAdjustedEntryWeek);
return `Week ${weekNumber}, ${monthAndYearString}`;
}
@ -309,22 +316,6 @@ 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 { App, ItemView } from 'obsidian';
import type { ItemView } from 'obsidian';
import { MarkdownView, TFile } from 'obsidian';
import { getNewLeaf } from 'utils.ts';
@ -87,18 +87,11 @@ export function getDisplayPath(path: string): string {
return path.split('/').last()?.replace(/\.md$/, '') ?? '';
}
/**
* 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 isDiffView(view: ItemView | null): boolean {
return (
view?.getViewType() === 'diff-view' ||
view?.getViewType() === 'split-diff-view'
);
}
export function openFile({
@ -143,18 +136,3 @@ 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,16 +1,5 @@
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';
@ -40,77 +29,4 @@ 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,27 +1,10 @@
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.34.0';
export const MAX_TESTED_GIT_PLUGIN_VERSION = '2.32.1';
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';
@ -39,25 +22,8 @@ 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,
previousVersionLastCommitHash,
previousDayLastCommitHash,
textFiles,
textFilesSummaryCached,
timeZoneAdjustedDate
timezoneAdjustedDate
}: {
binaryFiles: DiffFile[];
binaryFilesSummaryCached: FilesSummary;
commitHash: string;
previousVersionLastCommitHash?: string;
previousDayLastCommitHash?: 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 = previousVersionLastCommitHash;
this.previousVersionCommitHash = previousDayLastCommitHash;
}
public override getPotentialGitFilePath(): undefined {

View file

@ -1,8 +1,6 @@
import type { GitChangelogPluginTypes } from 'constants.ts';
import type { ChangelogEntry } from 'core/ChangelogEntry.svelte.ts';
import type GitChangelogPlugin from 'main.ts';
import type { ExtractPluginSettingsWrapper } from 'obsidian-dev-utils/obsidian/Plugin/PluginTypesBase';
import type { GitChangelogSettings } from 'settings/settings.ts';
import type { GitChangelogPluginSettings } from 'settings/settings.ts';
import type { Spacetime } from 'spacetime';
import type { TaskManager } from 'TaskManager.svelte.ts';
import type { ReadonlyDeep } from 'type-fest';
@ -14,7 +12,6 @@ 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';
@ -100,8 +97,6 @@ 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);
});
@ -124,14 +119,12 @@ export abstract class ChangelogManager<T extends ChangelogEntry> {
});
}
public abstract specificSettingsChanged(
oldSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>,
newSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>
): boolean;
public generationSettingsChanged(
oldSettings: ReadonlyDeep<GitChangelogPluginSettings>,
newSettings: GitChangelogPluginSettings
): boolean {
return this.getInterval(oldSettings) !== this.getInterval(newSettings);
}
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.
@ -148,7 +141,7 @@ export abstract class ChangelogManager<T extends ChangelogEntry> {
public abstract setNextInterval(): Promise<void>;
public abstract getInterval(
settings?: ReadonlyDeep<GitChangelogSettings>
settings?: ReadonlyDeep<GitChangelogPluginSettings>
): ChangelogInterval;
protected abstract updateEntries({
@ -169,27 +162,21 @@ 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,
upperBoundaryCommit: undefined,
git,
renameDetectionStrictness: this.plugin.settings.renameDetectionStrictness,
timeZone: getTimeZone(this.plugin)
plugin: this.plugin,
upperBoundaryCommit: undefined
});
const extractedVersions = await extractLastCommitsForInterval({
dayStartHour: this.plugin.settings.dayStartHour,
changelogGenerationSettings:
this.plugin.settings.changelogGenerationSettings,
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.
@ -201,7 +188,7 @@ export abstract class ChangelogManager<T extends ChangelogEntry> {
extractedVersions.push({
filePath: versionBeforeLatestCached.getPotentialGitFilePath(),
hash: versionBeforeLatestCached.commitHash,
timeZoneAdjustedDate: versionBeforeLatestCached.timeZoneAdjustedDate
timezoneAdjustedDate: versionBeforeLatestCached.timezoneAdjustedDate
});
}
@ -271,7 +258,6 @@ 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 });
}
@ -399,34 +385,31 @@ export abstract class ChangelogManager<T extends ChangelogEntry> {
) {
logCycles++;
const git = await this.plugin.getGit();
const timeZoneAdjustedLogs = await runLog({
const timezoneAdjustedLogs = await runLog({
abortSignal,
filePath: startingFilePath,
lowerBoundaryCommit: undefined,
maxCount: logMaxCount,
git,
renameDetectionStrictness:
this.plugin.settings.renameDetectionStrictness,
timeZone: getTimeZone(this.plugin),
plugin: 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({
dayStartHour: this.plugin.settings.dayStartHour,
changelogGenerationSettings:
this.plugin.settings.changelogGenerationSettings,
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,8 +1,6 @@
import type { GitChangelogPluginTypes } from 'constants.ts';
import type { FileChangelogEntry } from 'core/ChangelogEntry.svelte.ts';
import type GitChangelogPlugin from 'main.ts';
import type { ExtractPluginSettingsWrapper } from 'obsidian-dev-utils/obsidian/Plugin/PluginTypesBase';
import type { GitChangelogSettings } from 'settings/settings.ts';
import type { GitChangelogPluginSettings } from 'settings/settings.ts';
import type { TaskManager } from 'TaskManager.svelte.ts';
import type { ReadonlyDeep } from 'type-fest';
import type { ChangelogInterval, FileLogEntry } from 'types.ts';
@ -14,18 +12,21 @@ import {
} from 'constants.ts';
import { ChangelogManager } from 'core/ChangelogManager.svelte.ts';
import { runFileDiff } from 'core/gitOperations/runFileDiff.ts';
import { deepEqual } from 'obsidian-dev-utils/Object';
import { pickFileChangelogSettings } from 'settings/settings.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { validateChangelogInterval } from 'settings/validation/changelogInterval.ts';
export class FileChangelogManager extends ChangelogManager<FileChangelogEntry> {
public constructor({
// ActiveGitFile,
plugin,
taskManager
}: {
// ActiveGitFile?: string;
plugin: GitChangelogPlugin;
taskManager: TaskManager;
}) {
super({ plugin, taskManager });
// This.cachedActiveGitFile = activeGitFile;
}
/**
@ -46,35 +47,23 @@ export class FileChangelogManager extends ChangelogManager<FileChangelogEntry> {
}
public override async setNextInterval(): Promise<void> {
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'
);
}
const newSettings = this.plugin.settingsClone;
public override specificSettingsChanged(
oldSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>,
newSettings: ReadonlyDeep<
ExtractPluginSettingsWrapper<GitChangelogPluginTypes>
>
): boolean {
const oldVaultGenerationSettings = pickFileChangelogSettings(oldSettings);
const newVaultGenerationSettings = pickFileChangelogSettings(newSettings);
newSettings.fileChangelogInterval = this.getNextInterval();
return !deepEqual(oldVaultGenerationSettings, newVaultGenerationSettings);
await this.plugin.saveSettings(newSettings, false);
}
public override getInterval(
settings: ReadonlyDeep<GitChangelogSettings> = this.plugin.settings
settings: ReadonlyDeep<GitChangelogPluginSettings> = this.plugin.settings
): ChangelogInterval {
return settings.fileChangelogInterval;
const interval = settings.fileChangelogInterval;
if (!validateChangelogInterval(interval)) {
return DEFAULT_SETTINGS.fileChangelogInterval;
}
return interval;
}
protected override async loadEntries({
@ -135,17 +124,11 @@ 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,
diffAlgorithm: this.plugin.settings.diffAlgorithm,
whitespaceIgnoreMode: this.plugin.settings.whitespaceIgnoreMode,
ignoreBlankLines: this.plugin.settings.ignoreBlankLines,
emptyTreeHash: await this.plugin.getEmptyTreeHash(),
git
plugin: this.plugin
});
}

View file

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

View file

@ -1,7 +1,8 @@
import type { SimpleGit } from 'simple-git';
import type GitChangelogPlugin from 'main.ts';
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';
@ -13,23 +14,21 @@ export async function findFirstFileCommitBefore({
abortSignal,
filePath,
minutes,
timeZone,
git,
renameDetectionStrictness
plugin
}: {
abortSignal: AbortSignal;
filePath: string;
minutes: number;
timeZone: string;
git: SimpleGit;
renameDetectionStrictness: number;
plugin: GitChangelogPlugin;
}): 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(timeZone);
const currentTime = spacetime.now(
getTimeZone(plugin.settings.changelogGenerationSettings, plugin)
);
let startingCommit: string | undefined;
while (
@ -37,7 +36,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'
@ -50,10 +49,8 @@ export async function findFirstFileCommitBefore({
filePath: startingFilePath,
lowerBoundaryCommit: undefined,
maxCount,
upperBoundaryCommit: startingCommit,
git,
renameDetectionStrictness,
timeZone
plugin,
upperBoundaryCommit: startingCommit
});
if (firstEntriesOutsideInterval.length < maxCount) {
@ -76,7 +73,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,44 +1,23 @@
import type { LogResult, SimpleGit } from 'simple-git';
import type GitChangelogPlugin from 'main.ts';
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,
isoString,
git,
timeZone
plugin
}: {
abortSignal: AbortSignal;
minutes?: number;
isoString?: string;
git: SimpleGit;
timeZone: string;
minutes: number;
plugin: GitChangelogPlugin;
}): 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': isoString ?? `${assertNotNull(minutes) * 60 - 3} seconds ago`,
'--before': `${minutes * 60 - 3} seconds ago`,
'--diff-merges': 'first-parent',
format: {
date: '%cI',
@ -49,13 +28,15 @@ export async function findFirstCommitBefore({
strictDate: true
};
let result: LogResult;
try {
result = await git.log(options);
} catch {
// E.g. error when there are no commits in the repo
return undefined;
if (abortSignal.aborted) {
throw new AbortError();
}
const git = await plugin.getGit();
const result = await git.log(options);
const timezone = getTimeZone(
plugin.settings.changelogGenerationSettings,
plugin
);
if (abortSignal.aborted) {
throw new AbortError();
@ -66,11 +47,9 @@ export async function findFirstCommitBefore({
return undefined;
}
return result.all
.map<LogEntry>((entry) => ({
filePath: undefined,
hash: entry.hash,
timeZoneAdjustedDate: spacetime(entry.date).goto(timeZone)
}))
.at(0);
return result.all.map<LogEntry>((entry) => ({
filePath: undefined,
hash: entry.hash,
timezoneAdjustedDate: spacetime(entry.date).goto(timezone)
}))[0];
}

View file

@ -1,63 +0,0 @@
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

@ -0,0 +1,32 @@
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,6 +1,9 @@
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';
@ -20,14 +23,11 @@ export function addFileStatusToSummary(
}
}
export function assignDiffAlgorithm({
arguments_,
diffAlgorithm
}: {
arguments_: string[];
diffAlgorithm: DiffAlgorithm;
}): void {
switch (diffAlgorithm) {
export function assignDiffAlgorithm(
arguments_: string[],
plugin: GitChangelogPlugin
): void {
switch (getDiffAlgorithm(plugin.settings.changelogGenerationSettings)) {
case DiffAlgorithm.Default: {
arguments_.push('--diff-algorithm=default');
break;
@ -44,15 +44,13 @@ export function assignDiffAlgorithm({
}
}
export function assignWhitespaceIgnoreSettings({
arguments_,
whitespaceIgnoreMode,
ignoreBlankLines
}: {
arguments_: string[];
whitespaceIgnoreMode: WhitespaceIgnoreMode;
ignoreBlankLines: boolean;
}): void {
export function assignWhitespaceIgnoreSettings(
arguments_: string[],
plugin: GitChangelogPlugin
): void {
const whitespaceIgnoreMode = getWhitespaceIgnoreMode(
plugin.settings.changelogGenerationSettings
);
switch (whitespaceIgnoreMode) {
case WhitespaceIgnoreMode.None: {
break;
@ -71,7 +69,7 @@ export function assignWhitespaceIgnoreSettings({
}
}
if (ignoreBlankLines) {
if (plugin.settings.changelogGenerationSettings.ignoreBlankLines) {
arguments_.push('--ignore-blank-lines');
}
}

View file

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

View file

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

View file

@ -1,12 +1,8 @@
import type GitChangelogPlugin from 'main.ts';
import type { SimpleGit } from 'simple-git';
import type {
DiffAlgorithm,
FileLogEntry,
WhitespaceIgnoreMode
} from 'types.ts';
import type { FileLogEntry } from 'types.ts';
import { FileChangelogEntry } from 'core/ChangelogEntry.svelte.ts';
import { getEmptyTreeHash } from 'core/gitOperations/getEmptyTreeHash.ts';
import {
assignDiffAlgorithm,
assignWhitespaceIgnoreSettings,
@ -18,33 +14,19 @@ export async function runFileDiff({
abortSignal,
newCommit,
oldCommit,
plugin,
git,
diffAlgorithm,
whitespaceIgnoreMode,
ignoreBlankLines,
emptyTreeHash
plugin
}: {
abortSignal: AbortSignal;
newCommit: FileLogEntry;
oldCommit?: FileLogEntry;
plugin?: GitChangelogPlugin;
git: SimpleGit;
diffAlgorithm: DiffAlgorithm;
whitespaceIgnoreMode: WhitespaceIgnoreMode;
ignoreBlankLines: boolean;
emptyTreeHash: string;
plugin: GitChangelogPlugin;
}): 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'
);
@ -57,15 +39,13 @@ export async function runFileDiff({
'--no-renames'
// `--exit-code`,
];
assignDiffAlgorithm({ arguments_: numstatArguments, diffAlgorithm });
assignWhitespaceIgnoreSettings({
arguments_: numstatArguments,
whitespaceIgnoreMode,
ignoreBlankLines
});
assignDiffAlgorithm(numstatArguments, plugin);
assignWhitespaceIgnoreSettings(numstatArguments, plugin);
// 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,
@ -97,6 +77,11 @@ export async function runFileDiff({
);
}
if (abortSignal.aborted) {
throw new AbortError();
}
const git = await plugin.getGit();
const diffNumstatResult = await git.diffSummary(numstatArguments);
if (
@ -128,7 +113,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

@ -1,17 +0,0 @@
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,7 +1,9 @@
import type { SimpleGit } from 'simple-git';
import type GitChangelogPlugin from 'main.ts';
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';
@ -16,23 +18,16 @@ export async function runLog({
filePath,
lowerBoundaryCommit,
maxCount,
upperBoundaryCommit,
timeZone,
git,
renameDetectionStrictness
plugin,
upperBoundaryCommit
}: {
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> = {
@ -55,7 +50,8 @@ 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'] = `${renameDetectionStrictness}%`;
options['--find-renames'] =
`${getRenameDetectionStrictness(plugin.settings.changelogGenerationSettings)}%`;
}
if (upperBoundaryCommit) {
@ -64,8 +60,15 @@ 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) {
@ -106,7 +109,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,16 +1,9 @@
/* eslint-disable no-magic-numbers */
import type GitChangelogPlugin from 'main.ts';
import type { SimpleGit } from 'simple-git';
import type {
DiffAlgorithm,
DiffFile,
FilesSummary,
LogEntry,
TextDiffFile,
WhitespaceIgnoreMode
} from 'types.ts';
import type { DiffFile, FilesSummary, LogEntry, TextDiffFile } from 'types.ts';
import { VaultChangelogEntry } from 'core/ChangelogEntry.svelte.ts';
import { getEmptyTreeHash } from 'core/gitOperations/getEmptyTreeHash.ts';
import {
addFileStatusToSummary,
assignDiffAlgorithm,
@ -18,6 +11,8 @@ 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';
@ -59,94 +54,65 @@ export function compareTextFiles(
return leftFile.pathGitRelative.localeCompare(rightFile.pathGitRelative);
}
// eslint-disable-next-line complexity
export async function runRepoDiff({
abortSignal,
newCommit,
oldCommit,
git,
plugin,
excludeFilesAndFoldersLines,
convertToIncludeList,
renameLimit,
renameDetectionStrictness,
diffAlgorithm,
whitespaceIgnoreMode,
ignoreBlankLines,
emptyTreeHash,
enableExclusionList
plugin
}: {
abortSignal: AbortSignal;
newCommit: LogEntry;
oldCommit?: LogEntry;
diffAlgorithm: DiffAlgorithm;
git: SimpleGit;
excludeFilesAndFoldersLines: readonly string[];
enableExclusionList: boolean;
plugin?: GitChangelogPlugin;
convertToIncludeList: boolean;
renameLimit: number;
emptyTreeHash: string;
renameDetectionStrictness: number;
ignoreBlankLines: boolean;
whitespaceIgnoreMode: WhitespaceIgnoreMode;
plugin: GitChangelogPlugin;
}): Promise<undefined | VaultChangelogEntry> {
if (newCommit === undefined) {
plugin?.consoleDebug('newCommit is undefined');
plugin.consoleDebug('newCommit is undefined');
}
if (abortSignal.aborted) {
throw new AbortError();
}
const pathSpec = enableExclusionList
? convertGitIgnoreToPathspec(
excludeFilesAndFoldersLines,
convertToIncludeList
)
: undefined;
const pathSpec = convertGitIgnoreToPathspec(
plugin.settings.vaultChangelogGenerationSettings.excludeFilesAndFoldersLines
);
const numstatArguments = [
'--numstat',
`-l${renameLimit}`,
`--find-renames=${renameDetectionStrictness}%`,
`-l${getRenameLimit(plugin.settings.changelogGenerationSettings)}`,
`--find-renames=${getRenameDetectionStrictness(plugin.settings.changelogGenerationSettings)}%`,
'--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({ arguments_: numstatArguments, diffAlgorithm });
assignWhitespaceIgnoreSettings({
arguments_: numstatArguments,
whitespaceIgnoreMode,
ignoreBlankLines
});
assignDiffAlgorithm(numstatArguments, plugin);
assignWhitespaceIgnoreSettings(numstatArguments, plugin);
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,
abortSignal,
git
plugin
});
numstatArguments.push(oldCommit.hash, newCommit.hash);
}
if (pathSpec && pathSpec.length > 0) {
if (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 !== '');
@ -203,7 +169,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]) {
@ -244,10 +210,10 @@ export async function runRepoDiff({
binaryFiles,
binaryFilesSummaryCached: binaryFilesSummary,
commitHash: newCommit.hash,
previousVersionLastCommitHash: oldCommit?.hash,
previousDayLastCommitHash: oldCommit?.hash,
textFiles,
textFilesSummaryCached: textFilesSummary,
timeZoneAdjustedDate: newCommit.timeZoneAdjustedDate
timezoneAdjustedDate: newCommit.timezoneAdjustedDate
});
return dayEntry;

View file

@ -1,7 +1,6 @@
import type GitChangelogPlugin from 'main.ts';
import type { SimpleGit } from 'simple-git';
import { AbortError, DiffFileStatus } from 'types.ts';
import { DiffFileStatus } from 'types.ts';
import type { DiffResultNameStatusFile } from './simpleGitTypes.ts';
@ -14,21 +13,13 @@ export async function runRepoDiffStatus({
newCommit,
oldCommit,
pathSpec,
git,
plugin,
abortSignal
plugin
}: {
newCommit: string;
oldCommit?: string;
pathSpec: string[] | undefined;
plugin?: GitChangelogPlugin;
abortSignal: AbortSignal;
git: SimpleGit;
pathSpec: string[];
plugin: GitChangelogPlugin;
}): Promise<Record<string, DiffFileStatus> | undefined> {
if (abortSignal.aborted) {
throw new AbortError();
}
if (oldCommit === undefined) {
return undefined;
}
@ -44,9 +35,10 @@ 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 && pathSpec.length > 0) {
if (pathSpec.length > 0) {
diffStatusArguments.push('--', ...pathSpec);
}
const git = await plugin.getGit();
const diffStatusResult = await git.diffSummary(diffStatusArguments);
const changedFilesMap: Record<string, DiffFileStatus> = {};
@ -68,7 +60,7 @@ export async function runRepoDiffStatus({
file.status ?? DiffNameStatus.MODIFIED
)
) {
plugin?.consoleDebug(
plugin.consoleDebug(
`Unexpected file status of ${file.file}:`,
file.status
);

View file

@ -1,11 +1,6 @@
/* eslint-disable unicorn/prevent-abbreviations */
import type { SimpleGit } from 'simple-git';
import type {
DiffAlgorithm,
LogEntry,
TextDiffBaseStats,
WhitespaceIgnoreMode
} from 'types.ts';
import type GitChangelogPlugin from 'main.ts';
import type { LogEntry, TextDiffBaseStats } from 'types.ts';
import {
assignDiffAlgorithm,
@ -19,41 +14,32 @@ import { AbortError } from 'types.ts';
export async function runWorkingDirFileDiff({
abortSignal,
oldCommit,
activeGitFile,
git,
diffAlgorithm,
whitespaceIgnoreMode,
ignoreBlankLines
plugin,
activeGitFile
}: {
diffAlgorithm: DiffAlgorithm;
abortSignal: AbortSignal;
oldCommit: LogEntry;
activeGitFile: string;
git: SimpleGit;
whitespaceIgnoreMode: WhitespaceIgnoreMode;
ignoreBlankLines: boolean;
plugin: GitChangelogPlugin;
}): 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({ arguments_: numstatArguments, diffAlgorithm });
assignWhitespaceIgnoreSettings({
arguments_: numstatArguments,
whitespaceIgnoreMode,
ignoreBlankLines
});
assignDiffAlgorithm(numstatArguments, plugin);
assignWhitespaceIgnoreSettings(numstatArguments, plugin);
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,12 +1,9 @@
import type { GitChangelogPluginTypes } from 'constants.ts';
import type { ExtractPluginSettingsWrapper } from 'obsidian-dev-utils/obsidian/Plugin/PluginTypesBase';
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
import type { Spacetime, TimeUnit } from 'spacetime';
import type { ReadonlyDeep } from 'type-fest';
import type { ChangelogInterval, FilesSummary, LogEntry } from 'types.ts';
import { deepEqual } from 'obsidian-dev-utils/Object';
import { pickGeneralChangelogSettings } from 'settings/settings.ts';
import { applyDayStartHourSetting } from 'timeUtils.ts';
import { getDayStartTime } from 'settings/ui/DayStartTime.ts';
import { applyDayStartTimeSetting } from 'timeUtils.ts';
export const GIT_MAX_CONCURRENT_PROCESSES = 6;
@ -71,24 +68,24 @@ export async function isSameAsync({
}
export async function extractLastCommitsForInterval({
changelogGenerationSettings,
interval,
previouslySeenFullyAdjustedDates,
timeZoneAdjustedLogs,
dayStartHour
timezoneAdjustedLogs
}: {
changelogGenerationSettings: ChangelogGenerationSettings;
interval: ChangelogInterval;
previouslySeenFullyAdjustedDates?: Set<Spacetime>;
timeZoneAdjustedLogs: LogEntry[];
dayStartHour: number;
timezoneAdjustedLogs: LogEntry[];
}): Promise<LogEntry[]> {
const lastCommitsInEachInterval: LogEntry[] = [];
const fullyAdjustedSeenDates =
previouslySeenFullyAdjustedDates ?? new Set<Spacetime>();
for (const log of timeZoneAdjustedLogs) {
const fullyAdjustedLogDate = applyDayStartHourSetting({
dayStartHour,
timeZoneAdjustedDate: log.timeZoneAdjustedDate
for (const log of timezoneAdjustedLogs) {
const fullyAdjustedLogDate = applyDayStartTimeSetting({
dayStartTime: getDayStartTime(changelogGenerationSettings),
timezoneAdjustedDate: log.timezoneAdjustedDate
});
const logDateAlreadySeen = await dateAlreadySeen({
@ -105,24 +102,3 @@ 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,6 +1,5 @@
import type GitChangelogPlugin from 'main.ts';
import type { WorkspaceLeaf } from 'obsidian';
import type { GitChangelogSettings } from 'settings/settings.ts';
import type { MenuItem, WorkspaceLeaf } from 'obsidian';
import { COPY_COMMIT_HASH_ICON, PLUGIN_NAME_SENTENCE_CASE } from 'constants.ts';
import { Menu, TFolder } from 'obsidian';
@ -15,15 +14,17 @@ 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) => {
const gitRelativePath = plugin
.getGitPlugin()
.gitManager.getRelativeRepoPath(file.path, true);
menu.addItem((item) => {
const gitRelativePath = plugin
.getGitPlugin()
.gitManager.getRelativeRepoPath(file.path, true);
addExcludeMenuItem({
menu,
isFolder: file instanceof TFolder,
gitRelativePath,
plugin
addExcludeMenuItem({
item,
isFolder: file instanceof TFolder,
gitRelativePath,
plugin
});
});
})
);
@ -96,78 +97,41 @@ 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({
menu,
item,
isFolder,
plugin,
gitRelativePath
}: {
menu: Menu;
item: MenuItem;
isFolder: boolean;
gitRelativePath: string;
plugin: GitChangelogPlugin;
}): void {
const absoluteGitIgnoreRule = convertPathToAbsoluteGitIgnoreRule({
// 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({
isFolder,
gitRelativePath
gitRelativePath,
plugin
});
// 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;
}
const ruleAlreadyExists = lineNumber !== -1;
const actionTitle = ruleAlreadyExists ? 'Reinclude' : 'Exclude';
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
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
}));
});
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({
@ -185,11 +149,13 @@ export function handleChangelogViewContextMenu({
}): void {
// Skip adding the "Git changelog: Exclude" item again if the usual file menu is shown.
if (!inFileMenu && gitRelativePath) {
addExcludeMenuItem({
menu,
isFolder: false,
gitRelativePath,
plugin
menu.addItem((item) => {
addExcludeMenuItem({
item,
isFolder: false,
gitRelativePath,
plugin
});
});
}
@ -239,48 +205,59 @@ export function convertPathToAbsoluteGitIgnoreRule({
return convertPathToGitIgnoreRule(composedPath);
}
/**
* 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,
export function isAbsolutePathInExcludeFilesAndFolders({
isFolder,
gitRelativePath,
plugin
}: {
absoluteGitIgnoreRule: string;
isFolder: boolean;
gitRelativePath: string;
plugin: GitChangelogPlugin;
}): number {
const existingLines = plugin.settings.excludeFilesAndFoldersLines;
const gitIgnoreAbsoluteRule = convertPathToAbsoluteGitIgnoreRule({
isFolder,
gitRelativePath
});
const existingLines =
plugin.settingsClone.vaultChangelogGenerationSettings
.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(absoluteGitIgnoreRule);
return existingRules.indexOf(gitIgnoreAbsoluteRule);
}
export async function removeExcludeFilesAndFoldersItem(
lineNumber: number,
plugin: GitChangelogPlugin
): Promise<void> {
await plugin.settingsManager.editAndSave(
(settings: GitChangelogSettings): void => {
settings.excludeFilesAndFoldersLines.splice(lineNumber, 1);
}
const newSettings = plugin.settingsClone;
newSettings.vaultChangelogGenerationSettings.excludeFilesAndFoldersLines.splice(
lineNumber,
1
);
await plugin.saveSettings(newSettings);
}
export async function addExcludeFilesAndFoldersItem({
path,
gitRelativePath,
isFolder,
plugin
}: {
path: string;
gitRelativePath: string;
isFolder: boolean;
plugin: GitChangelogPlugin;
}): Promise<void> {
await plugin.settingsManager.editAndSave(
(settings: GitChangelogSettings): void => {
settings.excludeFilesAndFoldersLines.push(path);
}
const gitIgnoreRule = convertPathToAbsoluteGitIgnoreRule({
gitRelativePath,
isFolder
});
const newSettings = plugin.settingsClone;
newSettings.vaultChangelogGenerationSettings.excludeFilesAndFoldersLines.push(
gitIgnoreRule
);
await plugin.saveSettings(newSettings);
}

View file

@ -1,25 +1,38 @@
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 SettingComponent {
export abstract class GitChangelogSetting {
protected containerEl: HTMLElement;
protected disabled: boolean;
protected plugin: GitChangelogPlugin;
protected settingTab: GitChangelogSettingsTab;
protected settingTab?: GitChangelogSettingsTab;
public constructor({
containerEl,
disabled = false,
plugin
plugin,
settingTab
}: {
containerEl: HTMLElement;
disabled?: boolean;
plugin: GitChangelogPlugin;
settingTab?: GitChangelogSettingsTab;
}) {
this.plugin = plugin;
this.containerEl = containerEl;
this.disabled = disabled;
this.settingTab = this.plugin.settingsTab;
this.containerEl = this.settingTab.containerEl;
this.settingTab = settingTab;
}
public abstract display(): void;
@ -40,9 +53,46 @@ export abstract class SettingComponent {
*/
protected refreshDisplayWithDelay(timeout = 80): void {
if (this.settingTab) {
setTimeout(() => {
this.settingTab?.display();
}, timeout);
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)
);
}
}
}
}

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();
}

37
src/settings/helper.ts Normal file
View file

@ -0,0 +1,37 @@
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,14 +1,11 @@
import type { GitChangelogPluginTypes } from 'constants.ts';
import type { ExtractPluginSettingsWrapper } from 'obsidian-dev-utils/obsidian/Plugin/PluginTypesBase';
import type { Except, ReadonlyDeep } from 'type-fest';
import { PluginSettingsBase } from 'obsidian-dev-utils/obsidian/Plugin/PluginSettingsBase';
import spacetime from 'spacetime';
import {
ChangelogInterval,
DiffAlgorithm,
DiffMeasurementUnit,
FileExplorerStats,
FileSummariesDisplayMode,
FilesSummariesDisplayMode,
WhitespaceIgnoreMode
} from 'types.ts';
@ -18,186 +15,140 @@ 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';
export class GitChangelogSettings {
// Plugin state
public autoCommitDisabledWarningDismissed = false;
public firstStartup = true;
public activeMinutesPassedSinceLastCheckpoint = 0;
/**
* 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;
// ShowFilesSummaryCountOptions[]; //Set<ShowFilesSummaryCountOptions>;
// VaultChangelogFilesVisibility: VaultChangelogFilesVisibility;
// NotifyOnLargeCommitAdditions: boolean;
// NotifyOnLargeCommitAdditionsWarningThreshold: string;
public dedicatedFileTypeSummaries: string[] = [];
public fileSummariesDisplayMode: FileSummariesDisplayMode =
FileSummariesDisplayMode.Total;
public dedicatedFileTypeSummaries: string[] = [
...DEFAULT_SETTINGS.dedicatedFileTypeSummaries
];
public fileExplorerInterval = '4320'; // In mins
public fileExplorerStats: FileExplorerStats = FileExplorerStats.Disabled;
public fileChangelogInterval: ChangelogInterval =
DEFAULT_SETTINGS.fileChangelogInterval;
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 fileExplorerInterval: string = DEFAULT_SETTINGS.fileExplorerInterval;
public fileExplorerStats: FileExplorerStats =
DEFAULT_SETTINGS.fileExplorerStats;
public notifyOnHighFilesChanged = false;
public filesChangedWarningThreshold = '50';
public filesChangesWarningThreshold: string =
DEFAULT_SETTINGS.filesChangesWarningThreshold;
public checkpointCommits: string[] = [];
public reviewChangesReminderInterval = 0;
public fileSummariesDisplayMode: FilesSummariesDisplayMode =
DEFAULT_SETTINGS.fileSummariesDisplayMode;
public statusBarInterval = 30; // In mins
public showStatusBarStats = false;
public notifyOnContentDeletionsAndMovesThresholdReached: boolean =
DEFAULT_SETTINGS.notifyOnContentDeletionsAndMovesThresholdReached;
// FileGenerationSettings
public fileChangelogInterval: ChangelogInterval = ChangelogInterval.Daily;
public notifyOnFilesChangesThresholdReached: boolean =
DEFAULT_SETTINGS.notifyOnFilesChangesThresholdReached;
// VaultGenerationSettings
public excludeFilesAndFoldersLines: string[] = [];
public enableExclusionList = true;
public convertToIncludeList = false;
public vaultChangelogInterval = 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;
/**
* 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;
public constructor(data: unknown) {
super();
// Object.assign(this, DEFAULT_SETTINGS);
this.init(data);
this._shouldSaveAfterLoad = true;
}
}
// 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_VAULT_CHANGELOG_GENERATION_SETTINGS: VaultChangelogGenerationSettings =
{
excludeFilesAndFoldersLines: [],
interval: ChangelogInterval.Daily
} 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'
>;
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;

View file

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

View file

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

View file

@ -1,14 +1,48 @@
import { SettingComponent } from 'settings/components/setting.ts';
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { DiffMeasurementUnit } from 'types.ts';
export class ChangelogMeasurementUnit extends SettingComponent {
export class ChangelogMeasurementUnit extends GitChangelogSetting {
public display(): void {
this.createSetting()
.setName('Changelog measurement unit')
.addTypedDropdown((dropdown) => {
dropdown.addOption(DiffMeasurementUnit.Lines, 'Lines');
dropdown.addOption(DiffMeasurementUnit.Words, 'Words');
this.settingTab.bind(dropdown, 'diffMeasurementUnit');
.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);
});
});
}
}
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,23 +1,29 @@
import { SettingComponent } from 'settings/components/setting.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { FileExplorerStats } from 'types.ts';
export class ChangelogStatsInFileExplorerOptions extends SettingComponent {
export class ChangelogStatsInFileExplorerOptions extends GitChangelogSetting {
public display(): void {
this.createSetting()
.setName('Show changelog stats in file explorer')
.addTypedDropdown((dropdown) => {
dropdown.addOption(FileExplorerStats.Disabled, 'Disabled');
dropdown.addOption(FileExplorerStats.Folders, 'Folders');
dropdown.addOption(
FileExplorerStats.FoldersAndNotes,
'Folders and notes'
.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
);
dropdown.onChange((value: FileExplorerStats) => {
this.refreshDisplayWithDelay(0);
this.settingTab.bind(dropdown, 'fileExplorerStats', {
onChanged: () => {
// eslint-disable-next-line no-magic-numbers
this.refreshDisplayWithDelay(30);
}
const newSettings = this.plugin.settingsClone;
newSettings.fileExplorerStats = value;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.plugin.saveSettings(newSettings);
});
});
}

View file

@ -1,6 +1,7 @@
import { SettingComponent } from 'settings/components/setting.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
export class ContentDeletionsMovesThreshold extends SettingComponent {
export class ContentDeletionsMovesThreshold extends GitChangelogSetting {
public display(): void {
this.createSetting()
.setName('Custom threshold for deletions/moves alert')
@ -8,10 +9,33 @@ export class ContentDeletionsMovesThreshold extends SettingComponent {
"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);
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);
});
// This.restrictToPositiveIntegerInput(text);
this.settingTab.bind(text, 'contentDeletionsAndMovesWarningThreshold');
this.setNonDefaultValue({
settingsProperty: 'contentDeletionsAndMovesWarningThreshold',
text
});
});
}
}
export function validateContentDeletionsMovesThreshold(
contentDeletionsMovesThreshold: string
): boolean {
if (
!Number.isInteger(Number(contentDeletionsMovesThreshold)) ||
Number(contentDeletionsMovesThreshold) < 1
) {
return false;
}
return true;
}

View file

@ -1,63 +1,50 @@
import type GitChangelogPlugin from 'main.ts';
import { SettingComponent } from 'settings/components/setting.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
export class CustomLocale extends SettingComponent {
export class CustomLocale extends GitChangelogSetting {
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.settingTab.bind(text, 'locale', {
onChanged: () => {
// Without this check, plugin fails on startup
if (this.plugin.settingsManager) {
this.plugin.localeSafe = getLocaleToAssign(this.plugin);
}
}
this.setNonDefaultValue({
settingsProperty: 'changelogGenerationSettings',
diffSettingsProperty: 'locale',
text
});
});
}
}
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';
}
export function getUserLocale(plugin: GitChangelogPlugin): string {
const locale = plugin.settings.changelogGenerationSettings.locale;
if (validateLocale(locale)) {
return locale;
}
return plugin.detectedLocale;
// 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;
}
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 {
export function validateLocale(locale?: string): boolean {
try {
if (!locale || typeof locale !== 'string') {
return false;
}
new Intl.Locale(locale);
if (Intl.DateTimeFormat.supportedLocalesOf([locale]).length === 0) {
return false;
}
return Intl.DateTimeFormat.supportedLocalesOf([locale]).length > 0;
} catch {
return false;
}
return true;
}

View file

@ -1,48 +1,77 @@
import type GitChangelogPlugin from 'main.ts';
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
import { SettingComponent } from 'settings/components/setting.ts';
import { Notice } from 'obsidian';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { TimeZoneSuggest } from 'settings/components/suggest.ts';
import { TIME_ZONES_LIST } from 'settings/settings.ts';
import { DEFAULT_SETTINGS, TIME_ZONES_LIST } from 'settings/settings.ts';
export class CustomTimeZone extends SettingComponent {
export class CustomTimeZone extends GitChangelogSetting {
public display(): void {
this.createSetting()
.setName('Timezone')
.addText((text) => {
this.settingTab.bind(text, 'timeZone');
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
});
new TimeZoneSuggest(this.plugin.app, text.inputEl);
});
}
}
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 detectSystemTimeZone(): string {
return Intl.DateTimeFormat().resolvedOptions().timeZone.toLowerCase();
}
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';
}
export function getSystemTimeZone(plugin: GitChangelogPlugin): string {
if (plugin.detectedTimeZone !== undefined) {
return plugin.detectedTimeZone;
}
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(plugin: GitChangelogPlugin): string {
return plugin.settings.timeZone ===
plugin.settingsManager.defaultSettings.timeZone
? getSystemTimeZone(plugin)
: plugin.settings.timeZone;
export function getTimeZone(
changelogGenerationSettings: ChangelogGenerationSettings,
plugin: GitChangelogPlugin
): string {
return validateCustomTimeZone(changelogGenerationSettings.timezone)
? changelogGenerationSettings.timezone
: getSystemTimeZone(plugin);
}
export function validateCustomTimeZone(timeZone: string): boolean {
return TIME_ZONES_LIST.has(timeZone.toLowerCase());
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());
}

View file

@ -1,32 +1,60 @@
import { moment } from 'obsidian';
import { SettingComponent } from 'settings/components/setting.ts';
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
export class DayStartHour extends SettingComponent {
import { moment } from 'obsidian';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
export class DayStartTime extends GitChangelogSetting {
public display(): void {
this.createSetting()
.setName('Day start time')
.setDesc(
'Adjust the day based on your schedule. Applies exclusively to the day interval in the changelog views.'
)
.setDesc('Adjust the day based on your schedule.')
.addTime((text) => {
this.settingTab.bind(text, 'dayStartHour', {
componentToPluginSettingsValueConverter: (
uiValue: moment.Duration
) => {
text
.setValue(
moment.duration({
hours:
this.plugin.settings.changelogGenerationSettings.dayStartHour
})
)
.onChange((value) => {
// 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 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);
// 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';
});
}
}
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,18 +1,27 @@
import { SettingComponent } from 'settings/components/setting.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
export class DeletionsNotificationThreshold extends SettingComponent {
export class DeletionsNotificationThreshold extends GitChangelogSetting {
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) => {
this.settingTab.bind(toggle, 'notifyOnHighContentDeletionsAndMoves', {
onChanged: () => {
.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);
this.refreshDisplayWithDelay();
}
});
});
})
);
}
}

View file

@ -1,6 +1,6 @@
import { SettingComponent } from 'settings/components/setting.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
export class DetectMovedContentToggle extends SettingComponent {
export class DetectMovedContentToggle extends GitChangelogSetting {
public display(): void {
this.createSetting()
.setName('Detect moved lines/words')
@ -8,7 +8,16 @@ export class DetectMovedContentToggle extends SettingComponent {
`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) =>
this.settingTab.bind(toggle, 'detectMovedContent')
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);
})
);
}
}

View file

@ -1,12 +1,14 @@
import type GitChangelogPlugin from 'main.ts';
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
import { appendCodeBlock } from 'obsidian-dev-utils/HTMLElement';
import { SettingComponent } from 'settings/components/setting.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { DiffAlgorithm } from 'types.ts';
const GIT_CONFIG_PATH = '.git/config';
export class DiffAlgorithmOptions extends SettingComponent {
export class DiffAlgorithmOptions extends GitChangelogSetting {
public display(): void {
this.createSetting()
.setName('Difference detection algorithm')
@ -25,7 +27,9 @@ export class DiffAlgorithmOptions extends SettingComponent {
button.setButtonText('Apply');
button.setDisabled(shouldDisableApplyButton(this.plugin));
button.onClick(async () => {
const diffAlgorithm = this.plugin.settings.diffAlgorithm;
const diffAlgorithm = getDiffAlgorithm(
this.plugin.settings.changelogGenerationSettings
);
if (diffAlgorithm !== DiffAlgorithm.Inherit) {
try {
const git = await this.plugin.getGit();
@ -41,24 +45,51 @@ export class DiffAlgorithmOptions extends SettingComponent {
}
});
})
.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: () => {
.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(() => {
// eslint-disable-next-line no-magic-numbers
this.refreshDisplayWithDelay(30);
}
});
});
});
}
}
function shouldDisableApplyButton(plugin: GitChangelogPlugin): boolean {
const diffAlgorithm = plugin.settings.diffAlgorithm;
const diffAlgorithm = getDiffAlgorithm(
plugin.settings.changelogGenerationSettings
);
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 { EXCLUDE_FILES_AND_FOLDERS } from 'constants.ts';
import { SettingComponent } from 'settings/components/setting.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
export class ExcludeFilesAndFolders extends SettingComponent {
export class ExcludeFilesAndFolders extends GitChangelogSetting {
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,30 +38,23 @@ export class ExcludeFilesAndFolders extends SettingComponent {
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.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
.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.inputEl.classList.add('git-changelog-text-area');
});
}
@ -76,7 +69,7 @@ export function convertPathToGitIgnoreRule(path: string): string {
return escaped.replaceAll(/\s(?=\s*$)/g, String.raw`\ `);
}
export function joinExcludeItems(items: readonly string[]): string {
export function joinExcludeItems(items: string[]): string {
return items.join('\n');
}
@ -93,14 +86,11 @@ export function parseGitIgnoreLine(gitIgnoreLine: string): string {
}
export function convertGitIgnoreToPathspec(
gitIgnoreRules: ReadonlyDeep<string[]>,
include: boolean
gitIgnoreRules: ReadonlyDeep<string[]>
): string[] {
try {
const items: string[] = [];
// eslint-disable-next-line @typescript-eslint/no-unnecessary-boolean-literal-compare
const excludePrefix = include === true ? '' : 'exclude,';
// Always exclude .git directory
const excludes: string[] = [':(exclude,glob)**/.git/**'];
for (const line of gitIgnoreRules.map((element) =>
parseGitIgnoreLine(element)
@ -114,20 +104,21 @@ export function convertGitIgnoreToPathspec(
// Handle patterns differently based on their format:
if (line.endsWith('/*')) {
// Single-level match
items.push(`:(${excludePrefix}glob)${formatted}`);
excludes.push(`:(exclude,glob)${formatted}`);
} else if (line.endsWith('/**') || line.endsWith('/')) {
// Recursive match
items.push(`:(${excludePrefix}glob)${formatted}`);
excludes.push(`:(exclude,glob)${formatted}`);
} else {
// All other patterns - match both item and contents
// Regardless of whether they contain special characters
items.push(
`:(${excludePrefix}glob)${formatted}`,
`:(${excludePrefix}glob)${formatted}/**`
excludes.push(
`:(exclude,glob)${formatted}`,
`:(exclude,glob)${formatted}/**`
);
}
}
return items;
return excludes;
} catch {
return [];
}

View file

@ -1,15 +1,39 @@
import { SettingComponent } from 'settings/components/setting.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
export class FileChangesNotificationThreshold extends SettingComponent {
export class FileChangesNotificationThreshold extends GitChangelogSetting {
public display(): void {
this.createSetting()
.setName('Custom threshold for file changes alert')
.addText((text) => {
this.settingTab.bind(text, 'filesChangedWarningThreshold');
text.setDisabled(this.disabled);
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.setNonDefaultValue({
settingsProperty: 'filesChangesWarningThreshold',
text
});
});
}
}
export function validateFileChangesNotificationThreshold(
fileChangesNotificationThreshold: string
): boolean {
if (
!Number.isInteger(Number(fileChangesNotificationThreshold)) ||
Number(fileChangesNotificationThreshold) < 1
) {
return false;
}
return true;
}

View file

@ -1,13 +1,42 @@
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 FileExplorerStatsInterval extends SettingComponent {
export class FileExplorerStatsInterval extends GitChangelogSetting {
public display(): void {
this.createSetting()
.setName('Interval for file explorer stats (minutes)')
.addText((text) => {
this.settingTab.bind(text, 'fileExplorerInterval');
text.setDisabled(this.disabled);
.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.restrictToPositiveIntegerInput(text, 5);
this.setNonDefaultValue({
settingsProperty: 'fileExplorerInterval',
text
});
});
}
}
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 { SettingComponent } from 'settings/components/setting.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { GitPluginState } from 'types.ts';
export class GitPluginWarning extends SettingComponent {
export class GitPluginWarning extends GitChangelogSetting {
public display(): void {
let desc: DocumentFragment | string;
let setting: Setting;

View file

@ -1,16 +1,28 @@
import { SettingComponent } from 'settings/components/setting.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
export class IgnoreBlankLinesToggle extends SettingComponent {
export class IgnoreBlankLinesToggle extends GitChangelogSetting {
public display(): void {
this.createSetting()
.setName(
createFragment((fragment) => {
fragment.appendText(`Ignore changes whose lines are all blank`);
fragment.appendText(`Ignore blank lines`);
fragment
.createEl('span', { cls: 'nav-file-tag git-changelog-new' })
.setText('NEW');
})
)
.setDesc(
"Doesn't show a file as changed if the only changes are blank lines."
)
.addToggle((toggle) => this.settingTab.bind(toggle, 'ignoreBlankLines'));
.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);
})
);
}
}

View file

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

View file

@ -1,7 +1,10 @@
import { SettingComponent } from 'settings/components/setting.ts';
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
// https://github.com/git/git/blob/58b5801aa94ad5031978f8e42c1be1230b3d352f/diff.c#L58 - 1000 default
export class RenameDetectionFileLimit extends SettingComponent {
export class RenameDetectionFileLimit extends GitChangelogSetting {
public display(): void {
this.createSetting()
@ -17,8 +20,42 @@ export class RenameDetectionFileLimit extends SettingComponent {
);
})
)
.addNumber((text) => {
this.settingTab.bind(text, 'renameLimit');
.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
});
});
}
}
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,12 +1,16 @@
import {
MAX_RENAME_DETECTION_STRICTNESS,
MIN_RENAME_DETECTION_STRICTNESS
} from 'constants.ts';
import { ResetButton } from 'settings/components/resetButton.ts';
import { SettingComponent } from 'settings/components/setting.ts';
import type { SliderComponent } from 'obsidian';
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
export class RenameDetectionStrictnessSlider extends SettingComponent {
import { ResetButton } from 'settings/components/resetButton.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
const MIN_RENAME_DETECTION_STRICTNESS = 1;
const MAX_RENAME_DETECTION_STRICTNESS = 100;
export class RenameDetectionStrictnessSlider extends GitChangelogSetting {
public display(): void {
let slider: SliderComponent;
const setting = this.createSetting()
.setName('File move/rename detection strictness')
.setDesc(
@ -22,28 +26,50 @@ export class RenameDetectionStrictnessSlider extends SettingComponent {
);
new ResetButton(setting.controlEl).onClick(() => {
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
slider.setValue(
DEFAULT_SETTINGS.changelogGenerationSettings.renameDetectionStrictness
);
this.refreshDisplayWithDelay(0);
});
setting.addSlider((percent) => {
this.settingTab.bind(percent, 'renameDetectionStrictness');
slider = percent;
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

@ -1,139 +0,0 @@
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,16 +1,60 @@
import { SettingComponent } from 'settings/components/setting.ts';
import type { GitChangelogPluginSettings } from 'settings/settings.ts';
import type { ReadonlyDeep } from 'type-fest';
export class StatusBarInterval extends SettingComponent {
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS, MAX_SUPPORTED_INTERVAL } from 'settings/settings.ts';
export class StatusBarInterval extends GitChangelogSetting {
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.'
)
.addNumber((text) => {
this.settingTab.bind(text, 'statusBarInterval');
.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);
});
text.setDisabled(this.disabled);
this.setNonDefaultValue({
settingsProperty: 'statusBarInterval',
text
});
});
}
}
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,15 +1,27 @@
import { SettingComponent } from 'settings/components/setting.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
export class StatusBarStatsToggle extends SettingComponent {
export class StatusBarStatsToggle extends GitChangelogSetting {
public display(): void {
this.createSetting()
.setName('Active note live status bar stats')
.addToggle((toggle) => {
this.settingTab.bind(toggle, 'showStatusBarStats', {
onChanged: () => {
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.statusBarStats)
.onChange((value) => {
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,32 +1,57 @@
import { SettingComponent } from 'settings/components/setting.ts';
import type { ChangelogGenerationSettings } from 'settings/settings.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
import { DEFAULT_SETTINGS } from 'settings/settings.ts';
import { WhitespaceIgnoreMode } from 'types.ts';
export class WhitespaceIgnoreModeOptions extends SettingComponent {
export class WhitespaceIgnoreModeOptions extends GitChangelogSetting {
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');
})
)
.addTypedDropdown((dropdown) => {
dropdown.addOption(
WhitespaceIgnoreMode.None,
'Track all whitespace changes'
.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
)
);
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');
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);
});
});
}
}
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 { SettingComponent } from 'settings/components/setting.ts';
import { GitChangelogSetting } from 'settings/components/setting.ts';
export class WhitespaceSettingsHeading extends SettingComponent {
export class WhitespaceSettingsHeading extends GitChangelogSetting {
public display(): void {
this.createSetting()
.setHeading()
.setName('Whitespace settings')
.setDesc(
`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.`
`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.`
);
}
}

View file

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

View file

@ -17,28 +17,6 @@
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%;
@ -127,6 +105,7 @@
.git-changelog-view {
--git-changelog-opacity: 0.84;
display: flex;
flex-direction: column;
position: relative;
@ -134,18 +113,6 @@
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);
@ -154,16 +121,6 @@
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;
@ -238,8 +195,6 @@
/* 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,35 +3,32 @@ 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 applyDayStartHourSetting({
dayStartHour,
timeZoneAdjustedDate
export function applyDayStartTimeSetting({
dayStartTime,
timezoneAdjustedDate
}: {
dayStartHour: number;
timeZoneAdjustedDate: Spacetime;
dayStartTime: number;
timezoneAdjustedDate: Spacetime;
}): Spacetime {
return timeZoneAdjustedDate.subtract(dayStartHour, 'hours');
return timezoneAdjustedDate.subtract(dayStartTime, 'hours');
}
export function getDayStartHourAdjustedLogs(
export function getDayStartTimeAdjustedLogs(
logEntries: LogEntry[],
dayStartHour: number
dayStartTime: number
): LogEntry[] {
if (dayStartHour === 0) {
if (dayStartTime === 0) {
return logEntries;
}
return logEntries.map((entry) => {
return {
...entry,
fullyAdjustedDate: applyDayStartHourSetting({
dayStartHour,
timeZoneAdjustedDate: entry.timeZoneAdjustedDate
fullyAdjustedDate: applyDayStartTimeSetting({
dayStartTime,
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 FileSummariesDisplayMode {
export enum FilesSummariesDisplayMode {
TextAndBinary = 'Text and binary',
Total = 'Total'
// Binary = "Binary",
@ -171,15 +171,10 @@ 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,15 +1,10 @@
/* 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 {
COMPARE_REPO_COMMITS_VIEW_CONFIG,
COMPARE_TO_CHECKPOINT_VIEW_CONFIG,
FEEDBACK_URL
} from 'constants.ts';
import { FEEDBACK_URL } from 'constants.ts';
// Import * as cssColorConverter from "css-color-converter";
import { Keymap, Notice } from 'obsidian';
import { Keymap } from 'obsidian';
import { DiffFileStatus, NullValueError } from 'types.ts';
export function getFileNameFromPath({
@ -101,7 +96,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}\n${stack}`);
console.error(message);
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'
@ -125,14 +120,3 @@ 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,10 +1,7 @@
{
"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"
"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"
}