Skip to content

Commit

Permalink
Sort cell metadata to avoid unnecessary scm diffs
Browse files Browse the repository at this point in the history
  • Loading branch information
DonJayamanne committed Mar 19, 2024
1 parent d8200a8 commit 396a0a8
Showing 1 changed file with 36 additions and 3 deletions.
39 changes: 36 additions & 3 deletions src/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,50 @@ export async function updateCellTags(cell: vscode.NotebookCell, tags: string[])
const metadata = JSON.parse(JSON.stringify(cell.metadata));
if (useCustomMetadata()) {
metadata.custom = metadata.custom || {};
metadata.custom.tags = tags;
metadata.custom.metadata = metadata.custom.metadata || {};
metadata.custom.metadata.tags = tags;
if (tags.length === 0) {
delete metadata.custom.metadata.tags;
}
} else {
metadata.metadata = metadata.metadata || {};
metadata.metadata.tags = tags;
if (tags.length === 0) {
delete metadata.metadata.tags;
}
}
const edit = new vscode.WorkspaceEdit();
const nbEdit = vscode.NotebookEdit.updateCellMetadata(cell.index, metadata);
const nbEdit = vscode.NotebookEdit.updateCellMetadata(cell.index, sortObjectPropertiesRecursively(metadata));
edit.set(cell.notebook.uri, [nbEdit]);
await vscode.workspace.applyEdit(edit);
}

function useCustomMetadata() {
return !vscode.workspace.getConfiguration('jupyter').get<boolean>('experimental.dropCustomMetadata', false);
if (vscode.extensions.getExtension('vscode.ipynb')?.exports.dropCustomMetadata) {
return false;
}
return true;
}


/**
* Sort the JSON to minimize unnecessary SCM changes.
* Jupyter notbeooks/labs sorts the JSON keys in alphabetical order.
* https://github.com/microsoft/vscode/issues/208137
*/
function sortObjectPropertiesRecursively(obj: any): any {
if (Array.isArray(obj)) {
return obj.map(sortObjectPropertiesRecursively);
}
if (obj !== undefined && obj !== null && typeof obj === 'object' && Object.keys(obj).length > 0) {
return (
Object.keys(obj)
.sort()
.reduce<Record<string, any>>((sortedObj, prop) => {
sortedObj[prop] = sortObjectPropertiesRecursively(obj[prop]);
return sortedObj;
}, {}) as any
);
}
return obj;
}

0 comments on commit 396a0a8

Please sign in to comment.