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

node:fsからnode:fs/promisesを使うように修正 #4

Merged
merged 2 commits into from
Oct 2, 2024
Merged
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
8 changes: 4 additions & 4 deletions src/commands/add.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { readFileSync } from "node:fs";
import { readFile } from "node:fs/promises";

import { coloredLog } from "../functions/colored-log.js";
import { BlobObject } from "../models/blob-object.js";

export const add = (options: Array<string>): void => {
export const add = async (options: Array<string>): Promise<void> => {
const filePath = options[0];

//引数にファイルパスが含まれていなかった場合の処理
Expand All @@ -16,8 +16,8 @@ export const add = (options: Array<string>): void => {
return;
}

const content = readFileSync(filePath);
const content = await readFile(filePath);

const blobObject = new BlobObject(content);
blobObject.dumpBlobObject();
await blobObject.dumpBlobObject();
};
27 changes: 15 additions & 12 deletions src/commands/log.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,40 @@
import { existsSync, readFileSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { join } from "path";

import { GIT_DIR } from "../constants.js";
import { coloredLog } from "../functions/colored-log.js";
import { exists } from "../functions/exists.js";
import { Commit, CommitFieldType } from "../models/commit.js";

const extractHeadHash = (): string | undefined => {
const extractHeadHash = async (): Promise<string | undefined> => {
const headPath = join(GIT_DIR, "HEAD");

if (!existsSync(headPath)) {
if (!(await exists(headPath))) {
return;
}

const headText = readFileSync(headPath).toString("utf-8");
const headText = await readFile(headPath).then((head) =>
head.toString("utf-8"),
);

const refPrefix = "ref: ";
//ブランチ名かコミットハッシュのどちらをHEADに持つかを識別して出し分ける
if (headText.startsWith(refPrefix)) {
return readFileSync(
return await readFile(
join(GIT_DIR, headText.slice(refPrefix.length)).trim(),
"utf-8",
).trim();
).then((path) => path.trim());
} else {
return headText.trim();
}
};

const getCommitHistory = (
const getCommitHistory = async (
hash: string,
history: Array<CommitFieldType> = [],
): Array<CommitFieldType> => {
): Promise<Array<CommitFieldType>> => {
const commit = new Commit();
commit.setCommit(hash);
await commit.setCommit(hash);
const commitData = commit.getCommit();

const currentHistory = [...history, commitData];
Expand All @@ -57,15 +60,15 @@ export const displayCommitHistory = (
});
};

export const log = (_options?: Array<string>): void => {
const headHash = extractHeadHash();
export const log = async (_options?: Array<string>): Promise<void> => {
const headHash = await extractHeadHash();

if (!headHash) {
console.log("there is no commit.");
return;
}

const commitHistory = getCommitHistory(headHash);
const commitHistory = await getCommitHistory(headHash);

displayCommitHistory(commitHistory);
};
9 changes: 9 additions & 0 deletions src/functions/exists.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { access } from "node:fs/promises";

// https://github.com/privatenumber/fs.promises.exists/blob/develop/src/index.ts
export const exists = async (filePath: string): Promise<boolean> => {
return await access(filePath).then(
() => true,
() => false,
);
};
Copy link
Contributor Author

@hyphen-o hyphen-o Oct 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

memo
node:fs/promisesにはファイルorディレクトリが存在するかを確認するためのexistsSyncにあたる関数がない.
third-partyライブラリも存在したが,自前でも実装できる内容だったため汎用関数として実装することにする.

8 changes: 0 additions & 8 deletions src/functions/read-file.ts

This file was deleted.

8 changes: 8 additions & 0 deletions src/functions/read-git-object.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { readFile } from "node:fs/promises";
import { inflateSync } from "node:zlib";

export const readGitObject = async (path: string): Promise<string> => {
const file = Uint8Array.from(await readFile(path));

return inflateSync(file).toString();
};
11 changes: 6 additions & 5 deletions src/models/blob-object.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { mkdir, writeFile } from "node:fs/promises";
import { deflateSync } from "node:zlib";

import { exists } from "../functions/exists.js";
import { generateObjectPath } from "../functions/generate-object-path.js";

export class BlobObject {
constructor(private readonly content: Buffer) {}

public dumpBlobObject = (): void => {
public dumpBlobObject = async (): Promise<void> => {
const header = Buffer.from(`blob ${this.content.length.toString()}\x00`);
const store = Buffer.concat([
Uint8Array.from(header),
Expand All @@ -22,10 +23,10 @@ export class BlobObject {
const { dirPath, filePath } = generateObjectPath(hash);
const compressedBlobObject = deflateSync(Uint8Array.from(store));

if (existsSync(filePath)) return;
if (await exists(filePath)) return;

if (!existsSync(dirPath)) mkdirSync(dirPath);
if (!(await exists(dirPath))) await mkdir(dirPath);

writeFileSync(filePath, Uint8Array.from(compressedBlobObject));
await writeFile(filePath, Uint8Array.from(compressedBlobObject));
};
}
10 changes: 5 additions & 5 deletions src/models/commit.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { join } from "node:path";

import { GIT_OBJECTS } from "../constants.js";
import { readFile } from "../functions/read-file.js";
import { readGitObject } from "../functions/read-git-object.js";

export interface CommitFieldType {
tree: string;
Expand All @@ -28,8 +28,8 @@ export class Commit {
this.hash = "";
}

public setCommit = (hash: string): void => {
const content = this.getCommitContent(hash);
public setCommit = async (hash: string): Promise<void> => {
const content = await this.getCommitContent(hash);

this.parseCommit(hash, content);
};
Expand All @@ -44,13 +44,13 @@ export class Commit {
};
};

private getCommitContent = (hash: string): string => {
private getCommitContent = async (hash: string): Promise<string> => {
const dirName = hash.slice(0, 2);
const fileName = hash.slice(2);

const path = join(GIT_OBJECTS, dirName, fileName);

return readFile(path);
return await readGitObject(path);
};

private parseCommit = (hash: string, content: string): void => {
Expand Down
2 changes: 1 addition & 1 deletion src/mygit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const mygit = async (argv: Array<string>): Promise<void> => {
if (runCommand) {
const options = argv.slice(3);

runCommand(options);
await runCommand(options);
} else {
console.log(`mygit: '${command}' is not a valid mygit command.\n`);
validCommand.help();
Expand Down
Loading