bramses / chatgpt-md

A (nearly) seamless integration of ChatGPT into Obsidian.
MIT License
824 stars 61 forks source link

Detecting Templates Recursively in a Folder #72

Open Ding-Fan opened 1 year ago

Ding-Fan commented 1 year ago

At this function

https://github.com/bramses/chatgpt-md/blob/1cd9234a3f398d4a162042db388b42c94241471f/main.ts#L919-L933 It could recurrsively call it self according to folder or file.

https://marcus.se.net/obsidian-plugin-docs/vault#is-it-a-file-or-folder

const folderOrFile = this.app.vault.getAbstractFileByPath("folderOrFile");  

if (folderOrFile instanceof TFile) {  
console.log("It's a file!");  
// add to TFile[]
} else if (folderOrFile instanceof TFolder) {  
console.log("It's a folder!");  
// do recurrsion
}

Example from GPT

const isTemplate = (filePath: string) => {
  // check if filePath is a valid template
  ...
};

// Create a utility function for recursive search
const detectTemplatesInFolder = async (folderPath: string) => {
  const files = await this.app.vault.getFiles();

  let templateFiles = [];

  for (let i=0; i<files.length; i++) {
    const file = files[i];

    if (!file.path.startsWith(folderPath)) { // ignore unrelated files/folders 
      continue;
    }

    if (file instanceof TFile && isTemplate(file.path)) { // found a template file
      templateFiles.push(file);

    } else if (file instanceof TFolder) { // found a sub-folder, do recursion
      const subfolderTemplates = await detectTemplatesInFolder(file.path);

      if(subfolderTemplates.length > 0 ) {
        templateFiles.push(...subfolderTemplates);
      }
    }
  }

 return templateFiles;
};