Skip to content

Commit

Permalink
Merge branch 'feature/#39-logs' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
Zhykos committed Nov 1, 2024
2 parents 288a2b0 + 2a55d9a commit 4f944bb
Show file tree
Hide file tree
Showing 14 changed files with 152 additions and 81 deletions.
7 changes: 4 additions & 3 deletions src/cli/service/CLIService.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import type { Log } from "@cross/log";
import { type Args, parseArgs } from "@std/cli/parse-args";
import { File } from "../../common/domain/valueobject/File.ts";
import { Path } from "../../common/domain/valueobject/Path.ts";
import { pathExists } from "../../utils/file.ts";
import { CLI, type CLIBuilder } from "../domain/aggregate/CLI.ts";

export class CLIService {
read(cliArgs: string[]): CLI {
read(cliArgs: string[], logger: Log): CLI {
const args: Args = parseArgs(cliArgs, {
boolean: ["debug", "publish"],
string: [
Expand Down Expand Up @@ -45,9 +46,9 @@ export class CLIService {
cliBuilder.withDatabaseFilepath(databaseFilepath);

if (pathExists(databaseFilepath)) {
console.log(`Using database file: ${databaseFilepath}`);
logger.log(`Using database file: ${databaseFilepath}`);
} else {
console.warn(
logger.warn(
`Database file not found, using a new one: ${databaseFilepath}`,
);
}
Expand Down
5 changes: 3 additions & 2 deletions src/common/repository/CommonKvRelationRepository.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Log } from "@cross/log";
import type { KvDriver } from "../../common/dbdriver/KvDriver.ts";
import type { VideoGameRelationImageRepositoryEntity } from "./entity/VideoGameRelationImageRepositoryEntity.ts";

Expand All @@ -19,7 +20,7 @@ export class CommonKvRelationRepository {
);
}

async updatePublishedStatus(imageID: string): Promise<void> {
async updatePublishedStatus(imageID: string, logger: Log): Promise<void> {
const allRelations: VideoGameRelationImageRepositoryEntity[] =
await this.getAllVideoGameRelations();

Expand All @@ -30,7 +31,7 @@ export class CommonKvRelationRepository {
entity.published = true;
await this.kvDriver.save(["relation", entity.uuid], entity);
} else {
console.error(
logger.error(
`Image ID "${imageID}" in relations cannot be found.
Possible entities are: ${(await this.kvDriver.list(["relation"], {} as VideoGameRelationImageRepositoryEntity)).map((e) => `${e.imageID} (rel: ${e.uuid})`).sort()}`,
);
Expand Down
25 changes: 15 additions & 10 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,36 +12,41 @@ import { publish } from "./publish.ts";
import { runScanner } from "./scan.ts";

export async function main(cliArgs: string[]): Promise<boolean> {
console.log("Starting Autophoto...");
const logger = new Log();

logger.log("Starting Autophoto...");

const cli: CLI = new CLIService().read(cliArgs);
const cli: CLI = new CLIService().read(cliArgs, logger);
const kvDriver = new KvDriver(cli.action.databaseFilepath);
const logger = new Log();

try {
if (cli.action instanceof ScannerAction) {
console.log("Scanning...");
logger.log("Scanning...");
const configuration: Configuration = new ConfigurationService().loadFile(
cli.action.configurationFile.path.value,
);
await runScanner(configuration, kvDriver, cli.action.debug);
await runScanner(configuration, kvDriver, cli.action.debug, logger);
return true;
}

if (cli.action instanceof BlueskyPublisherAction) {
console.log("Publishing...");
const result: string | undefined = await publish(cli.action, kvDriver);
console.log("Publication result:", result ?? "Nothing to publish.");
logger.log("Publishing...");
const result: string | undefined = await publish(
cli.action,
kvDriver,
logger,
);
logger.log("Publication result:", result ?? "Nothing to publish.");
return true;
}

console.log("Pre-scanning...");
logger.log("Pre-scanning...");
const configuration: Configuration = new ConfigurationService().loadFile(
(cli.action as PreScannerAction).configurationFile.path.value,
);
return preScan(configuration, logger);
} finally {
kvDriver.close();
console.log("Autophoto finished.");
logger.log("Autophoto finished.");
}
}
13 changes: 10 additions & 3 deletions src/picker/repository/RelationRepository.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Log } from "@cross/log";
import type { KvDriver } from "../../common/dbdriver/KvDriver.ts";
import { CommonKvRelationRepository } from "../../common/repository/CommonKvRelationRepository.ts";
import type { VideoGameRelationImageRepositoryEntity } from "../../common/repository/entity/VideoGameRelationImageRepositoryEntity.ts";
Expand All @@ -9,7 +10,7 @@ export interface RelationRepository {
UnpublishedVideoGameScreenshotRelation[]
>;

updatePublishedStatuses(updatedImages: Image[]): Promise<void>;
updatePublishedStatuses(updatedImages: Image[], logger: Log): Promise<void>;
}

export class KvRelationRepository implements RelationRepository {
Expand Down Expand Up @@ -38,9 +39,15 @@ export class KvRelationRepository implements RelationRepository {
);
}

async updatePublishedStatuses(updatedImages: Image[]): Promise<void> {
async updatePublishedStatuses(
updatedImages: Image[],
logger: Log,
): Promise<void> {
for (const updatedImage of updatedImages) {
await this.commonRepository.updatePublishedStatus(updatedImage.id);
await this.commonRepository.updatePublishedStatus(
updatedImage.id,
logger,
);
}
}
}
14 changes: 12 additions & 2 deletions src/publish.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { AtpAgent } from "@atproto/api";
import type { Log } from "@cross/log";
import type { BlueskyPublisherAction } from "./cli/domain/valueobject/BlueskyPublisherAction.ts";
import type { KvDriver } from "./common/dbdriver/KvDriver.ts";
import { File } from "./common/domain/valueobject/File.ts";
Expand All @@ -21,6 +22,7 @@ import { pluralFinalS } from "./utils/plural-final-s.ts";
export const publish = async (
blueskyAction: BlueskyPublisherAction,
kvDriver: KvDriver,
logger: Log,
): Promise<string | undefined> => {
const relationRepository = new KvRelationRepository(kvDriver);

Expand All @@ -37,6 +39,8 @@ export const publish = async (
return undefined;
}

logger.log(`Picked video game: ${pickedVideoGameScreeshots.title}`);

const resultPublication: string = await new BlueskyPublisherService().publish(
new BlueskyPublication(
new AtpAgent({
Expand All @@ -56,14 +60,18 @@ export const publish = async (
),
);

await updatePublishedStatuses(pickedVideoGameScreeshots, relationRepository);
await updatePublishedStatuses(
pickedVideoGameScreeshots,
relationRepository,
logger,
);

if (blueskyAction.debug) {
const debug: string = await debugDatabaseInformation(
pickedVideoGameScreeshots,
relationRepository,
);
console.log("Debug database information:", debug);
logger.log("Debug database information:", debug);
}

return resultPublication;
Expand All @@ -72,9 +80,11 @@ export const publish = async (
async function updatePublishedStatuses(
publishedVideoGameScreeshots: VideoGameScreeshotsToShare,
relationRepository: RelationRepository,
logger: Log,
): Promise<void> {
await relationRepository.updatePublishedStatuses(
publishedVideoGameScreeshots.screenshots,
logger,
);
}

Expand Down
15 changes: 9 additions & 6 deletions src/scan.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Log } from "@cross/log";
import type { KvDriver } from "./common/dbdriver/KvDriver.ts";
import type { VideoGameRelationImageRepositoryEntity } from "./common/repository/entity/VideoGameRelationImageRepositoryEntity.ts";
import type { Configuration } from "./configuration/domain/aggregate/Configuration.ts";
Expand All @@ -20,6 +21,7 @@ export const runScanner = async (
configuration: Configuration,
kvDriver: KvDriver,
debugDatabase: boolean,
logger: Log,
): Promise<void> => {
const videoGameRepository = new KvVideoGameRepository(kvDriver);
const relationRepository = new KvRelationRepository(kvDriver);
Expand All @@ -30,15 +32,15 @@ export const runScanner = async (
relationRepository,
);

await scan(scanner, configuration.scans);
await scan(scanner, configuration.scans, logger);

if (debugDatabase) {
const debug: string = await debugDatabaseInformation(
kvDriver.databaseFilePath,
videoGameRepository,
relationRepository,
);
console.log("Debug database information:", debug);
logger.log("Debug database information:", debug);
}
};

Expand Down Expand Up @@ -81,26 +83,27 @@ ${pluralFinalS(allRelations.length, "screenshot")} in database, ${remainingScree
export async function scan(
scanner: Scanner,
scanData: ConfigurationScanWithPattern[],
logger: Log,
): Promise<void> {
let hasError = false;

try {
// TODO Alerting
for (const scan of scanData) {
console.log(`Scanning ${scan.directory.path.value}...`);
logger.log(`Scanning ${scan.directory.path.value}...`);
const imageDirectory = new ImageDirectory(
scan.directory,
scan.pattern.regex,
scan.pattern.groups,
);
await scanner.scanAndSaveNewImages(imageDirectory);
}
console.log("Scan completed!");
logger.log("Scan completed!");
} catch (error) {
// TODO Alerting
hasError = true;
console.error("An error occurred while scanning.");
console.error(error);
logger.error("An error occurred while scanning.");
logger.error(error);
}

if (hasError) {
Expand Down
62 changes: 37 additions & 25 deletions test/cli/service/CLIService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import type { CLI } from "../../../src/cli/domain/aggregate/CLI.ts";
import { BlueskyPublisherAction } from "../../../src/cli/domain/valueobject/BlueskyPublisherAction.ts";
import { ScannerAction } from "../../../src/cli/domain/valueobject/ScannerAction.ts";
import { CLIService } from "../../../src/cli/service/CLIService.ts";
import { mockLogger } from "../../mock/logger/mockLogger.ts";

describe("CLIService", () => {
it("should fail if no args", () => {
const error = assertThrows(() => new CLIService().read([]));
const error = assertThrows(() => new CLIService().read([], mockLogger()));
assert(error instanceof Error);
assertEquals(
error.message,
Expand All @@ -17,7 +18,7 @@ describe("CLIService", () => {

it("should fail if too mush args", () => {
const error = assertThrows(() =>
new CLIService().read(["README.md", "LICENSE"]),
new CLIService().read(["README.md", "LICENSE"], mockLogger()),
);
assert(error instanceof Error);
assertEquals(
Expand All @@ -27,19 +28,25 @@ describe("CLIService", () => {
});

it("should fail if one arg", () => {
const error = assertThrows(() => new CLIService().read(["foo"]));
const error = assertThrows(() =>
new CLIService().read(["foo"], mockLogger()),
);
assert(error instanceof Error);
assertEquals(error.message, 'Command line argument is not allowed: "foo"');
});

it("should fail if scanner option is a directory", () => {
const error = assertThrows(() => new CLIService().read(["--scan=src"]));
const error = assertThrows(() =>
new CLIService().read(["--scan=src"], mockLogger()),
);
assert(error instanceof Error);
assertEquals(error.message, 'Path is not a file: "src"');
});

it("should fail if one file arg", () => {
const error = assertThrows(() => new CLIService().read(["README.md"]));
const error = assertThrows(() =>
new CLIService().read(["README.md"], mockLogger()),
);
assert(error instanceof Error);
assertEquals(
error.message,
Expand All @@ -48,7 +55,10 @@ describe("CLIService", () => {
});

it("should create scanner", () => {
const cliResult: CLI = new CLIService().read(["--scan=README.md"]);
const cliResult: CLI = new CLIService().read(
["--scan=README.md"],
mockLogger(),
);
assert(cliResult.action instanceof ScannerAction);
assertEquals(
(cliResult.action as ScannerAction).configurationFile.path.value,
Expand All @@ -58,19 +68,18 @@ describe("CLIService", () => {
});

it("should create publisher", () => {
const cliResult: CLI = new CLIService().read([
"--publish",
"--bluesky_login=login",
"--bluesky_password=password",
]);
const cliResult: CLI = new CLIService().read(
["--publish", "--bluesky_login=login", "--bluesky_password=password"],
mockLogger(),
);
assert(cliResult.action instanceof BlueskyPublisherAction);
});

it("should specify database", () => {
const cliResult: CLI = new CLIService().read([
"--database=new.db",
"--scan=README.md",
]);
const cliResult: CLI = new CLIService().read(
["--database=new.db", "--scan=README.md"],
mockLogger(),
);
assertEquals(
(cliResult.action as ScannerAction).configurationFile.path.value,
"README.md",
Expand All @@ -79,16 +88,16 @@ describe("CLIService", () => {
});

it("should activate debug", () => {
const cliResult: CLI = new CLIService().read([
"--debug",
"--scan=README.md",
]);
const cliResult: CLI = new CLIService().read(
["--debug", "--scan=README.md"],
mockLogger(),
);
assert(cliResult.action.debug);
});

it("should fail if debug prescan", () => {
const error = assertThrows(() =>
new CLIService().read(["--debug", "--prescan=config.yml"]),
new CLIService().read(["--debug", "--prescan=config.yml"], mockLogger()),
);
assert(error instanceof Error);
assertEquals(
Expand All @@ -99,7 +108,10 @@ describe("CLIService", () => {

it("should fail if using a database with prescan", () => {
const error = assertThrows(() =>
new CLIService().read(["--database=db.sqlite", "--prescan=config.yml"]),
new CLIService().read(
["--database=db.sqlite", "--prescan=config.yml"],
mockLogger(),
),
);
assert(error instanceof Error);
assertEquals(
Expand All @@ -110,10 +122,10 @@ describe("CLIService", () => {

it("should fail if using scanner with bluesky publisher", () => {
const error = assertThrows(() =>
new CLIService().read([
"--bluesky_host=https://bsky.social",
"--prescan=config.yml",
]),
new CLIService().read(
["--bluesky_host=https://bsky.social", "--prescan=config.yml"],
mockLogger(),
),
);
assert(error instanceof Error);
assertEquals(
Expand Down
Loading

0 comments on commit 4f944bb

Please sign in to comment.