Skip to content

Add package update notice #28

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 1 commit into from
Jul 19, 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
1 change: 1 addition & 0 deletions .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ QIITA_DOMAIN='qiita.com'
QIITA_TOKEN='<Qiita トークン>'
QIITA_CLI_ITEMS_ROOT="./tmp"
XDG_CONFIG_HOME="./tmp"
XDG_CACHE_HOME="./tmp/.cache"
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@
},
"dependencies": {
"arg": "^5.0.2",
"boxen": "^7.1.1",
"chalk": "^5.3.0",
"chokidar": "^3.5.3",
"debug": "^4.3.4",
"dotenv": "^16.0.3",
Expand Down
10 changes: 8 additions & 2 deletions src/commands/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { packageUpdateNotice } from "../lib/package-update-notice";
import { help, helpText } from "./help";
import { init } from "./init";
import { login } from "./login";
import { newArticles } from "./newArticles";
import { preview } from "./preview";
import { publish } from "./publish";
import { version } from "./version";
import { pull } from "./pull";
import { version } from "./version";

export const exec = (commandName: string, commandArgs: string[]) => {
export const exec = async (commandName: string, commandArgs: string[]) => {
const commands = {
init,
login,
Expand All @@ -32,5 +33,10 @@ export const exec = (commandName: string, commandArgs: string[]) => {
process.exit(1);
}

const updateMessage = await packageUpdateNotice();
if (updateMessage) {
console.log(updateMessage);
}

commands[commandName](commandArgs);
};
37 changes: 37 additions & 0 deletions src/lib/config.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import process from "node:process";
import { config } from "./config";

jest.mock("node:process");

const initMockFs = () => {
let files: { [path: string]: string } = {};

Expand Down Expand Up @@ -175,6 +178,40 @@ describe("config", () => {
});
});

describe("#getCacheDataDir", () => {
beforeEach(() => {
config.load({});
});

it("returns default path", () => {
expect(config.getCacheDataDir()).toEqual(
"/home/test-user/.cache/qiita-cli"
);
});

describe("with XDG_CACHE_HOME environment", () => {
const xdgCacheHome = "/tmp/.cache";

const mockProcess = process as jest.Mocked<typeof process>;
const env = mockProcess.env;
beforeEach(() => {
mockProcess.env = {
...env,
XDG_CACHE_HOME: xdgCacheHome,
};

config.load({});
});
afterEach(() => {
mockProcess.env = env;
});

it("returns customized path", () => {
expect(config.getCacheDataDir()).toEqual(`${xdgCacheHome}/qiita-cli`);
});
});
});

describe("#getUserConfig", () => {
const userConfigFilePath =
"/home/test-user/qiita-articles/qiita.config.json";
Expand Down
27 changes: 22 additions & 5 deletions src/lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,12 @@ class Config {
private userConfigFilePath?: string;
private userConfigDir?: string;
private credential?: Credential;
private cacheDataDir?: string;
private readonly packageName: string;

constructor() {}
constructor() {
this.packageName = "qiita-cli";
}

load(options: Options) {
this.credentialDir = this.resolveConfigDir(options.credentialDir);
Expand All @@ -32,6 +36,7 @@ class Config {
this.userConfigFilePath = this.resolveUserConfigFilePath(
options.userConfigDir
);
this.cacheDataDir = this.resolveCacheDataDir();
this.credential = new Credential({
credentialDir: this.credentialDir,
profile: options.profile,
Expand All @@ -43,6 +48,7 @@ class Config {
credentialDir: this.credentialDir,
itemsRootDir: this.itemsRootDir,
userConfigFilePath: this.userConfigFilePath,
cacheDataDir: this.cacheDataDir,
})
);
}
Expand Down Expand Up @@ -76,6 +82,13 @@ class Config {
return this.userConfigFilePath;
}

getCacheDataDir() {
if (!this.cacheDataDir) {
throw new Error("cacheDataDir is undefined");
}
return this.cacheDataDir;
}

getCredential() {
if (!this.credential) {
throw new Error("credential is undefined");
Expand Down Expand Up @@ -109,15 +122,13 @@ class Config {
}

private resolveConfigDir(credentialDirPath?: string) {
const packageName = "qiita-cli";

if (process.env.XDG_CONFIG_HOME) {
const credentialDir = process.env.XDG_CONFIG_HOME;
return path.join(credentialDir, packageName);
return path.join(credentialDir, this.packageName);
}
if (!credentialDirPath) {
const homeDir = os.homedir();
return path.join(homeDir, ".config", packageName);
return path.join(homeDir, ".config", this.packageName);
}

return this.resolveFullPath(credentialDirPath);
Expand Down Expand Up @@ -150,6 +161,12 @@ class Config {
return path.join(this.resolveUserConfigDirPath(dirPath), filename);
}

private resolveCacheDataDir() {
const cacheHome =
process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache");
return path.join(cacheHome, this.packageName);
}

private resolveFullPath(filePath: string) {
if (path.isAbsolute(filePath)) {
return filePath;
Expand Down
15 changes: 15 additions & 0 deletions src/lib/get-latest-package-version/fetch-package-version.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { PackageSettings } from "../package-settings";

export const fetchLatestPackageVersion = async () => {
try {
const response = await fetch(
`https://registry.npmjs.org/${PackageSettings.name}/latest`
);
const json = await response.json();
const latestVersion = json.version as string;

return latestVersion;
} catch {
return null;
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import * as fetchPackageVersion from "./fetch-package-version";
import { getLatestPackageVersion } from "./get-latest-package-version";
import type { CacheData } from "./package-version-cache";
import * as packageVersionCache from "./package-version-cache";

describe("getLatestPackageVersion", () => {
const mockFetchLatestPackageVersion = jest.spyOn(
fetchPackageVersion,
"fetchLatestPackageVersion"
);
const mockGetCacheData = jest.spyOn(packageVersionCache, "getCacheData");
const mockSetCacheData = jest.spyOn(packageVersionCache, "setCacheData");
const mockDateNow = jest.spyOn(Date, "now");

beforeEach(() => {
mockFetchLatestPackageVersion.mockReset();
mockGetCacheData.mockReset();
mockSetCacheData.mockReset();
});

describe("when cache exists and not expired", () => {
const cacheData: CacheData = {
lastCheckedAt: new Date("2023-07-13T00:00:00.000Z").getTime(),
latestVersion: "0.0.0",
};

beforeEach(() => {
mockGetCacheData.mockReturnValue(cacheData);
mockDateNow.mockReturnValue(
new Date("2023-07-13T11:00:00.000Z").getTime()
);
});

it("returns cached version", async () => {
expect(await getLatestPackageVersion()).toEqual("0.0.0");
expect(mockGetCacheData).toHaveBeenCalled();
expect(mockFetchLatestPackageVersion).not.toHaveBeenCalled();
expect(mockDateNow).toHaveBeenCalled();
expect(mockSetCacheData).not.toHaveBeenCalled();
});
});

describe("when cache exists but expired", () => {
const cacheData: CacheData = {
lastCheckedAt: new Date("2023-07-13T00:00:00.000Z").getTime(),
latestVersion: "0.0.0",
};
const currentTime = new Date("2023-07-13T12:00:00.000Z").getTime();

beforeEach(() => {
mockGetCacheData.mockReturnValue(cacheData);
mockDateNow.mockReturnValue(currentTime);
mockFetchLatestPackageVersion.mockResolvedValue("0.0.1");
mockSetCacheData.mockReturnValue();
});

it("returns latest version and updates cache", async () => {
expect(await getLatestPackageVersion()).toEqual("0.0.1");
expect(mockGetCacheData).toBeCalled();
expect(mockDateNow).toHaveBeenCalled();
expect(mockFetchLatestPackageVersion).toHaveBeenCalled();
expect(mockSetCacheData).toHaveBeenCalledWith({
lastCheckedAt: currentTime,
latestVersion: "0.0.1",
});
});
});

describe("when cache does not exist", () => {
const currentTime = new Date("2023-07-13T12:00:00.000Z").getTime();

beforeEach(() => {
mockGetCacheData.mockReturnValue(null);
mockDateNow.mockReturnValue(currentTime);
mockFetchLatestPackageVersion.mockResolvedValue("0.0.1");
mockSetCacheData.mockReturnValue();
});

it("returns latest version and updates cache", async () => {
expect(await getLatestPackageVersion()).toEqual("0.0.1");
expect(mockGetCacheData).toBeCalled();
expect(mockDateNow).toHaveBeenCalled();
expect(mockFetchLatestPackageVersion).toHaveBeenCalled();
expect(mockSetCacheData).toHaveBeenCalledWith({
lastCheckedAt: currentTime,
latestVersion: "0.0.1",
});
});
});
});
27 changes: 27 additions & 0 deletions src/lib/get-latest-package-version/get-latest-package-version.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { fetchLatestPackageVersion } from "./fetch-package-version";
import { getCacheData, setCacheData } from "./package-version-cache";

const CACHE_EXPIRE_TIME = 1000 * 60 * 60 * 12; // 12 hours

export const getLatestPackageVersion = async () => {
const cacheData = getCacheData();
const now = Date.now();

if (cacheData) {
const { lastCheckedAt, latestVersion } = cacheData;

if (now - lastCheckedAt < CACHE_EXPIRE_TIME) {
return latestVersion;
}
}

const latestVersion = await fetchLatestPackageVersion();
if (latestVersion) {
setCacheData({
lastCheckedAt: now,
latestVersion,
});
}

return latestVersion;
};
1 change: 1 addition & 0 deletions src/lib/get-latest-package-version/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { getLatestPackageVersion } from "./get-latest-package-version";
36 changes: 36 additions & 0 deletions src/lib/get-latest-package-version/package-version-cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import fs from "node:fs";
import path from "node:path";
import { config } from "../config";

export interface CacheData {
lastCheckedAt: number;
latestVersion: string;
}

const CACHE_FILE_NAME = "latest-package-version";

const cacheFilePath = () => {
const cacheDir = config.getCacheDataDir();
return path.join(cacheDir, CACHE_FILE_NAME);
};

export const getCacheData = () => {
const filePath = cacheFilePath();
if (!fs.existsSync(filePath)) {
return null;
}

const data = fs.readFileSync(filePath, { encoding: "utf-8" });
return JSON.parse(data) as CacheData;
};

export const setCacheData = (data: CacheData) => {
const cacheDir = config.getCacheDataDir();
const filePath = cacheFilePath();

fs.mkdirSync(cacheDir, { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(data), {
encoding: "utf-8",
mode: 0o600,
});
};
1 change: 1 addition & 0 deletions src/lib/package-settings.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const packageJsonData = require("../../package.json");

export const PackageSettings = {
name: packageJsonData.name,
userAgentName: "QiitaCLI",
version: packageJsonData.version,
};
27 changes: 27 additions & 0 deletions src/lib/package-update-notice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { getLatestPackageVersion } from "./get-latest-package-version";
import { PackageSettings } from "./package-settings";

export const packageUpdateNotice = async () => {
const currentVersion = PackageSettings.version;
const latestVersion = await getLatestPackageVersion();

if (!latestVersion) {
return null;
}
if (currentVersion === latestVersion) {
return null;
}

const chalk = (await import("chalk")).default; // `chalk` supports only ESM.
const boxen = (await import("boxen")).default; // `boxen` supports only ESM.

let message = "新しいバージョンがあります! ";
message += ` ${chalk.red(currentVersion)} -> ${chalk.green(latestVersion)}`;
message += "\n";
message += `${chalk.green(`npm install ${PackageSettings.name}@latest`)}`;
message += " でアップデートできます!";

message = boxen(message, { padding: 1, margin: 1, borderStyle: "round" });

return message;
};
1 change: 0 additions & 1 deletion src/server/api/items.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ const itemsShow = async (req: Express.Request, res: Express.Response) => {
return;
}

// const { data, itemPath, modified, published } = ;
const { itemPath, modified, published } = item;

const qiitaApi = await getQiitaApiInstance();
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"lib": ["es2020", "DOM"],
"module": "commonjs",
"module": "Node16",
"outDir": "./dist",
"rootDir": "./src",
"skipLibCheck": false,
Expand Down
Loading