Skip to content
Draft
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: 6 additions & 2 deletions docs/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -335,11 +335,11 @@ These commands help you develop Actors locally. Use them to create new Actor pro
DESCRIPTION
Creates an Actor project from a template in a new directory. The command
automatically initializes a git repository in the newly created Actor
directory.
directory, unless it's inside an existing Git repository.

USAGE
$ apify create [actorName] [--auto-build on|off]
[--git-repo <value>] [--json]
[--git-repo <value>] [--into <value>] [--json]
[-l javascript|js|typescript|ts|python|py]
[--omit-optional-deps] [--profile <value>]
[--skip-dependency-install] [--skip-git-init]
Expand All @@ -364,6 +364,10 @@ FLAGS
is asked for when you have more than one. List
yours with "apify api integrations/git". Only used
when --source is a Git provider.
--into=<value> Folder to create the
Actor directory in, instead of the current
directory. It's relative to the current directory
or absolute, and it's created if it doesn't exist.
--json Format the command
output as JSON.
-l, --language=<option> Filter templates by
Expand Down
79 changes: 68 additions & 11 deletions src/commands/create.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { mkdir, readdir, stat } from 'node:fs/promises';
import { join } from 'node:path';
import { join, relative, resolve } from 'node:path';
import process from 'node:process';

