Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wip: feat: Make foam respect the .gitignore file #1413

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 67 additions & 3 deletions packages/foam-vscode/src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
/*global markdownit:readonly*/

import { workspace, ExtensionContext, window, commands } from 'vscode';
import { workspace, ExtensionContext, window, commands, Uri } from 'vscode';
import { MarkdownResourceProvider } from './core/services/markdown-provider';
import { bootstrap } from './core/model/foam';
import { Logger } from './core/utils/log';
import * as path from 'path';

import { Logger } from '../core/utils/log';
import { isEmpty, map, compact, filter, split, startsWith } from 'lodash';
import { features } from './features';
import { VsCodeOutputLogger, exposeLogger } from './services/logging';
import {
Expand All @@ -24,7 +27,7 @@ export async function activate(context: ExtensionContext) {
exposeLogger(context, logger);

try {
Logger.info('Starting Foam');
Logger.info('[wtw] Starting Foam');

if (workspace.workspaceFolders === undefined) {
Logger.info('No workspace open. Foam will not start');
Expand All @@ -33,6 +36,57 @@ export async function activate(context: ExtensionContext) {

// Prepare Foam
const excludes = getIgnoredFilesSetting().map(g => g.toString());

Logger.info('[wtw] Excluded patterns from settings: ' + excludes);

// Read all .gitignore files and add patterns to excludePatterns
const gitignoreFiles = await workspace.findFiles('**/.gitignore');

gitignoreFiles.forEach(gitignoreUri => {
try {
workspace.fs.stat(gitignoreUri); // Check if the file exists
const gitignoreContent = await workspace.fs.readFile(gitignoreUri);

// TODO maybe better to use a specific gitignore parser lib.
let ignore_rules = Buffer.from(gitignoreContent)
.toString('utf-8')
.split('\n')
.map(line => line.trim())
.filter(line => !isEmpty(line))
.filter(line => !line.startsWith('#'))
.forEach(line => excludes.push(line));

excludes.push(...ignore_rules);
Logger.info(
`Excluded patterns from ${gitignoreUri.path}: ${ignore_rules}`
);
} catch (error) {
Logger.error(`Error reading .gitignore file: ${error}`);
}
});
Comment on lines +43 to +66
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@riccardoferretti Do you think here is a reasonable place to calculate ignore rules? I tend to append them into exclude variable.

[info - 6:03:40 PM] [wtw] Starting Foam
[info - 6:03:40 PM] [wtw] Excluded patterns from settings: **/.foam/**,**/.vscode/**/*,**/_layouts/**/*,**/_site/**/*,**/node_modules/**/*,**/.git,**/.svn,**/.hg,**/CVS,**/.DS_Store,**/Thumbs.db,**/.classpath,**/.factorypath,**/.project,**/.settings
[info - 6:03:47 PM] Excluded patterns from /tmp/test_folder/.gitignore: ignored_note.md
[info - 6:03:48 PM] Loading from directories:
[info - 6:03:48 PM] - /tmp/test_folder
[info - 6:03:48 PM]   Include: **/*
[info - 6:03:48 PM]   Exclude: ignored_note.md,**/.foam/**,**/.vscode/**/*,**/_layouts/**/*,**/_site/**/*,**/node_modules/**/*,**/.git,**/.svn,**/.hg,**/CVS,**/.DS_Store,**/Thumbs.db,**/.classpath,**/.factorypath,**/.project,**/.settings
[info - 6:03:49 PM] Workspace loaded in 1071ms
[info - 6:03:49 PM] Graph loaded in 2ms
[info - 6:03:49 PM] Tags loaded in 0ms
[info - 6:03:49 PM] [wtw] Excluded patterns from settings:
[info - 6:03:49 PM] [wtw] Excluded patterns from settings:
[info - 6:03:49 PM] Loaded 2 resources
[info - 6:03:50 PM] Excluded patterns from /tmp/test_folder/.gitignore: ignored_note.md
[info - 6:03:50 PM] Excluded patterns from /tmp/test_folder/.gitignore: ignored_note.md


// Read .gitignore files and add patterns to excludePatterns
// for (const folder of workspace.workspaceFolders) {
// const gitignoreUri = Uri.joinPath(folder.uri, '.gitignore');
// try {
// await workspace.fs.stat(gitignoreUri); // Check if the file exists
// const gitignoreContent = await workspace.fs.readFile(gitignoreUri); // Read the file content
// const patterns = map(
// filter(
// split(Buffer.from(gitignoreContent).toString('utf-8'), '\n'),
// line => line && !startsWith(line, '#')
// ),
// line => line.trim()
// );
// excludePatterns.get(folder.name).push(...compact(patterns));

// Logger.info(`Excluded patterns from ${gitignoreUri.path}: ${patterns}`);
// } catch (error) {
// // .gitignore file does not exist, continue
// Logger.error(`Error reading .gitignore file: ${error}`);
// }
// }

const { matcher, dataStore, excludePatterns } =
await createMatcherAndDataStore(excludes);

Expand Down Expand Up @@ -79,6 +133,8 @@ export async function activate(context: ExtensionContext) {
const foam = await foamPromise;
Logger.info(`Loaded ${foam.workspace.list().length} resources`);

const gitignoreWatcher = workspace.createFileSystemWatcher('**/.gitignore');

context.subscriptions.push(
foam,
watcher,
Expand All @@ -100,9 +156,17 @@ export async function activate(context: ExtensionContext) {
'Foam: Reload the window to use the updated settings'
);
}
})
}),
gitignoreWatcher
);

gitignoreWatcher.onDidChange(e => {
Logger.info(`[wtw] File changed: ${e.fsPath}`);
window.showInformationMessage(
'Foam: Reload the window to use the updated .gitignore settings'
);
});

const feats = (await Promise.all(featuresPromises)).filter(r => r != null);

return {
Expand Down
4 changes: 3 additions & 1 deletion packages/foam-vscode/src/services/editor.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isEmpty } from 'lodash';
import { isEmpty, map, compact, filter, split, startsWith } from 'lodash';
import {
EndOfLine,
FileType,
Expand All @@ -25,6 +25,8 @@ import {
IDataStore,
IMatcher,
} from '../core/services/datastore';
import * as path from 'path';
import { Logger } from '../core/utils/log';

interface SelectionInfo {
document: TextDocument;
Expand Down