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

Code refactoring and enhancement #5

Open
wants to merge 9 commits into
base: main
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
18 changes: 9 additions & 9 deletions convertFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ const convertFile = (file) => {
hours = hours.toString().padStart(2, "0");
minutes = minutes.toString().padStart(2, "0");

const mdFileName = `${year}_${month}_${day}.md`;

const formatTitle = (title) => {
return title ? `**${title.trim()}**` : "";
};

const formatTextAnnoContent = (text, annotations) => {
let formattedText = text?.replaceAll(/\n(.+)/g, "\n\t- $1");
let formattedText = text?.replaceAll(/\n(.+)/g, "\n- $1")
.replaceAll(/^-\s*•/gm, '\t-')
.replaceAll(/^-\s+-/gm, '\t\t-');
if (!annotations) return formattedText;
let formattedAnnotationsStr = "";

Expand All @@ -44,7 +44,7 @@ const convertFile = (file) => {
const mappedList = list?.map((item) =>
item.isChecked ? `DONE ${item.text}` : `TODO ${item.text}`
);
return mappedList?.join("\n\t- ");
return mappedList?.join("\n- ");
};

const formatAttachments = (attachments) => {
Expand All @@ -57,8 +57,8 @@ const convertFile = (file) => {
};

const formatLabels = (labels) => {
const mappedLabel = labels?.map((label) => `#[[${label.name}]]`);
return mappedLabel?.join(" ");
const mappedLabel = labels?.map((label) => `${label.name}, `);
return mappedLabel;
};

const formattedTitle = formatTitle(file.title);
Expand All @@ -71,12 +71,12 @@ const convertFile = (file) => {
const formattedLabels = formatLabels(file.labels);
const timestamp = `${hours}:${minutes}`;

const content = `\n- ${formattedTitle} (${timestamp}) ${
formattedLabels || ""
}\n\t- ${
const content = `timestamp:: ${day}.${month}.${year} ${timestamp}\ntags:: ${formattedLabels?.join("") ?? ""}from-keep-2023\n- ${
formattedTextAnnoContent || formattedList || ""
} \n\t- ${formattedAttachments}`;

const mdFileName = `${file.title.replaceAll('/', '___')}.md`;

return { mdFileName, content };
};

Expand Down
190 changes: 120 additions & 70 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,93 +1,143 @@
const fs = require("node:fs");
const path = require("node:path");
const readline = require("node:readline");
// const readline = require("node:readline");
const rls = require("readline-sync");
// import psp from "prompt-sync-plus";
// const prompt = psp();
const { stdin: input, stdout: output } = require("node:process");
const convertFile = require("./convertFile.js");
const createOrReturnDirectory = require("./createOrReturnDirectory.js");
const copyAssets = require("./copyAssets.js");

const rl = readline.createInterface({ input, output });
//const rl = readline.createInterface({ input, output });

const FIRST_QUESTION =
" \n\x1b[1m\x1b[33mEnter the location of downloaded and unzipped 'Google Keep' Takeout folder?\x1b[0m \n\x1b[33m e.g. /Users/<your username>/desktop/\x1b[0m\n\n >";
" \n\x1b[1m\x1b[33mEnter the location of downloaded and unzipped 'Google Keep' Takeout folder?\x1b[0m \n\x1b[33m e.g. /Users/<your username>/desktop/\x1b[0m CAUTION: If using Google Keep in other languages, make sure to rename the directory inside Takeout to \'Keep\'!\n\n >.";
const SECOND_QUESTION =
" \n\x1b[1m\x1b[33mEnter location of your 'Journals' folder or press 'ENTER' if you want to create new 'journals' folder in current location\x1b[0m \n\x1b[33m e.g. /Users/<your username>/Documents/<Logseq Graph name>/\x1b[0m\n\n >";
" \n\x1b[1m\x1b[33mEnter location of your 'Notes' folder (CAUTION: The directory should exist!) or press 'ENTER' if you want to create new 'notes' folder in current location\x1b[0m \n\x1b[33m e.g. /Users/<your username>/Documents/<Logseq Graph name>/\x1b[0m\n\n >";

let sourceDirectory;
let destinationDirectory;
let jsonFiles;

const runFirstQuestion = () => {
rl.question(FIRST_QUESTION, (firstAnswer) => {
const askedFolderLocation = firstAnswer.trim().replace(/^['"]|['"]$/g, "");
sourceDirectory = path.normalize(`${askedFolderLocation}/Takeout/Keep/`);

if (
!fs.existsSync(sourceDirectory) ||
!fs.statSync(sourceDirectory).isDirectory()
) {
console.log(
"\n\x1b[1m\x1b[31mTakeout folder not found! Please try again!\x1b[0m"
);
return runFirstQuestion();
}
function checkSourcePath(srcpath) {
const askedFolderLocation = srcpath.trim().replace(/^['"]|['"]$/g, "");
sourceDirectory = path.normalize(`${askedFolderLocation}/Takeout/Keep/`);

if (
!fs.existsSync(sourceDirectory) ||
!fs.statSync(sourceDirectory).isDirectory()
) {
console.log(
"\n\x1b[1m\x1b[31mTakeout folder not found! Please try again!\x1b[0m"
);
return 1;
}
else {
return 0;
}
}

function checkDestPath(destpath) {
const askedDestinationLocation = destpath
.trim()
.replace(/^['"]|['"]$/g, "");
destinationDirectory = path.normalize(askedDestinationLocation);

if (
!fs.existsSync(destinationDirectory) ||
!fs.statSync(destinationDirectory).isDirectory()
) {
console.log(
"\n\x1b[1m\x1b[31mDestination location is not valid! Please try again!\x1b[0m"
);
return 1;
}
else {
return 0;
}
}

function getKeepData() {
try {
const files = fs.readdirSync(sourceDirectory);

jsonFiles = files.filter(
(file) => path.extname(file).toLowerCase() === ".json"
);
} catch (error) {
console.log("Error getting directory info");
}

}

function convertData() {
let processedFilesCount = 0;
for (let file of jsonFiles) {
try {
const files = fs.readdirSync(sourceDirectory);
const fileContent = fs.readFileSync(`${sourceDirectory}/${file}`);
const jsonData = JSON.parse(fileContent);
if (jsonData.isTrashed) continue;
const { mdFileName, content } = convertFile(jsonData);

jsonFiles = files.filter(
(file) => path.extname(file).toLowerCase() === ".json"
const pathToAppend = createOrReturnDirectory(
`${destinationDirectory}/notes/`
);
runSecondQuestion();

fs.appendFileSync(`${pathToAppend}/${mdFileName}`, content);
processedFilesCount++;
} catch (error) {
console.log("Error getting directory info");
}
});
};

const runSecondQuestion = () => {
rl.question(SECOND_QUESTION, (secondAnswer) => {
const askedDestinationLocation = secondAnswer
.trim()
.replace(/^['"]|['"]$/g, "");
destinationDirectory = path.normalize(askedDestinationLocation);

if (
!fs.existsSync(destinationDirectory) ||
!fs.statSync(destinationDirectory).isDirectory()
) {
console.log(
"\n\x1b[1m\x1b[31mDestination location is not valid! Please try again!\x1b[0m"
);
return runSecondQuestion();
console.error(error);
}
}
console.log(
`\n\x1b[92m All notes processed. Total converted notes: ${processedFilesCount}. \n Please look for newly created 'notes' folder in '${
destinationDirectory === "." ? __dirname : destinationDirectory
}' directory. \x1b[0m\n`
);
copyAssets(sourceDirectory, destinationDirectory);
}

let processedFilesCount = 0;
for (let file of jsonFiles) {
try {
const fileContent = fs.readFileSync(`${sourceDirectory}/${file}`);
const jsonData = JSON.parse(fileContent);
if (jsonData.isTrashed) continue;
const { mdFileName, content } = convertFile(jsonData);

const pathToAppend = createOrReturnDirectory(
`${destinationDirectory}/journals/`
);

fs.appendFileSync(`${pathToAppend}/${mdFileName}`, content);
processedFilesCount++;
} catch (error) {
console.error(error);
}
}
console.log(
`\n\x1b[92m All notes processed. Total converted notes: ${processedFilesCount}. \n Please look for newly created 'journals' folder in '${
destinationDirectory === "." ? __dirname : destinationDirectory
}' directory. \x1b[0m\n`
);
copyAssets(sourceDirectory, destinationDirectory);
rl.close();
});
};
function main() {
console.log(`Starting! Arguments: ${process.argv[2]}, ${process.argv[3]}`)
if (typeof process.argv[2] !== 'undefined') {
sourceDirectory = process.argv[2];
}
else {
/* rl.question(FIRST_QUESTION, (firstAnswer) => {
sourceDirectory = firstAnswer;
rl.close();
}); */

sourceDirectory = rls.question(FIRST_QUESTION);

}

if (checkSourcePath(sourceDirectory) == 0) {
getKeepData();
}
else {
return;
}

if (typeof process.argv[3] !== 'undefined') {
destinationDirectory = process.argv[3];
}
else {
/* rl.question(SECOND_QUESTION, (secondAnswer) => {
destinationDirectory = secondAnswer;
rl.close();
}); */
destinationDirectory = rls.question(SECOND_QUESTION);
}

if (checkDestPath(destinationDirectory) == 0) {
convertData();
}
else {
return;
}

runFirstQuestion();
}

main();
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,8 @@
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
"license": "ISC",
"dependencies": {
"readline-sync": "^1.4.10"
}
}