-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathissue-file-manager.ts
More file actions
244 lines (220 loc) · 8.17 KB
/
issue-file-manager.ts
File metadata and controls
244 lines (220 loc) · 8.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import { App, TFile } from "obsidian";
import { GitHubTrackerSettings, RepositoryTracking } from "./types";
import { escapeBody } from "./util/escapeUtils";
import { NoticeManager } from "./notice-manager";
import { GitHubClient } from "./github-client";
import {
createIssueTemplateData,
processFilenameTemplate
} from "./util/templateUtils";
import { getEffectiveRepoSettings } from "./util/settingsUtils";
import { extractPersistBlocks, mergePersistBlocks } from "./util/persistUtils";
import { shouldUpdateContent, hasStatusChanged } from "./util/contentUtils";
import { FileHelpers } from "./util/file-helpers";
import { FolderPathManager } from "./folder-path-manager";
import { CleanupManager } from "./cleanup-manager";
import { ContentGenerator } from "./content-generator";
export class IssueFileManager {
private fileHelpers: FileHelpers;
private folderPathManager: FolderPathManager;
private cleanupManager: CleanupManager;
private contentGenerator: ContentGenerator;
constructor(
private app: App,
private settings: GitHubTrackerSettings,
private noticeManager: NoticeManager,
private gitHubClient: GitHubClient,
) {
this.fileHelpers = new FileHelpers(app, noticeManager);
this.folderPathManager = new FolderPathManager();
this.cleanupManager = new CleanupManager(app, settings, noticeManager);
this.contentGenerator = new ContentGenerator(this.fileHelpers);
}
/**
* Create issue files for a repository
*/
public async createIssueFiles(
repo: RepositoryTracking,
openIssues: any[],
allIssuesIncludingRecentlyClosed: any[],
_currentIssueNumbers: Set<string>,
): Promise<void> {
// Apply global defaults to repository settings
const effectiveRepo = getEffectiveRepoSettings(repo, this.settings.globalDefaults);
const [owner, repoName] = effectiveRepo.repository.split("/");
if (!owner || !repoName) return;
const repoCleaned = repoName.replace(/\//g, "-");
const ownerCleaned = owner.replace(/\//g, "-");
await this.cleanupManager.cleanupDeletedIssues(
effectiveRepo,
ownerCleaned,
repoCleaned,
allIssuesIncludingRecentlyClosed,
);
// Create or update issue files (openIssues contains filtered issues from main.ts)
// Note: projectData is only added for project items, not for repository issues
for (const issue of openIssues) {
await this.createOrUpdateIssueFile(
effectiveRepo,
ownerCleaned,
repoCleaned,
issue,
);
}
}
private async createOrUpdateIssueFile(
repo: RepositoryTracking,
ownerCleaned: string,
repoCleaned: string,
issue: any,
): Promise<void> {
// Generate filename using template
const templateData = createIssueTemplateData(issue, repo.repository);
const baseFileName = processFilenameTemplate(
repo.issueNoteTemplate || "Issue - {number}",
templateData,
this.settings.dateFormat
);
const fileName = `${baseFileName}.md`;
const issueFolderPath = this.folderPathManager.getIssueFolderPath(repo, ownerCleaned, repoCleaned);
// Ensure folder structure exists
if (repo.useCustomIssueFolder && repo.customIssueFolder && repo.customIssueFolder.trim()) {
// For custom folders, just ensure the custom path exists
await this.fileHelpers.ensureFolderExists(repo.customIssueFolder.trim());
} else {
// For default structure, ensure nested path exists
await this.fileHelpers.ensureFolderExists(repo.issueFolder);
await this.fileHelpers.ensureFolderExists(`${repo.issueFolder}/${ownerCleaned}`);
await this.fileHelpers.ensureFolderExists(`${repo.issueFolder}/${ownerCleaned}/${repoCleaned}`);
}
const file = this.app.vault.getAbstractFileByPath(`${issueFolderPath}/${fileName}`);
const [owner, repoName] = repo.repository.split("/");
// Only fetch comments if they should be included
let comments: any[] = [];
if (repo.includeIssueComments) {
comments = await this.gitHubClient.fetchIssueComments(
owner,
repoName,
issue.number,
);
} else {
this.noticeManager.debug(
`Skipping comments for issue ${issue.number}: repository setting disabled`,
);
}
// Fetch sub-issues and parent issue for template support (only if enabled)
let subIssues: any[] = [];
let parentIssue: any = null;
if (repo.includeSubIssues) {
subIssues = await this.gitHubClient.fetchSubIssues(owner, repoName, issue.number);
parentIssue = await this.gitHubClient.fetchParentIssue(owner, repoName, issue.number);
// Enrich sub-issues with vault paths if they exist
const issueFolder = this.folderPathManager.getIssueFolderPath(repo, owner, repoName);
const noteTemplate = repo.issueNoteTemplate || "Issue - {number}";
subIssues = await this.fileHelpers.enrichSubIssuesWithVaultPaths(
subIssues,
issueFolder,
noteTemplate,
repo.repository,
this.settings.dateFormat,
this.settings.escapeMode
);
}
let content = await this.contentGenerator.createIssueContent(
issue,
repo,
comments,
this.settings,
undefined, // projectData
subIssues,
parentIssue
);
if (file) {
if (file instanceof TFile) {
// Use current repository updateMode setting (not the old value from file properties)
const updateMode = repo.issueUpdateMode;
// Read existing content to check for changes
const existingContent = await this.app.vault.read(file);
// Check if status has changed (e.g., open -> closed)
const statusHasChanged = hasStatusChanged(existingContent, issue.state);
// If status changed, always update regardless of updateMode
// Otherwise, respect the updateMode setting
if (statusHasChanged || updateMode === "update") {
// Check if content needs updating based on updated_at field
if (!statusHasChanged && !shouldUpdateContent(existingContent, issue.updated_at)) {
this.noticeManager.debug(
`Skipped update for issue ${issue.number}: no changes detected (updated_at match)`
);
return;
}
// Extract persist blocks from existing content
const persistBlocks = extractPersistBlocks(existingContent);
// Create the complete new content with updated frontmatter
let updatedContent = await this.contentGenerator.createIssueContent(
issue,
repo,
comments,
this.settings,
undefined, // projectData
subIssues,
parentIssue
);
// Merge persist blocks back into new content
if (persistBlocks.size > 0) {
updatedContent = mergePersistBlocks(updatedContent, existingContent, persistBlocks);
this.noticeManager.debug(
`Restored ${persistBlocks.size} persist block(s) for issue ${issue.number}`
);
}
await this.app.vault.modify(file, updatedContent);
if (statusHasChanged) {
this.noticeManager.debug(`Updated issue ${issue.number} (status changed to ${issue.state})`);
} else {
this.noticeManager.debug(`Updated issue ${issue.number}`);
}
} else if (updateMode === "append") {
const shouldEscapeHashTags = repo.ignoreGlobalSettings ? repo.escapeHashTags : this.settings.escapeHashTags;
content = `---\n### New status: "${
issue.state
}"\n\n# ${escapeBody(
issue.title,
this.settings.escapeMode,
false,
)}\n${
issue.body
? escapeBody(issue.body, this.settings.escapeMode, shouldEscapeHashTags)
: "No description found"
}\n`;
if (comments.length > 0) {
content += this.fileHelpers.formatComments(
comments,
this.settings.escapeMode,
this.settings.dateFormat,
shouldEscapeHashTags,
);
}
const currentFileContent = await this.app.vault.read(file);
const newContent = currentFileContent + "\n\n" + content;
await this.app.vault.modify(file, newContent);
this.noticeManager.debug(
`Appended content to issue ${issue.number}`,
);
} else {
this.noticeManager.debug(
`Skipped update for issue ${issue.number} (mode: ${updateMode})`,
);
}
}
} else {
await this.app.vault.create(`${issueFolderPath}/${fileName}`, content);
this.noticeManager.debug(`Created issue file for ${issue.number}`);
}
}
public async cleanupEmptyIssueFolder(
repo: RepositoryTracking,
issueFolder: string,
ownerCleaned: string,
): Promise<void> {
return this.cleanupManager.cleanupEmptyIssueFolder(repo, issueFolder, ownerCleaned);
}
}