Skip to content

Check if local files are up to date #37

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

Merged
merged 3 commits into from
Jul 26, 2023
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
14 changes: 14 additions & 0 deletions src/client/components/ArticleInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ interface Props {
errorMessages: string[];
qiitaItemUrl: string | null;
slide: boolean;
isOlderThanRemote: boolean;
}

export const ArticleInfo = ({
Expand All @@ -28,6 +29,7 @@ export const ArticleInfo = ({
errorMessages,
qiitaItemUrl,
slide,
isOlderThanRemote,
}: Props) => {
const [isOpen, setIsOpen] = useState(
localStorage.getItem("openInfoState") === "true" ? true : false
Expand Down Expand Up @@ -88,6 +90,18 @@ export const ArticleInfo = ({
</InfoItem>
<InfoItem title="スライドモード">{slide ? "ON" : "OFF"}</InfoItem>
</details>
{isOlderThanRemote && (
<div css={errorContentsStyle}>
<p css={errorStyle}>
<MaterialSymbol fill={true} css={exclamationIconStyle}>
error
</MaterialSymbol>
{
"この記事ファイルの内容は、Qiita上の記事より古い可能性があります。"
}
</p>
</div>
)}
{errorMessages.length > 0 && (
<div css={errorContentsStyle}>
{errorMessages.map((errorMessage, index) => (
Expand Down
12 changes: 12 additions & 0 deletions src/client/components/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { Snackbar, Message as SnackbarMessage } from "./Snackbar";
interface Props {
id?: string;
isItemPublishable: boolean;
isOlderThanRemote: boolean;
itemPath: string;
basename: string | null;
handleMobileOpen: () => void;
Expand All @@ -21,6 +22,7 @@ interface Props {
export const Header = ({
id,
isItemPublishable,
isOlderThanRemote,
itemPath,
basename,
handleMobileOpen,
Expand All @@ -32,6 +34,16 @@ export const Header = ({
const mobileSize = currentWidth <= breakpoint.S;

const handlePublish = () => {
if (isOlderThanRemote) {
if (
!window.confirm(
"この記事はQiita上の記事より古い可能性があります。上書きしますか?"
)
) {
return;
}
}

const params = {
method: "POST",
headers: {
Expand Down
2 changes: 2 additions & 0 deletions src/client/pages/items/show.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export const ItemsShow = () => {
isItemPublishable={
item.modified && item.error_messages.length === 0
}
isOlderThanRemote={item.is_older_than_remote}
itemPath={item.item_path}
id={id}
basename={basename}
Expand All @@ -98,6 +99,7 @@ export const ItemsShow = () => {
errorMessages={item.error_messages}
qiitaItemUrl={item.qiita_item_url}
slide={item.slide}
isOlderThanRemote={item.is_older_than_remote}
/>
<div css={articleWrapStyle}>
<Article
Expand Down
13 changes: 13 additions & 0 deletions src/commands/publish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ export const publish = async (argv: string[]) => {
const args = arg(
{
"--all": Boolean,
"--force": Boolean,
"-f": "--force",
},
{ argv }
);
Expand Down Expand Up @@ -40,6 +42,7 @@ export const publish = async (argv: string[]) => {
}

// Validate
const enableForcePublish = args["--force"];
const invalidItemMessages = targetItems.reduce((acc, item) => {
const frontmatterErrors = checkFrontmatterType(item);
if (frontmatterErrors.length > 0)
Expand All @@ -49,6 +52,16 @@ export const publish = async (argv: string[]) => {
if (validationErrors.length > 0)
return [...acc, { name: item.name, errors: validationErrors }];

if (!enableForcePublish && item.isOlderThanRemote) {
return [
...acc,
{
name: item.name,
errors: ["内容がQiita上の記事より古い可能性があります"],
},
];
}

return acc;
}, [] as { name: string; errors: string[] }[]);
if (invalidItemMessages.length > 0) {
Expand Down
61 changes: 61 additions & 0 deletions src/commands/pull.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { getFileSystemRepo } from "../lib/get-file-system-repo";
import { getQiitaApiInstance } from "../lib/get-qiita-api-instance";
import { syncArticlesFromQiita } from "../lib/sync-articles-from-qiita";
import { pull } from "./pull";

jest.mock("../lib/get-qiita-api-instance");
jest.mock("../lib/get-file-system-repo");
jest.mock("../lib/sync-articles-from-qiita");
const mockGetQiitaApiInstance = jest.mocked(getQiitaApiInstance);
const mockGetFileSystemRepo = jest.mocked(getFileSystemRepo);
const mockSyncArticlesFromQiita = jest.mocked(syncArticlesFromQiita);

describe("pull", () => {
const qiitaApi = {} as ReturnType<typeof getQiitaApiInstance>;
const fileSystemRepo = {} as ReturnType<typeof getFileSystemRepo>;

beforeEach(() => {
mockGetQiitaApiInstance.mockReset();
mockGetFileSystemRepo.mockReset();
mockSyncArticlesFromQiita.mockReset();

mockGetQiitaApiInstance.mockReturnValue(qiitaApi);
mockGetFileSystemRepo.mockReturnValue(fileSystemRepo);
mockSyncArticlesFromQiita.mockImplementation();
jest.spyOn(console, "log").mockImplementation();
});

it("pulls articles", async () => {
await pull([]);

expect(mockSyncArticlesFromQiita).toBeCalledWith({
fileSystemRepo,
qiitaApi,
forceUpdate: undefined,
});
expect(mockSyncArticlesFromQiita).toBeCalledTimes(1);
});

describe('with "--force" option', () => {
it("pulls articles with forceUpdate", async () => {
await pull(["--force"]);

expect(mockSyncArticlesFromQiita).toBeCalledWith({
fileSystemRepo,
qiitaApi,
forceUpdate: true,
});
expect(mockSyncArticlesFromQiita).toBeCalledTimes(1);
});

it("pulls articles with forceUpdate", async () => {
await pull(["-f"]);

expect(mockSyncArticlesFromQiita).toBeCalledWith({
fileSystemRepo,
qiitaApi,
forceUpdate: true,
});
});
});
});
4 changes: 2 additions & 2 deletions src/commands/pull.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ export const pull = async (argv: string[]) => {

const qiitaApi = await getQiitaApiInstance();
const fileSystemRepo = await getFileSystemRepo();
const isLocalUpdate = args["--force"];
const forceUpdate = args["--force"];
Copy link
Member

Choose a reason for hiding this comment

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

pull.tssync-article-from-qiita.tsの変数の命名変更は別文脈なのでコミット分けたいです 🙏


await syncArticlesFromQiita({ fileSystemRepo, qiitaApi, isLocalUpdate });
await syncArticlesFromQiita({ fileSystemRepo, qiitaApi, forceUpdate });
console.log("Sync local articles from Qiita");
console.log("Successful!");
};
4 changes: 4 additions & 0 deletions src/lib/entities/qiita-item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export class QiitaItem {
public readonly rawBody: string;
public readonly name: string;
public readonly modified: boolean;
public readonly isOlderThanRemote: boolean;
public readonly itemsShowPath: string;
public readonly published: boolean;
public readonly itemPath: string;
Expand All @@ -23,6 +24,7 @@ export class QiitaItem {
rawBody,
name,
modified,
isOlderThanRemote,
itemsShowPath,
published,
itemPath,
Expand All @@ -37,6 +39,7 @@ export class QiitaItem {
rawBody: string;
name: string;
modified: boolean;
isOlderThanRemote: boolean;
itemsShowPath: string;
published: boolean;
itemPath: string;
Expand All @@ -51,6 +54,7 @@ export class QiitaItem {
this.rawBody = rawBody;
this.name = name;
this.modified = modified;
this.isOlderThanRemote = isOlderThanRemote;
this.itemsShowPath = itemsShowPath;
this.published = published;
this.itemPath = itemPath;
Expand Down
6 changes: 3 additions & 3 deletions src/lib/file-system-repo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,9 +315,9 @@ updated
`;
const subject = (
beforeSync: boolean = false,
isLocalUpdate: boolean = false
forceUpdate: boolean = false
) => {
return instance.saveItem(item, beforeSync, isLocalUpdate);
return instance.saveItem(item, beforeSync, forceUpdate);
};

describe("when local article does not exist", () => {
Expand Down Expand Up @@ -378,7 +378,7 @@ updated
});
});

describe("when isLocalUpdate is true", () => {
describe("when forceUpdate is true", () => {
it("saves item local and remote", () => {
const mockFs = fs as jest.Mocked<typeof fs>;
mockFs.readdir.mockResolvedValueOnce([localFilename] as any[]);
Expand Down
22 changes: 16 additions & 6 deletions src/lib/file-system-repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,14 @@ class FileContent {
);
}

isOlderThan(otherFileContent: FileContent | null): boolean {
if (!otherFileContent) return false;
const updatedAt = new Date(this.updatedAt);
const otherUpdatedAt = new Date(otherFileContent.updatedAt);

return updatedAt < otherUpdatedAt;
}

clone({ id }: { id: string }): FileContent {
return new FileContent({
title: this.title,
Expand Down Expand Up @@ -264,7 +272,7 @@ export class FileSystemRepo {
private async syncItem(
item: Item,
beforeSync: boolean = false,
isLocalUpdate: boolean = false
forceUpdate: boolean = false
) {
const fileContent = FileContent.fromItem(item);
Comment on lines 272 to 277
Copy link
Member

Choose a reason for hiding this comment

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

LGTMした後ですみません
テストは変更ないですが大丈夫ですか?


Expand All @@ -279,17 +287,17 @@ export class FileSystemRepo {
true
);

if (data === null || remoteFileContent?.equals(data) || isLocalUpdate) {
if (data === null || remoteFileContent?.equals(data) || forceUpdate) {
await this.setItemData(fileContent, true);
await this.setItemData(fileContent, false, basename);
} else {
await this.setItemData(fileContent, true);
}
}

async saveItems(items: Item[], isLocalUpdate: boolean = false) {
async saveItems(items: Item[], forceUpdate: boolean = false) {
const promises = items.map(async (item) => {
await this.syncItem(item, false, isLocalUpdate);
await this.syncItem(item, false, forceUpdate);
});

await Promise.all(promises);
Expand All @@ -298,9 +306,9 @@ export class FileSystemRepo {
async saveItem(
item: Item,
beforeSync: boolean = false,
isLocalUpdate: boolean = false
forceUpdate: boolean = false
) {
await this.syncItem(item, beforeSync, isLocalUpdate);
await this.syncItem(item, beforeSync, forceUpdate);
}

async loadItems(): Promise<QiitaItem[]> {
Expand Down Expand Up @@ -353,6 +361,7 @@ export class FileSystemRepo {
slide: localFileContent.slide,
name: basename,
modified: !localFileContent.equals(remoteFileContent),
isOlderThanRemote: localFileContent.isOlderThan(remoteFileContent),
itemsShowPath: this.generateItemsShowPath(localFileContent.id, basename),
published: remoteFileContent !== null,
itemPath,
Expand Down Expand Up @@ -388,6 +397,7 @@ export class FileSystemRepo {
slide: localFileContent.slide,
name: basename,
modified: !localFileContent.equals(remoteFileContent),
isOlderThanRemote: localFileContent.isOlderThan(remoteFileContent),
itemsShowPath: this.generateItemsShowPath(localFileContent.id, basename),
published: remoteFileContent !== null,
itemPath,
Expand Down
Loading