Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· OpenAIAi2 WildChat-4.8M (AI2)

Fix the TODO comment: [code]

  1. User

    Fix the TODO comment:

    // file-versioning-plugin.ts
    import {
      Notice,
      Plugin,
      PluginSettingTab,
      Setting,
      TFile,
      ItemView,
      WorkspaceLeaf,
      MarkdownView,
      ViewRegistry,
    } from "obsidian";
    
    interface FileVersioningSettings {
      maxVersions: number;
      versionsLocation: string;
      minDuration: number;
    }
    
    const DEFAULT_SETTINGS: FileVersioningSettings = {
      maxVersions: 5,
      versionsLocation: ".versions",
      minDuration: 1800, // 30 minutes
    };
    
    export default class FileVersioningPlugin extends Plugin {
      settings: FileVersioningSettings;
    
      async onload() {
        await this.loadSettings();
    
        this.addSettingTab(new FileVersioningSettingTab(this.app, this));
    
        this.registerEvent(
          this.app.vault.on("modify", async (file: TFile) => {
            const durationSinceLastSave = Date.now() - file.stat.mtime;
    
            if (durationSinceLastSave >= this.settings.minDuration) {
              await this.createVersion(file);
            }
          })
        );
    		
        this.addCommand({
          id: "view-file-versions",
          name: "View File Versions",
          callback: async () => {
            const file = this.app.workspace.getActiveFile();
            if (!file) {
              new Notice("No active file to view versions for.");
              return;
            }
            await this.showVersions(file);
          },
        });
    
    		this.registerView("file-versions-view", (leaf: WorkspaceLeaf) =>
          new FileVersionsView(leaf, this)
        );
    		
      }
    	
      async createVersion(file: TFile) {
        const data = await this.app.vault.read(file);
        const versionsFolder = this.app.vault.getAbstractFileByPath(this.settings.versionsLocation);
    		
        if (!versionsFolder) {
          await this.app.vault.createFolder(this.settings.versionsLocation);
        }
    		
        const uniqueTimestamp = Date.now().toString();
    
        await this.app.vault.create(
          this.settings.versionsLocation + '/' + file.basename + '-' + uniqueTimestamp + '.md',
          data
        );
    
        if (this.settings.maxVersions > 0) {
          await this.removeOldVersions(file, this.settings.maxVersions);
        }
      }
    
      async removeOldVersions(file: TFile, maxVersions: number) {
        const versions = await this.getVersions(file);
        const numVersions = versions.length;
    
        if (numVersions > maxVersions) {
          await this.app.vault.delete(versions[0]);
        }
      }
    
    	//TODO: "file" undefined, getVersions fails to get versions
      async getVersions(file: TFile) {
    		
        const folder = this.settings.versionsLocation
        const versions: TFile[] = [];
    
        if (folder) {
          this.app.vault.getFiles().forEach((version) => {
    				if (version instanceof TFile && version.parent === folder && version.basename.startsWith(file.basename)) {
    					versions.push(version);
            }
          });
    
          versions.sort((a: TFile, b: TFile) => {
            const timestampA = parseInt(
              a.basename.split("-").slice(-1).toString()
            );
            const timestampB = parseInt(
              b.basename.split("-").slice(-1).toString()
            );
    
            return timestampA - timestampB;
          });
        }
    
        return versions;
      }
    	
      async showVersions(file: TFile) {
    		const existingLeaf = this.app.workspace.getLeavesOfType(
    			"file-versions-view"
    		)?.[0];
    
    		const leaf =
    			existingLeaf ||
    			this.app.workspace.splitActiveLeaf("horizontal");
    
    		leaf
    			.setViewState({ type: "file-versions-view", file: file.path })
    			.then((fileVersionsView) => {
            // Check if the view has been created before
            if (!fileVersionsView) {
    					this.app.workspace.setActiveLeaf(existingLeaf);
              return;
            }
    
            // Focus the leaf once it has been created.
    				this.app.workspace.setActiveLeaf(leaf);
          })
      }
    
      async loadSettings() {
        this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
      }
    
      async saveSettings() {
        await this.saveData(this.settings);
      }
    }
    
    class FileVersionsView extends ItemView {
      plugin: FileVersioningPlugin;
      file: TFile;
    
      constructor(leaf: WorkspaceLeaf, plugin: FileVersioningPlugin) {
        super(leaf, plugin);
        this.plugin = plugin;
      }
    
      getViewType(): string {
        return "file-versions-view";
      }
    
      getDisplayText(): string {
        return "File Versions";
      }
    
      getIcon(): string {
        return "clock";
      }
    
    	async onOpen() {
        const state = this.leaf.getViewState();
        this.file = this.app.vault.getAbstractFileByPath(state.file) as TFile;
        await this.reloadData();
      }
    
      async reloadData() {
        const container = createDiv({ cls: "file-versions-container" });
        const versions = await this.plugin.getVersions(this.file);
        versions.reverse();
    
        versions.forEach((version) => {
          const versionItem = container.createEl("div", {
            cls: "file-version-item",
          });
          versionItem.createEl("span", {
            cls: "file-version-label",
            text: version.basename.replace(this.file.basename, "").replace('.md', ''),
          });
    
          versionItem.createEl("a", {
            cls: "file-version-restore",
            text: "Restore",
            oncontextmenu: async (e: MouseEvent) => {
              e.preventDefault();
              await this.plugin.createVersion(this.file);
              await this.app.vault.modify(this.file, await this.app.vault.read(version));
              this.leaf.setEphemeralState({});
            },
          });
        });
    
        this.contentEl.empty();
        this.contentEl.appendChild(container);
      }
    }
    
    class FileVersioningSettingTab extends PluginSettingTab {
      plugin: FileVersioningPlugin;
    
      constructor(app: App, plugin: FileVersioningPlugin) {
        super(app, plugin);
        this.plugin = plugin;
      }
    
      display(): void {
        let { containerEl } = this;
    
        containerEl.empty();
    
        containerEl.createEl("h2", { text: "File Versioning Settings" });
    
        new Setting(containerEl)
          .setName("Maximum Versions")
          .setDesc("Maximum number of versions to keep. Set to 0 for no limit.")
          .addText((text) =>
            text
              .setPlaceholder("Enter maximum versions")
              .setValue(this.plugin.settings.maxVersions.toString())
              .onChange(async (value) => {
                this.plugin.settings.maxVersions = parseInt(value);
                await this.plugin.saveSettings();
              })
          );
    
        new Setting(containerEl)
          .setName("Versions Location")
          .setDesc("Specify the folder where versions should be stored.")
          .addText((text) =>
            text
              .setPlaceholder("Enter versions location")
              .setValue(this.plugin.settings.versionsLocation)
              .onChange(async (value) => {
                this.plugin.settings.versionsLocation = value;
                await this.plugin.saveSettings();
              })
          );
    
        new Setting(containerEl)
          .setName("Minimum Duration")
          .setDesc("Minimum time in seconds after which a new version may be created.")
          .addText((text) =>
            text
              .setPlaceholder("Enter minimum duration")
              .setValue(this.plugin.settings.minDuration.toString())
              .onChange(async (value) => {
                this.plugin.settings.minDuration = parseInt(value);
                await this.plugin.saveSettings();
              })
          );
      }
    }
    
  2. Assistant
    // file-versioning-plugin.ts
    import {
      Notice,
      Plugin,
      PluginSettingTab,
      Setting,
      TFile,
      ItemView,
      WorkspaceLeaf,
      MarkdownView,
      ViewRegistry,
    } from "obsidian";
    
    interface FileVersioningSettings {
      maxVersions: number;
      versionsLocation: string;
      minDuration: number;
    }
    
    const DEFAULT_SETTINGS: FileVersioningSettings = {
      maxVersions: 5,
      versionsLocation: ".versions",
      minDuration: 1800, // 30 minutes
    };
    
    export default class FileVersioningPlugin extends Plugin {
      settings: FileVersioningSettings;
    
      async onload() {
        await this.loadSettings();
    
        this.addSettingTab(new FileVersioningSettingTab(this.app, this));
    
        this.registerEvent(
          this.app.vault.on("modify", async (file: TFile) => {
            const durationSinceLastSave = Date.now() - file.stat.mtime;
    
            if (durationSinceLastSave >= this.settings.minDuration) {
              await this.createVersion(file);
            }
          })
        );
        
        this.addCommand({
          id: "view-file-versions",
          name: "View File Versions",
          callback: async () => {
            const file = this.app.workspace.getActiveFile();
            if (!file) {
              new Notice("No active file to view versions for.");
              return;
            }
            await this.showVersions(file);
          },
        });
    
        this.registerView("file-versions-view", (leaf: WorkspaceLeaf) =>
          new FileVersionsView(leaf, this)
        );
        
      }
      
      async createVersion(file: TFile) {
        const data = await this.app.vault.read(file);
        const versionsFolder = this.app.vault.getAbstractFileByPath(this.settings.versionsLocation);
        
        if (!versionsFolder) {
          await this.app.vault.createFolder(this.settings.versionsLocation);
        }
        
        const uniqueTimestamp = Date.now().toString();
    
        await this.app.vault.create(
          this.settings.versionsLocation + '/' + file.basename + '-' + uniqueTimestamp + '.md',
          data
        );
    
        if (this.settings.maxVersions > 0) {
          await this.removeOldVersions(file, this.settings.maxVersions);
        }
      }
    
      async removeOldVersions(file: TFile, maxVersions: number) {
        const versions = await this.getVersions(file);
        const numVersions = versions.length;
    
        if (numVersions > maxVersions) {
          await this.app.vault.delete(versions[0]);
        }
      }
    
      async getVersions(file: TFile) {
        
        const folder = this.settings.versionsLocation
        const versions: TFile[] = [];
    
        if (folder) {
          this.app.vault.getFiles().forEach((version) => {
            if (version instanceof TFile && version.parent.path === folder && version.basename.startsWith(file.basename)) {
              versions.push(version);
            }
          });
    
          versions.sort((a: TFile, b: TFile) => {
            const timestampA = parseInt(
              a.basename.split("-").slice(-1).toString()
            );
            const timestampB = parseInt(
              b.basename.split("-").slice(-1).toString()
            );
    
            return timestampA - timestampB;
          });
        }
    
        return versions;
      }
      
      async showVersions(file: TFile) {
        const existingLeaf = this.app.workspace.getLeavesOfType(
          "file-versions-view"
        )?.[0];
    
        const leaf =
          existingLeaf ||
          this.app.workspace.splitActiveLeaf("horizontal");
    
        leaf
          .setViewState({ type: "file-versions-view", file: file.path })
          .then((fileVersionsView) => {
            // Check if the view has been created before
            if (!fileVersionsView) {
              this.app.workspace.setActiveLeaf(existingLeaf);
              return;
            }
    
            // Focus the leaf once it has been created.
            this.app.workspace.setActiveLeaf(leaf);
          })
      }
    
      async loadSettings() {
        this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
      }
    
      async saveSettings() {
        await this.saveData(this.settings);
      }
    }
    
    class FileVersionsView extends ItemView {
      plugin: FileVersioningPlugin;
      file: TFile;
    
      constructor(leaf: WorkspaceLeaf, plugin: FileVersioningPlugin) {
        super(leaf, plugin);
        this.plugin = plugin;
      }
    
      getViewType(): string {
        return "file-versions-view";
      }
    
      getDisplayText(): string {
        return "File Versions";
      }
    
      getIcon(): string {
        return "clock";
      }
    
      async onOpen() {
        const state = this.leaf.getViewState();
        this.file = this.app.vault.getAbstractFileByPath(state.file) as TFile;
        await this.reloadData();
      }
    
      async reloadData() {
        const container = createDiv({ cls: "file-versions-container" });
        const versions = await this.plugin.getVersions(this.file);
        versions.reverse();
    
        versions.forEach((version) => {
          const versionItem = container.createEl("div", {
            cls: "file-version-item",
          });
          versionItem.createEl("span", {
            cls: "file-version-label",
            text: version.basename.replace(this.file.basename, "").replace('.md', ''),
          });
    
          versionItem.createEl("a", {
            cls: "file-version-restore",
            text: "Restore",
            oncontextmenu: async (e: MouseEvent) => {
              e.preventDefault();
              await this.plugin.createVersion(this.file);
              await this.app.vault.modify(this.file, await this.app.vault.read(version));
              this.leaf.setEphemeralState({});
            },
          });
        });
    
        this.contentEl.empty();
        this.contentEl.appendChild(container);
      }
    }
    
    class FileVersioningSettingTab extends PluginSettingTab {
      plugin: FileVersioningPlugin;
    
      constructor(app: App, plugin: FileVersioningPlugin) {
        super(app, plugin);
        this.plugin = plugin;
      }
    
      display(): void {
        let { containerEl } = this;
    
        containerEl.empty();
    
        containerEl.createEl("h2", { text: "File Versioning Settings" });
    
        new Setting(containerEl)
          .setName("Maximum Versions")
          .setDesc("Maximum number of versions to keep. Set to 0 for no limit.")
          .addText((text) =>
            text
              .setPlaceholder("Enter maximum versions")
              .setValue(this.plugin.settings.maxVersions.toString())
              .onChange(async (value) => {
                this.plugin.settings.maxVersions = parseInt(value);
                await this.plugin.saveSettings();
              })
          );
    
        new Setting(containerEl)
          .setName("Versions Location")
          .setDesc("Specify the folder where versions should be stored.")
          .addText((text) =>
            text
              .setPlaceholder("Enter versions location")
              .setValue(this.plugin.settings.versionsLocation)
              .onChange(async (value) => {
                this.plugin.settings.versionsLocation = value;
                await this.plugin.saveSettings();
              })
          );
    
        new Setting(containerEl)
          .setName("Minimum Duration")
          .setDesc("Minimum time in seconds after which a new version may be created.")
          .addText((text) =>
            text
              .setPlaceholder("Enter minimum duration")
              .setValue(this.plugin.settings.minDuration.toString())
              .onChange(async (value) => {
                this.plugin.settings.minDuration = parseInt(value);
                await this.plugin.saveSettings();
              })
          );
      }
    }
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.