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

Add template variable {{dirPath}} #85

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
50 changes: 34 additions & 16 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import {
App,
HeadingCache,
ListedFiles,
MarkdownView,
Modal,
Notice,
Expand All @@ -33,6 +34,7 @@ import {
NameObj,
path,
sanitizer,
getDirectoryPath,
} from './utils';

interface PluginSettings {
Expand Down Expand Up @@ -157,9 +159,16 @@ export default class PasteImageRenamePlugin extends Plugin {
const linkText = this.app.fileManager.generateMarkdownLink(file, sourcePath)

// file system operation: rename the file
const newPath = path.join(file.parent.path, newName)
// const newPath = path.join(file.parent.path, newName)
try {
await this.app.fileManager.renameFile(file, newPath)
// get directory part of new path
const newPathDirectory = path.directory(newName)
// check if directory exists
const newPathDirectoryExists = await this.app.vault.adapter.exists(newPathDirectory)
// create directory
if (!newPathDirectoryExists) await this.app.vault.createFolder(newPathDirectory)
// execute rename
await this.app.fileManager.renameFile(file, newName)
} catch (err) {
new Notice(`Failed to rename ${newName}: ${err}`)
throw err
Expand Down Expand Up @@ -276,12 +285,15 @@ export default class PasteImageRenamePlugin extends Plugin {
console.warn('could not get file cache from active file', activeFile.name)
}

const dirPath = getDirectoryPath(activeFile.parent)

const stem = renderTemplate(
this.settings.imageNamePattern,
{
imageNameKey,
fileName: activeFile.basename,
dirName: activeFile.parent.name,
dirPath,
firstHeading,
},
frontmatter)
Expand All @@ -296,14 +308,17 @@ export default class PasteImageRenamePlugin extends Plugin {

// newName: foo.ext
async deduplicateNewName(newName: string, file: TFile): Promise<NameObj> {
// confirmed new file path
const newFilePath = path.join(getDirectoryPath(file.parent), newName);
// list files in dir
const dir = file.parent.path
const listed = await this.app.vault.adapter.list(dir)
const dir = path.directory(newFilePath) // file.parent.path
const dirExists = await this.app.vault.adapter.exists(dir)
const listed: false | ListedFiles = dirExists && await this.app.vault.adapter.list(dir)
debugLog('sibling files', listed)

// parse newName
const newNameExt = path.extension(newName),
newNameStem = newName.slice(0, newName.length - newNameExt.length - 1),
newNameStem = newFilePath.slice(0, newFilePath.length - newNameExt.length - 1),
newNameStemEscaped = escapeRegExp(newNameStem),
delimiter = this.settings.dupNumberDelimiter,
delimiterEscaped = escapeRegExp(delimiter)
Expand All @@ -320,18 +335,20 @@ export default class PasteImageRenamePlugin extends Plugin {

const dupNameNumbers: number[] = []
let isNewNameExist = false
for (let sibling of listed.files) {
sibling = path.basename(sibling)
if (sibling == newName) {
isNewNameExist = true
continue
}
if (listed) {
for (let sibling of listed.files) {
let siblingBasename = path.basename(sibling)
if (siblingBasename == newName) {
isNewNameExist = true
continue
}

// match dupNames
const m = dupNameRegex.exec(sibling)
if (!m) continue
// parse int for m.groups.number
dupNameNumbers.push(parseInt(m.groups.number))
// match dupNames
const m = dupNameRegex.exec(sibling)
if (!m) continue
// parse int for m.groups.number
dupNameNumbers.push(parseInt(m.groups.number))
}
}

if (isNewNameExist || this.settings.dupNumberAlways) {
Expand Down Expand Up @@ -559,6 +576,7 @@ The pattern indicates how the new name should be generated.
Available variables:
- {{fileName}}: name of the active file, without ".md" extension.
- {{dirName}}: name of the directory which contains the document (the root directory of vault results in an empty variable).
- {{dirPath}}: full path of the directory which contains the document
- {{imageNameKey}}: this variable is read from the markdown file's frontmatter, from the same key "imageNameKey".
- {{DATE:$FORMAT}}: use "$FORMAT" to format the current date, "$FORMAT" must be a Moment.js format string, e.g. {{DATE:YYYY-MM-DD}}.

Expand Down
2 changes: 2 additions & 0 deletions src/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ interface TemplateData {
imageNameKey: string
fileName: string
dirName: string
dirPath: string
firstHeading: string
}

Expand All @@ -38,6 +39,7 @@ export const renderTemplate = (tmpl: string, data: TemplateData, frontmatter?: F
.replace(/{{imageNameKey}}/gm, data.imageNameKey)
.replace(/{{fileName}}/gm, data.fileName)
.replace(/{{dirName}}/gm, data.dirName)
.replace(/{{dirPath}}/gm, data.dirPath)
.replace(/{{firstHeading}}/gm, data.firstHeading)
return text
}
22 changes: 22 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
App,
Vault,
TFolder,
} from 'obsidian';

export const DEBUG = !(process.env.BUILD_ENV === 'production')
Expand Down Expand Up @@ -64,13 +65,34 @@ export const path = {
return sp[sp.length - 1]
},

/**
* get the parent directory part of a file or directory
* @param fullpath - full path of a file or directory
* @returns the directory part of a path,
* @example
*/
directory(fullpath: string): string {
const sp = fullpath.split('/')
return sp.slice(0, sp.length - 1).join('/')
},

// return extension without dot, e.g. 'jpg'
extension(fullpath: string): string {
const positions = [...fullpath.matchAll(new RegExp('\\.', 'gi'))].map(a => a.index)
return fullpath.slice(positions[positions.length - 1] + 1)
},
}

/**
* get the full path of given folder object
* @param tFolder - a folder object
* @returns the full path of directory
*/
export const getDirectoryPath = (tFolder: TFolder): string => {
if (tFolder.parent.name === '') return tFolder.name
return `${getDirectoryPath(tFolder.parent)}/${tFolder.name}`
}

const filenameNotAllowedChars = /[^\p{L}0-9~`!@$&*()\-_=+{};'",<.>? ]/ug

export const sanitizer = {
Expand Down