import { isCI } from 'ci-info';
Expand All @@ -23,8 +23,10 @@ import {
enhanceReadmeWithLocalSuffix,
ensureValidActorName,
formatCreateSuccessMessage,
getRepositoryDockerContextDir,
getTemplateDefinition,
} from '../lib/create-utils.js';
import { findGitRoot, isOutside } from '../lib/docker-context.js';
import { execWithLog } from '../lib/exec.js';
import { updateLocalJson } from '../lib/files.js';
import {
Expand Down Expand Up @@ -65,7 +67,7 @@ export class CreateCommand extends ApifyCommand<typeof CreateCommand> {
static override enableProfileFlag = true;

static override description =
'Creates an Actor project from a template in a new directory. The command automatically initializes a git repository in the newly created Actor directory.';
"Creates an Actor project from a template in a new directory. The command automatically initializes a git repository in the newly created Actor directory, unless it's inside an existing Git repository.";

static override group = 'Local Actor Development';

Expand Down Expand Up @@ -100,6 +102,10 @@ export class CreateCommand extends ApifyCommand<typeof CreateCommand> {
description: 'Name the account and the repository to create, instead of being asked.',
command: 'apify create my-actor --template js-crawlee-cheerio --source github --git-repo my-org/my-scraper',
},
{
description: 'Add an Actor to the "actors" folder of an existing repository.',
command: 'apify create my-actor --template js-crawlee-cheerio --into actors',
},
];

static override docsUrl = 'https://docs.apify.com/cli/docs/reference#apify-create';
Expand All @@ -123,6 +129,11 @@ export class CreateCommand extends ApifyCommand<typeof CreateCommand> {
choices: LANGUAGE_FLAG_CHOICES,
required: false,
}),
into: Flags.string({
description:
"Folder to create the Actor directory in, instead of the current directory. It's relative to the current directory or absolute, and it's created if it doesn't exist.",
required: false,
}),
'skip-dependency-install': Flags.boolean({
description: 'Skip installing Actor dependencies.',
required: false,
Expand Down Expand Up @@ -190,6 +201,7 @@ export class CreateCommand extends ApifyCommand<typeof CreateCommand> {
origin,
json,
gitRepo,
into,
} = this.flags;

// --template-archive-url is an internal, undocumented flag that's used
Expand All @@ -214,6 +226,23 @@ export class CreateCommand extends ApifyCommand<typeof CreateCommand> {

let source = this.flags.source as GitSource | undefined;

if (into && source && isGitProvider(source)) {
throw new Error(
`--into places the Actor in an existing folder, while --source ${source} creates a new repository for it. Drop one of them.`,
);
}

const cwd = process.cwd();
const parentDir = into ? resolve(cwd, into) : cwd;
const intoStats = into ? await stat(parentDir).catch(() => null) : null;

if (intoStats && !intoStats.isDirectory()) {
throw new Error(`Cannot create the Actor in "${into}", because it isn't a directory.`);
}

// As the user would type it: relative to the current directory, or absolute outside it.
const pathFromCwd = (dir: string) => (isOutside(relative(cwd, dir)) ? dir : relative(cwd, dir));

// Start fetching manifest immediately to prevent
// annoying delays that sometimes happen on CLI startup.
const manifestPromise = fetchManifest().catch((err) => {
Expand All @@ -222,8 +251,7 @@ export class CreateCommand extends ApifyCommand<typeof CreateCommand> {

actorName = await ensureValidActorName(actorName);

const cwd = process.cwd();
let actFolderDir = join(cwd, actorName);
let actFolderDir = join(parentDir, actorName);

while (true) {
const folderExists = await stat(actFolderDir).catch(() => null);
Expand All @@ -235,7 +263,7 @@ export class CreateCommand extends ApifyCommand<typeof CreateCommand> {

if (folderExists?.isDirectory() && folderHasFiles) {
const message =
`Cannot create new Actor, directory '${actorName}' already exists. Provide a different name.` +
`Cannot create new Actor, directory '${pathFromCwd(actFolderDir)}' already exists. Provide a different name.` +
' To create a local Actor environment inside an existing directory, use "apify init".';

if (json) {
Expand All @@ -245,7 +273,7 @@ export class CreateCommand extends ApifyCommand<typeof CreateCommand> {
error({ message });

actorName = await ensureValidActorName();
actFolderDir = join(cwd, actorName);
actFolderDir = join(parentDir, actorName);

continue;
}
Expand Down Expand Up @@ -289,8 +317,9 @@ export class CreateCommand extends ApifyCommand<typeof CreateCommand> {
const { isTTY } = await useStdin();
const isInteractive = isTTY && !isCI && !json;

// Last wizard step, matching the Console. A run that cannot be asked keeps the previous behaviour.
source ??= isInteractive ? await promptGitSource() : 'apify';
// Last wizard step, matching the Console. A run that cannot be asked keeps the previous behaviour. A Git source
// creates its own repository, so it can't go into an existing folder.
source ??= isInteractive && !into ? await promptGitSource() : 'apify';
const gitProvider = isGitProvider(source) ? source : null;
this.telemetryData.create.source = source;

Expand Down Expand Up @@ -328,6 +357,8 @@ export class CreateCommand extends ApifyCommand<typeof CreateCommand> {
: null;

let usesStandbyMode = false;
let dockerContextDir: string | undefined;
const existingGitRoot = findGitRoot(parentDir);

// Local-only setup, applied to the unzipped archive or to the clone, whichever the run produced.
const applyLocalConfig = async (dir: string) => {
Expand All @@ -345,6 +376,19 @@ export class CreateCommand extends ApifyCommand<typeof CreateCommand> {
await downloadAndUnzip({ url: templateArchiveUrl, pathTo: actFolderDir });
await applyLocalConfig(actFolderDir);

// A Dockerfile that builds from the repository root needs the platform to build from there too.
const repositoryRoot = existingGitRoot ?? (into ? cwd : undefined);
if (repositoryRoot) {
const localConfig = getJsonFileContent(join(actFolderDir, LOCAL_CONFIG_PATH)) ?? {};
dockerContextDir = getRepositoryDockerContextDir(actFolderDir, localConfig, repositoryRoot);
if (dockerContextDir) {
await setLocalConfig({ ...localConfig, dockerContextDir }, actFolderDir);
info({
message: `Set "dockerContextDir" to "${dockerContextDir}" in ${LOCAL_CONFIG_PATH}, so the Actor builds from ${repositoryRoot}.`,
});
}
}

// Add localReadmeSuffix which is fetched from manifest to README.md
// The suffix contains local development instructions. The Git path skips it: the platform
// already appended its own while seeding the repository.
Expand Down Expand Up @@ -552,11 +596,21 @@ export class CreateCommand extends ApifyCommand<typeof CreateCommand> {

// Initialize git repository before reporting success, but store result for later
let gitInitResult: { success: boolean; error?: Error } = { success: true };
const cwdHasGit = await stat(join(cwd, '.git')).catch(() => null);
// Skip when the Actor directory is already a repository, which the Git path's clone has made it.
const actorDirHasGit = await stat(join(actFolderDir, '.git')).catch(() => null);
const stoppedEmpty = gitResult !== null && !gitResult.scaffolded;
const gitInitAttempted = !skipGitInit && !cwdHasGit && !actorDirHasGit && !stoppedEmpty;
// Outside Git, a `dockerContextDir` points above the Actor directory, which a repository there would leave out.
const gitInitAttempted = !skipGitInit && !existingGitRoot && !dockerContextDir && !actorDirHasGit && !stoppedEmpty;

if (!skipGitInit && !gitProvider) {
if (existingGitRoot) {
info({ message: `Skipped git init, because the Actor is inside the Git repository ${existingGitRoot}.` });
} else if (dockerContextDir) {
info({
message: `Skipped git init, because the Actor builds from ${cwd}. Initialize a repository there instead.`,
});
}
}

if (gitInitAttempted) {
try {
Expand All @@ -573,6 +627,8 @@ export class CreateCommand extends ApifyCommand<typeof CreateCommand> {
// Suggest install command if dependencies were not installed
const installCommandSuggestion = !dependenciesInstalled ? await getInstallCommandSuggestion(actFolderDir) : null;

const actorPath = pathFromCwd(actFolderDir);

// The Git path's clone makes it a repository too, not only `git init`.
const gitRepositoryInitialized = (gitInitAttempted && gitInitResult.success) || Boolean(actorDirHasGit);

Expand All @@ -595,7 +651,7 @@ export class CreateCommand extends ApifyCommand<typeof CreateCommand> {
actorId: gitResult.actorId,
account: gitSetup.account,
})
: buildNextSteps({ actorName, dependenciesInstalled, installCommandSuggestion, usesStandbyMode });
: buildNextSteps({ actorName, actorPath, dependenciesInstalled, installCommandSuggestion, usesStandbyMode });

const reportSuccess = !gitResult?.stopReason;

Expand Down Expand Up @@ -624,6 +680,7 @@ export class CreateCommand extends ApifyCommand<typeof CreateCommand> {
success({
message: formatCreateSuccessMessage({
actorName,
actorPath,
dependenciesInstalled,
postCreate: messages?.postCreate ?? null,
gitRepositoryInitialized,
Expand Down
2 changes: 1 addition & 1 deletion src/lib/actor-paths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ const FALLBACK_FIELDS = new Set(['readme', 'changelog']);
* Without `dockerfile`, the worker takes the first of these that exists, relative to `.actor/`; with none, it copies
* its built-in Node.js Dockerfile into the Docker context.
*/
const DEFAULT_DOCKERFILE_PATHS = ['./Dockerfile', '../Dockerfile'];
export const DEFAULT_DOCKERFILE_PATHS = ['./Dockerfile', '../Dockerfile'];

interface PathField {
field: string;
Expand Down
52 changes: 49 additions & 3 deletions src/lib/create-utils.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { readFileSync, statSync } from 'node:fs';
import { appendFile } from 'node:fs/promises';
import { join, relative, resolve } from 'node:path';

import { Separator } from '@inquirer/core';
import axios from 'axios';

import type { Manifest, Template } from '@apify/actor-templates';

import { DEFAULT_DOCKERFILE_PATHS } from './actor-paths.js';
import { ACTOR_SPECIFICATION_FOLDER } from './consts.js';
import { isOutside, realPath, toPosix } from './docker-context.js';
import type { AutomaticBuilds } from './git-source/gitSource.js';
import type { ChoicesType } from './hooks/user-confirmations/useSelectFromList.js';
import { useSelectFromList } from './hooks/user-confirmations/useSelectFromList.js';
Expand Down Expand Up @@ -81,16 +86,49 @@ export async function enhanceReadmeWithLocalSuffix(readmePath: string, manifestP
}
}

/** A Dockerfile that declares this build argument builds from the repository root, not from the Actor folder. */
const REPOSITORY_ROOT_BUILD_ARG = /^\s*ARG\s+ACTOR_PATH_IN_DOCKER_CONTEXT\b/m;

/**
* The `dockerContextDir` a new Actor needs when its Dockerfile builds from the repository root: the POSIX path from
* `.actor/` to `repositoryRoot`. Undefined when `actor.json` already sets one, when the Dockerfile builds from the Actor
* folder, or when `repositoryRoot` is the Actor folder or doesn't hold it.
*/
export function getRepositoryDockerContextDir(
actorDir: string,
config: Record<string, unknown>,
repositoryRoot: string,
): string | undefined {
if ('dockerContextDir' in config) return undefined;

const realActorDir = realPath(actorDir);
const realRoot = realPath(repositoryRoot);
const actorPath = relative(realRoot, realActorDir);
if (actorPath === '' || isOutside(actorPath)) return undefined;

const specificationDir = join(realActorDir, ACTOR_SPECIFICATION_FOLDER);
const candidates =
typeof config.dockerfile === 'string' && config.dockerfile ? [config.dockerfile] : DEFAULT_DOCKERFILE_PATHS;
const dockerfile = candidates
.map((candidate) => resolve(specificationDir, candidate))
.find((path) => statSync(path, { throwIfNoEntry: false })?.isFile());
if (!dockerfile || !REPOSITORY_ROOT_BUILD_ARG.test(readFileSync(dockerfile, 'utf-8'))) return undefined;

return toPosix(relative(specificationDir, realRoot));
}

export function buildNextSteps(params: {
actorName: string;
/** Where to `cd`, relative to the current directory. The Actor name when left out. */
actorPath?: string;
dependenciesInstalled: boolean;
installCommandSuggestion?: string | null;
/** A Server Actor serves HTTP, so a plain `apify run` gives the wrong interface. */
usesStandbyMode?: boolean;
}): string[] {
const { actorName, dependenciesInstalled, installCommandSuggestion, usesStandbyMode } = params;
const { actorName, actorPath, dependenciesInstalled, installCommandSuggestion, usesStandbyMode } = params;

const steps = [`cd "${actorName}"`];
const steps = [`cd "${actorPath ?? actorName}"`];
if (!dependenciesInstalled) {
steps.push(installCommandSuggestion || 'install dependencies with your package manager');
}
Expand All @@ -101,6 +139,7 @@ export function buildNextSteps(params: {

export function formatCreateSuccessMessage(params: {
actorName: string;
actorPath?: string;
dependenciesInstalled: boolean;
postCreate?: string | null;
gitRepositoryInitialized?: boolean;
Expand All @@ -111,6 +150,7 @@ export function formatCreateSuccessMessage(params: {
}) {
const {
actorName,
actorPath,
dependenciesInstalled,
postCreate,
gitRepositoryInitialized,
Expand All @@ -121,7 +161,13 @@ export function formatCreateSuccessMessage(params: {

let message = `✅ Actor '${actorName}' created successfully!`;

const nextSteps = buildNextSteps({ actorName, dependenciesInstalled, installCommandSuggestion, usesStandbyMode });
const nextSteps = buildNextSteps({
actorName,
actorPath,
dependenciesInstalled,
installCommandSuggestion,
usesStandbyMode,
});
message += `\n\nNext steps:\n\n${nextSteps.join('\n')}`;

if (gitRemote) {
Expand Down
10 changes: 8 additions & 2 deletions src/lib/docker-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,10 @@ export function resolveDockerContext(actorDir: string, dockerContextDir: unknown
}

// The platform's clone holds nothing above the repository root.
const repoRoot = git(realActorDir, ['rev-parse', '--show-toplevel']);
const repoRoot = findGitRoot(realActorDir);
let sourceRoot = realContextRoot;
if (repoRoot) {
sourceRoot = realPath(repoRoot);
sourceRoot = repoRoot;
if (isOutside(relative(sourceRoot, realContextRoot))) {
return {
kind: 'invalid',
Expand Down Expand Up @@ -134,6 +134,12 @@ export function realPath(path: string): string {
}
}

/** The real path of the Git work tree that holds `dir`, or undefined outside one or without git. */
export function findGitRoot(dir: string): string | undefined {
const root = git(dir, ['rev-parse', '--show-toplevel']);
return root && realPath(root);
}

export function isOutside(relativePath: string): boolean {
return isAbsolute(relativePath) || relativePath === '..' || relativePath.startsWith(`..${sep}`);
}
Expand Down
Loading
Loading