first commit
Security: Sync from Public / sync-from-public (push) Has been cancelled
Test: Benchmark Nightly / build (push) Has been cancelled
Test: Benchmark Nightly / Notify Cats on failure (push) Has been cancelled
CI: Python / Checks (push) Has been cancelled
Test: Evals Python / Workflow Comparison Python (push) Has been cancelled
Util: Check Docs URLs / check-docs-urls (push) Has been cancelled
Test: Visual Storybook / Cloudflare Pages (push) Has been cancelled
Test: E2E Performance / build-and-test-performance (push) Has been cancelled
Test: Workflows Nightly / Run Workflow Tests (push) Has been cancelled
Util: Cleanup CI Docker Images / Delete stale CI images (push) Has been cancelled
Test: Benchmark Destroy Env / build (push) Has been cancelled
Util: Update Node Popularity / update-popularity (push) Has been cancelled
Test: E2E Coverage Weekly / Coverage Tests (push) Has been cancelled
Security: Sync from Public / sync-from-public (push) Has been cancelled
Test: Benchmark Nightly / build (push) Has been cancelled
Test: Benchmark Nightly / Notify Cats on failure (push) Has been cancelled
CI: Python / Checks (push) Has been cancelled
Test: Evals Python / Workflow Comparison Python (push) Has been cancelled
Util: Check Docs URLs / check-docs-urls (push) Has been cancelled
Test: Visual Storybook / Cloudflare Pages (push) Has been cancelled
Test: E2E Performance / build-and-test-performance (push) Has been cancelled
Test: Workflows Nightly / Run Workflow Tests (push) Has been cancelled
Util: Cleanup CI Docker Images / Delete stale CI images (push) Has been cancelled
Test: Benchmark Destroy Env / build (push) Has been cancelled
Util: Update Node Popularity / update-popularity (push) Has been cancelled
Test: E2E Coverage Weekly / Coverage Tests (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
import type { INode } from 'n8n-workflow';
|
||||
import { NodeOperationError } from 'n8n-workflow';
|
||||
import type { ConfigListSummary } from 'simple-git';
|
||||
|
||||
/**
|
||||
* Validates a git reference to prevent command injection attacks
|
||||
* @param reference - The git reference to validate (e.g., branch name, HEAD, refs/heads/main)
|
||||
* @param node - The node instance for error throwing
|
||||
* @throws {NodeOperationError} If the reference contains unsafe characters or patterns
|
||||
*/
|
||||
export function validateGitReference(reference: string, node: INode): void {
|
||||
// Allow only safe characters: alphanumeric, /, @, {, }, ., -, _, :
|
||||
const safeReferencePattern = /^[a-zA-Z0-9/@{}._:-]+$/;
|
||||
|
||||
if (!safeReferencePattern.test(reference)) {
|
||||
throw new NodeOperationError(
|
||||
node,
|
||||
'Invalid reference format. Reference contains unsafe characters. Only alphanumeric characters and /@{}._:- are allowed',
|
||||
);
|
||||
}
|
||||
|
||||
// Prevent argument injection by blocking references starting with -
|
||||
if (reference.startsWith('-')) {
|
||||
throw new NodeOperationError(
|
||||
node,
|
||||
'Invalid reference format. Reference cannot start with a hyphen',
|
||||
);
|
||||
}
|
||||
|
||||
// Prevent path traversal attempts
|
||||
if (reference.includes('..')) {
|
||||
throw new NodeOperationError(node, 'Invalid reference format. Reference cannot contain ".."');
|
||||
}
|
||||
|
||||
// Prevent control characters that could be used for injection
|
||||
// eslint-disable-next-line no-control-regex
|
||||
if (/[\x00-\x1f\x7f]/.test(reference)) {
|
||||
throw new NodeOperationError(
|
||||
node,
|
||||
'Invalid reference format. Reference cannot contain control characters',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const REMOTE_ORIGIN_URL_KEY = 'remote.origin.url';
|
||||
|
||||
const REMOTE_ORIGIN_PUSH_URL_KEY = 'remote.origin.pushurl';
|
||||
|
||||
function sanitizeUrl(url: string): string {
|
||||
const urlObj = new URL(url);
|
||||
urlObj.username = '';
|
||||
urlObj.password = '';
|
||||
return urlObj.toString();
|
||||
}
|
||||
|
||||
export function mapGitConfigList(config: ConfigListSummary) {
|
||||
const data = [];
|
||||
for (const fileName of Object.keys(config.values)) {
|
||||
let remoteOriginUrl = config.values[fileName][REMOTE_ORIGIN_URL_KEY];
|
||||
if (remoteOriginUrl) {
|
||||
if (Array.isArray(remoteOriginUrl)) {
|
||||
remoteOriginUrl = remoteOriginUrl.map(sanitizeUrl);
|
||||
} else {
|
||||
remoteOriginUrl = sanitizeUrl(remoteOriginUrl);
|
||||
}
|
||||
}
|
||||
|
||||
let remoteOriginPushUrl = config.values[fileName][REMOTE_ORIGIN_PUSH_URL_KEY];
|
||||
if (remoteOriginPushUrl) {
|
||||
if (Array.isArray(remoteOriginPushUrl)) {
|
||||
remoteOriginPushUrl = remoteOriginPushUrl.map(sanitizeUrl);
|
||||
} else {
|
||||
remoteOriginPushUrl = sanitizeUrl(remoteOriginPushUrl);
|
||||
}
|
||||
}
|
||||
|
||||
data.push({
|
||||
_file: fileName,
|
||||
...config.values[fileName],
|
||||
[REMOTE_ORIGIN_URL_KEY]: remoteOriginUrl,
|
||||
[REMOTE_ORIGIN_PUSH_URL_KEY]: remoteOriginPushUrl,
|
||||
});
|
||||
}
|
||||
return data;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"node": "n8n-nodes-base.git",
|
||||
"nodeVersion": "1.0",
|
||||
"codexVersion": "1.0",
|
||||
"categories": ["Core Nodes", "Development"],
|
||||
"resources": {
|
||||
"credentialDocumentation": [
|
||||
{
|
||||
"url": "https://docs.n8n.io/integrations/builtin/credentials/git/"
|
||||
}
|
||||
],
|
||||
"primaryDocumentation": [
|
||||
{
|
||||
"url": "https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.git/"
|
||||
}
|
||||
]
|
||||
},
|
||||
"subcategories": ["Helpers"]
|
||||
}
|
||||
@@ -0,0 +1,738 @@
|
||||
import { DeploymentConfig, SecurityConfig } from '@n8n/config';
|
||||
import { Container } from '@n8n/di';
|
||||
import { access, mkdir } from 'fs/promises';
|
||||
import type {
|
||||
IExecuteFunctions,
|
||||
INodeExecutionData,
|
||||
INodeType,
|
||||
INodeTypeDescription,
|
||||
} from 'n8n-workflow';
|
||||
import {
|
||||
NodeConnectionTypes,
|
||||
NodeOperationError,
|
||||
assertParamIsBoolean,
|
||||
assertParamIsString,
|
||||
} from 'n8n-workflow';
|
||||
import type { LogOptions, SimpleGit, SimpleGitOptions } from 'simple-git';
|
||||
import simpleGit from 'simple-git';
|
||||
import { URL } from 'url';
|
||||
|
||||
import {
|
||||
addConfigFields,
|
||||
addFields,
|
||||
ALLOWED_CONFIG_KEYS,
|
||||
cloneFields,
|
||||
commitFields,
|
||||
logFields,
|
||||
pushFields,
|
||||
reflogFields,
|
||||
switchBranchFields,
|
||||
tagFields,
|
||||
} from './descriptions';
|
||||
import { mapGitConfigList, validateGitReference } from './GenericFunctions';
|
||||
|
||||
export class Git implements INodeType {
|
||||
description: INodeTypeDescription = {
|
||||
displayName: 'Git',
|
||||
name: 'git',
|
||||
icon: 'file:git.svg',
|
||||
group: ['transform'],
|
||||
version: [1, 1.1],
|
||||
description: 'Control git.',
|
||||
defaults: {
|
||||
name: 'Git',
|
||||
},
|
||||
usableAsTool: true,
|
||||
inputs: [NodeConnectionTypes.Main],
|
||||
outputs: [NodeConnectionTypes.Main],
|
||||
credentials: [
|
||||
{
|
||||
name: 'gitPassword',
|
||||
required: true,
|
||||
displayOptions: {
|
||||
show: {
|
||||
authentication: ['gitPassword'],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
properties: [
|
||||
{
|
||||
displayName: 'Authentication',
|
||||
name: 'authentication',
|
||||
type: 'options',
|
||||
options: [
|
||||
{
|
||||
name: 'Authenticate',
|
||||
value: 'gitPassword',
|
||||
},
|
||||
{
|
||||
name: 'None',
|
||||
value: 'none',
|
||||
},
|
||||
],
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['clone', 'push'],
|
||||
},
|
||||
},
|
||||
default: 'none',
|
||||
description: 'The way to authenticate',
|
||||
},
|
||||
{
|
||||
displayName: 'Operation',
|
||||
name: 'operation',
|
||||
type: 'options',
|
||||
noDataExpression: true,
|
||||
default: 'log',
|
||||
options: [
|
||||
{
|
||||
name: 'Add',
|
||||
value: 'add',
|
||||
description: 'Add a file or folder to commit',
|
||||
action: 'Add a file or folder to commit',
|
||||
},
|
||||
{
|
||||
name: 'Add Config',
|
||||
value: 'addConfig',
|
||||
description: 'Add configuration property',
|
||||
action: 'Add configuration property',
|
||||
},
|
||||
{
|
||||
name: 'Clone',
|
||||
value: 'clone',
|
||||
description: 'Clone a repository',
|
||||
action: 'Clone a repository',
|
||||
},
|
||||
{
|
||||
name: 'Commit',
|
||||
value: 'commit',
|
||||
description: 'Commit files or folders to git',
|
||||
action: 'Commit files or folders to git',
|
||||
},
|
||||
{
|
||||
name: 'Fetch',
|
||||
value: 'fetch',
|
||||
description: 'Fetch from remote repository',
|
||||
action: 'Fetch from remote repository',
|
||||
},
|
||||
{
|
||||
name: 'List Config',
|
||||
value: 'listConfig',
|
||||
description: 'Return current configuration',
|
||||
action: 'Return current configuration',
|
||||
},
|
||||
{
|
||||
name: 'Log',
|
||||
value: 'log',
|
||||
description: 'Return git commit history',
|
||||
action: 'Return git commit history',
|
||||
},
|
||||
{
|
||||
name: 'Pull',
|
||||
value: 'pull',
|
||||
description: 'Pull from remote repository',
|
||||
action: 'Pull from remote repository',
|
||||
},
|
||||
{
|
||||
name: 'Push',
|
||||
value: 'push',
|
||||
description: 'Push to remote repository',
|
||||
action: 'Push to remote repository',
|
||||
},
|
||||
{
|
||||
name: 'Push Tags',
|
||||
value: 'pushTags',
|
||||
description: 'Push Tags to remote repository',
|
||||
action: 'Push tags to remote repository',
|
||||
},
|
||||
{
|
||||
name: 'Reflog',
|
||||
value: 'reflog',
|
||||
description: 'Return reference log',
|
||||
action: 'Return reference log',
|
||||
},
|
||||
{
|
||||
name: 'Status',
|
||||
value: 'status',
|
||||
description: 'Return status of current repository',
|
||||
action: 'Return status of current repository',
|
||||
},
|
||||
{
|
||||
name: 'Switch Branch',
|
||||
value: 'switchBranch',
|
||||
description: 'Switch to a different branch',
|
||||
action: 'Switch to a different branch',
|
||||
},
|
||||
{
|
||||
name: 'Tag',
|
||||
value: 'tag',
|
||||
description: 'Create a new tag',
|
||||
action: 'Create a new tag',
|
||||
},
|
||||
{
|
||||
name: 'User Setup',
|
||||
value: 'userSetup',
|
||||
description: 'Set the user',
|
||||
action: 'Set up a user',
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
{
|
||||
displayName: 'Repository Path',
|
||||
name: 'repositoryPath',
|
||||
type: 'string',
|
||||
displayOptions: {
|
||||
hide: {
|
||||
operation: ['clone'],
|
||||
},
|
||||
},
|
||||
default: '',
|
||||
placeholder: '/tmp/repository',
|
||||
required: true,
|
||||
description: 'Local path of the git repository to operate on',
|
||||
},
|
||||
{
|
||||
displayName: 'New Repository Path',
|
||||
name: 'repositoryPath',
|
||||
type: 'string',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['clone'],
|
||||
},
|
||||
},
|
||||
default: '',
|
||||
placeholder: '/tmp/repository',
|
||||
required: true,
|
||||
description: 'Local path to which the git repository should be cloned into',
|
||||
},
|
||||
|
||||
...addFields,
|
||||
...addConfigFields,
|
||||
...cloneFields,
|
||||
...commitFields,
|
||||
...logFields,
|
||||
...pushFields,
|
||||
...reflogFields,
|
||||
...switchBranchFields,
|
||||
...tagFields,
|
||||
// ...userSetupFields,
|
||||
],
|
||||
};
|
||||
|
||||
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
|
||||
const items = this.getInputData();
|
||||
|
||||
const prepareRepository = async (repositoryPath: string): Promise<string> => {
|
||||
const authentication = this.getNodeParameter('authentication', 0) as string;
|
||||
|
||||
if (authentication === 'gitPassword') {
|
||||
const gitCredentials = await this.getCredentials('gitPassword');
|
||||
|
||||
const url = new URL(repositoryPath);
|
||||
url.username = gitCredentials.username as string;
|
||||
url.password = gitCredentials.password as string;
|
||||
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
return repositoryPath;
|
||||
};
|
||||
|
||||
interface CheckoutBranchOptions {
|
||||
branchName: string;
|
||||
createBranch?: boolean;
|
||||
startPoint?: string;
|
||||
force?: boolean;
|
||||
setUpstream?: boolean;
|
||||
remoteName?: string;
|
||||
}
|
||||
|
||||
const checkoutBranch = async (
|
||||
git: SimpleGit,
|
||||
options: CheckoutBranchOptions,
|
||||
): Promise<void> => {
|
||||
const {
|
||||
branchName,
|
||||
createBranch = true,
|
||||
startPoint,
|
||||
force = false,
|
||||
setUpstream = false,
|
||||
remoteName = 'origin',
|
||||
} = options;
|
||||
try {
|
||||
if (force) {
|
||||
await git.checkout(['-f', branchName]);
|
||||
} else {
|
||||
await git.checkout(branchName);
|
||||
}
|
||||
} catch (error) {
|
||||
if (createBranch) {
|
||||
// Try to create the branch when checkout fails
|
||||
if (startPoint) {
|
||||
await git.checkoutBranch(branchName, startPoint);
|
||||
} else {
|
||||
await git.checkoutLocalBranch(branchName);
|
||||
}
|
||||
// If we reach here, branch creation succeeded
|
||||
} else {
|
||||
// Don't create branch, throw original error
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (setUpstream) {
|
||||
try {
|
||||
await git.addConfig(`branch.${branchName}.remote`, remoteName);
|
||||
await git.addConfig(`branch.${branchName}.merge`, `refs/heads/${branchName}`);
|
||||
} catch (upstreamError) {
|
||||
// Upstream setup failed but that's non-fatal
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const operation = this.getNodeParameter('operation', 0);
|
||||
const returnItems: INodeExecutionData[] = [];
|
||||
for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
|
||||
try {
|
||||
const repositoryPath = this.getNodeParameter('repositoryPath', itemIndex, '') as string;
|
||||
const resolvedRepositoryPath = await this.helpers.resolvePath(repositoryPath);
|
||||
const isFilePathBlocked = this.helpers.isFilePathBlocked(resolvedRepositoryPath);
|
||||
if (isFilePathBlocked) {
|
||||
throw new NodeOperationError(
|
||||
this.getNode(),
|
||||
'Access to the repository path is not allowed',
|
||||
);
|
||||
}
|
||||
|
||||
const options = this.getNodeParameter('options', itemIndex, {});
|
||||
|
||||
if (operation === 'clone') {
|
||||
// Create repository folder if it does not exist
|
||||
try {
|
||||
await access(resolvedRepositoryPath);
|
||||
} catch (error) {
|
||||
await mkdir(resolvedRepositoryPath);
|
||||
}
|
||||
}
|
||||
|
||||
const gitConfig: string[] = [];
|
||||
const deploymentConfig = Container.get(DeploymentConfig);
|
||||
const isCloud = deploymentConfig.type === 'cloud';
|
||||
const securityConfig = Container.get(SecurityConfig);
|
||||
const disableBareRepos = securityConfig.disableBareRepos;
|
||||
if (isCloud || disableBareRepos) {
|
||||
gitConfig.push('safe.bareRepository=explicit');
|
||||
}
|
||||
|
||||
const enableHooks = securityConfig.enableGitNodeHooks;
|
||||
if (!enableHooks) {
|
||||
gitConfig.push('core.hooksPath=/dev/null');
|
||||
}
|
||||
|
||||
const gitOptions: Partial<SimpleGitOptions> = {
|
||||
baseDir: resolvedRepositoryPath,
|
||||
config: gitConfig,
|
||||
};
|
||||
|
||||
const git: SimpleGit = simpleGit(gitOptions)
|
||||
// Tell git not to ask for any information via the terminal like for
|
||||
// example the username. As nobody will be able to answer it would
|
||||
// n8n keep on waiting forever.
|
||||
.env('GIT_TERMINAL_PROMPT', '0');
|
||||
|
||||
if (operation === 'add') {
|
||||
// ----------------------------------
|
||||
// add
|
||||
// ----------------------------------
|
||||
|
||||
const pathsToAdd = this.getNodeParameter('pathsToAdd', itemIndex, '') as string;
|
||||
const paths = pathsToAdd
|
||||
.split(',')
|
||||
.map((p) => p.trim())
|
||||
.filter((p) => p.length > 0);
|
||||
|
||||
// Use -- separator to prevent argument injection
|
||||
await git.add(['--', ...paths]);
|
||||
|
||||
returnItems.push({
|
||||
json: {
|
||||
success: true,
|
||||
},
|
||||
pairedItem: {
|
||||
item: itemIndex,
|
||||
},
|
||||
});
|
||||
} else if (operation === 'addConfig') {
|
||||
// ----------------------------------
|
||||
// addConfig
|
||||
// ----------------------------------
|
||||
|
||||
const key = this.getNodeParameter('key', itemIndex, '') as string;
|
||||
const value = this.getNodeParameter('value', itemIndex, '') as string;
|
||||
const securityConfig = Container.get(SecurityConfig);
|
||||
const enableGitNodeAllConfigKeys = securityConfig.enableGitNodeAllConfigKeys;
|
||||
let append = false;
|
||||
if (!enableGitNodeAllConfigKeys && !ALLOWED_CONFIG_KEYS.includes(key)) {
|
||||
throw new NodeOperationError(
|
||||
this.getNode(),
|
||||
`The provided git config key '${key}' is not allowed`,
|
||||
);
|
||||
}
|
||||
|
||||
if (options.mode === 'append') {
|
||||
append = true;
|
||||
}
|
||||
|
||||
await git.addConfig(key, value, append);
|
||||
returnItems.push({
|
||||
json: {
|
||||
success: true,
|
||||
},
|
||||
pairedItem: {
|
||||
item: itemIndex,
|
||||
},
|
||||
});
|
||||
} else if (operation === 'clone') {
|
||||
// ----------------------------------
|
||||
// clone
|
||||
// ----------------------------------
|
||||
|
||||
let sourceRepository = this.getNodeParameter('sourceRepository', itemIndex, '') as string;
|
||||
sourceRepository = await prepareRepository(sourceRepository);
|
||||
|
||||
await git.clone(sourceRepository, '.');
|
||||
|
||||
returnItems.push({
|
||||
json: {
|
||||
success: true,
|
||||
},
|
||||
pairedItem: {
|
||||
item: itemIndex,
|
||||
},
|
||||
});
|
||||
} else if (operation === 'commit') {
|
||||
// ----------------------------------
|
||||
// commit
|
||||
// ----------------------------------
|
||||
|
||||
const message = this.getNodeParameter('message', itemIndex, '') as string;
|
||||
const branch = options.branch;
|
||||
if (branch !== undefined && branch !== '') {
|
||||
assertParamIsString('branch', branch, this.getNode());
|
||||
await checkoutBranch(git, {
|
||||
branchName: branch,
|
||||
setUpstream: true,
|
||||
});
|
||||
}
|
||||
|
||||
let pathsToAdd: string[] | undefined = undefined;
|
||||
if (options.files !== undefined) {
|
||||
pathsToAdd = (options.pathsToAdd as string)
|
||||
.split(',')
|
||||
.map((p) => p.trim())
|
||||
.filter((p) => p.length > 0);
|
||||
}
|
||||
|
||||
// Use -- separator to prevent argument injection
|
||||
if (pathsToAdd && pathsToAdd.length > 0) {
|
||||
await git.commit(message, ['--', ...pathsToAdd]);
|
||||
} else {
|
||||
await git.commit(message);
|
||||
}
|
||||
|
||||
returnItems.push({
|
||||
json: {
|
||||
success: true,
|
||||
},
|
||||
pairedItem: {
|
||||
item: itemIndex,
|
||||
},
|
||||
});
|
||||
} else if (operation === 'fetch') {
|
||||
// ----------------------------------
|
||||
// fetch
|
||||
// ----------------------------------
|
||||
|
||||
await git.fetch();
|
||||
returnItems.push({
|
||||
json: {
|
||||
success: true,
|
||||
},
|
||||
pairedItem: {
|
||||
item: itemIndex,
|
||||
},
|
||||
});
|
||||
} else if (operation === 'log') {
|
||||
// ----------------------------------
|
||||
// log
|
||||
// ----------------------------------
|
||||
|
||||
const logOptions: LogOptions = {};
|
||||
|
||||
const returnAll = this.getNodeParameter('returnAll', itemIndex, false);
|
||||
if (!returnAll) {
|
||||
logOptions.maxCount = this.getNodeParameter('limit', itemIndex, 100);
|
||||
}
|
||||
if (options.file) {
|
||||
logOptions.file = options.file as string;
|
||||
}
|
||||
|
||||
const log = await git.log(logOptions);
|
||||
|
||||
returnItems.push(
|
||||
// @ts-ignore
|
||||
...this.helpers.returnJsonArray(log.all).map((item) => {
|
||||
return {
|
||||
...item,
|
||||
pairedItem: { item: itemIndex },
|
||||
};
|
||||
}),
|
||||
);
|
||||
} else if (operation === 'pull') {
|
||||
// ----------------------------------
|
||||
// pull
|
||||
// ----------------------------------
|
||||
|
||||
await git.pull();
|
||||
returnItems.push({
|
||||
json: {
|
||||
success: true,
|
||||
},
|
||||
pairedItem: {
|
||||
item: itemIndex,
|
||||
},
|
||||
});
|
||||
} else if (operation === 'push') {
|
||||
// ----------------------------------
|
||||
// push
|
||||
// ----------------------------------
|
||||
|
||||
const branch = options.branch;
|
||||
if (branch !== undefined && branch !== '') {
|
||||
assertParamIsString('branch', branch, this.getNode());
|
||||
await checkoutBranch(git, {
|
||||
branchName: branch,
|
||||
createBranch: false,
|
||||
setUpstream: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (options.repository) {
|
||||
const targetRepository = await prepareRepository(options.targetRepository as string);
|
||||
await git.push(targetRepository);
|
||||
} else {
|
||||
const authentication = this.getNodeParameter('authentication', 0) as string;
|
||||
if (authentication === 'gitPassword') {
|
||||
// Try to get remote repository path from git repository itself to add
|
||||
// authentication data
|
||||
const config = await git.listConfig();
|
||||
let targetRepository;
|
||||
for (const fileName of Object.keys(config.values)) {
|
||||
if (config.values[fileName]['remote.origin.url']) {
|
||||
targetRepository = config.values[fileName]['remote.origin.url'];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
targetRepository = await prepareRepository(targetRepository as string);
|
||||
await git.push(targetRepository);
|
||||
} else {
|
||||
await git.push();
|
||||
}
|
||||
}
|
||||
|
||||
returnItems.push({
|
||||
json: {
|
||||
success: true,
|
||||
},
|
||||
pairedItem: {
|
||||
item: itemIndex,
|
||||
},
|
||||
});
|
||||
} else if (operation === 'pushTags') {
|
||||
// ----------------------------------
|
||||
// pushTags
|
||||
// ----------------------------------
|
||||
|
||||
await git.pushTags();
|
||||
returnItems.push({
|
||||
json: {
|
||||
success: true,
|
||||
},
|
||||
pairedItem: {
|
||||
item: itemIndex,
|
||||
},
|
||||
});
|
||||
} else if (operation === 'reflog') {
|
||||
// ----------------------------------
|
||||
// reflog
|
||||
// ----------------------------------
|
||||
|
||||
const returnAll = this.getNodeParameter('returnAll', itemIndex, false);
|
||||
|
||||
let reference = 'HEAD';
|
||||
if (options.reference !== undefined && options.reference !== '') {
|
||||
assertParamIsString('reference', options.reference, this.getNode());
|
||||
validateGitReference(options.reference, this.getNode());
|
||||
|
||||
reference = options.reference;
|
||||
}
|
||||
|
||||
const reflogResult = await git.raw(['reflog', reference]);
|
||||
|
||||
const reflogEntries = reflogResult
|
||||
.trim()
|
||||
.split('\n')
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => {
|
||||
// reflog format: hash ref@{number}: action: message
|
||||
const match = line.match(/^(\S+)\s+(.+?):\s+(.+?):\s+(.+)$/);
|
||||
if (match) {
|
||||
return {
|
||||
hash: match[1],
|
||||
ref: match[2],
|
||||
action: match[3],
|
||||
message: match[4],
|
||||
raw: line,
|
||||
};
|
||||
}
|
||||
return {
|
||||
raw: line,
|
||||
};
|
||||
});
|
||||
|
||||
const entries = returnAll
|
||||
? reflogEntries
|
||||
: reflogEntries.slice(0, this.getNodeParameter('limit', itemIndex, 100));
|
||||
|
||||
returnItems.push.apply(
|
||||
returnItems,
|
||||
this.helpers.returnJsonArray(entries).map((item) => {
|
||||
return {
|
||||
...item,
|
||||
pairedItem: { item: itemIndex },
|
||||
};
|
||||
}),
|
||||
);
|
||||
} else if (operation === 'listConfig') {
|
||||
// ----------------------------------
|
||||
// listConfig
|
||||
// ----------------------------------
|
||||
|
||||
const config = await git.listConfig();
|
||||
|
||||
const data = mapGitConfigList(config);
|
||||
|
||||
returnItems.push(
|
||||
...this.helpers.returnJsonArray(data).map((item) => {
|
||||
return {
|
||||
...item,
|
||||
pairedItem: { item: itemIndex },
|
||||
};
|
||||
}),
|
||||
);
|
||||
} else if (operation === 'status') {
|
||||
// ----------------------------------
|
||||
// status
|
||||
// ----------------------------------
|
||||
|
||||
const status = await git.status();
|
||||
|
||||
returnItems.push(
|
||||
// @ts-ignore
|
||||
...this.helpers.returnJsonArray([status]).map((item) => {
|
||||
return {
|
||||
...item,
|
||||
pairedItem: { item: itemIndex },
|
||||
};
|
||||
}),
|
||||
);
|
||||
} else if (operation === 'switchBranch') {
|
||||
// ----------------------------------
|
||||
// switchBranch
|
||||
// ----------------------------------
|
||||
|
||||
const branchName = this.getNodeParameter('branchName', itemIndex);
|
||||
assertParamIsString('branchName', branchName, this.getNode());
|
||||
|
||||
const createBranch = options.createBranch;
|
||||
if (createBranch !== undefined) {
|
||||
assertParamIsBoolean('createBranch', createBranch, this.getNode());
|
||||
}
|
||||
const remoteName =
|
||||
typeof options.remoteName === 'string' && options.remoteName
|
||||
? options.remoteName
|
||||
: 'origin';
|
||||
|
||||
const startPoint = options.startPoint;
|
||||
if (startPoint !== undefined) {
|
||||
assertParamIsString('startPoint', startPoint, this.getNode());
|
||||
}
|
||||
|
||||
const setUpstream = options.setUpstream;
|
||||
if (setUpstream !== undefined) {
|
||||
assertParamIsBoolean('setUpstream', setUpstream, this.getNode());
|
||||
}
|
||||
|
||||
const force = options.force;
|
||||
if (force !== undefined) {
|
||||
assertParamIsBoolean('force', force, this.getNode());
|
||||
}
|
||||
|
||||
await checkoutBranch(git, {
|
||||
branchName,
|
||||
createBranch,
|
||||
startPoint,
|
||||
force,
|
||||
setUpstream,
|
||||
remoteName,
|
||||
});
|
||||
|
||||
returnItems.push({
|
||||
json: {
|
||||
success: true,
|
||||
branch: branchName,
|
||||
},
|
||||
pairedItem: {
|
||||
item: itemIndex,
|
||||
},
|
||||
});
|
||||
} else if (operation === 'tag') {
|
||||
// ----------------------------------
|
||||
// tag
|
||||
// ----------------------------------
|
||||
|
||||
const name = this.getNodeParameter('name', itemIndex, '') as string;
|
||||
|
||||
await git.addTag(name);
|
||||
returnItems.push({
|
||||
json: {
|
||||
success: true,
|
||||
},
|
||||
pairedItem: {
|
||||
item: itemIndex,
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (this.continueOnFail()) {
|
||||
returnItems.push({
|
||||
json: {
|
||||
error: error.toString(),
|
||||
},
|
||||
pairedItem: {
|
||||
item: itemIndex,
|
||||
},
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
return [returnItems];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { mockDeep } from 'jest-mock-extended';
|
||||
import type { ConfigListSummary } from 'simple-git';
|
||||
|
||||
import { mapGitConfigList } from '../GenericFunctions';
|
||||
|
||||
describe('GenericFunctions', () => {
|
||||
describe('mapGitConfigList', () => {
|
||||
it('should map the git config list', () => {
|
||||
const config = mockDeep<ConfigListSummary>({
|
||||
values: {
|
||||
'.git/config': {
|
||||
'user.name': 'test',
|
||||
'core.autocrlf': 'true',
|
||||
'remote.origin.url': undefined,
|
||||
'remote.origin.pushurl': undefined,
|
||||
},
|
||||
'/other/config': {
|
||||
'user.name': 'other',
|
||||
'core.autocrlf': 'false',
|
||||
'remote.origin.url': undefined,
|
||||
'remote.origin.pushurl': undefined,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = mapGitConfigList(config);
|
||||
|
||||
expect(result).toEqual([
|
||||
{
|
||||
_file: '.git/config',
|
||||
'user.name': 'test',
|
||||
'core.autocrlf': 'true',
|
||||
},
|
||||
{
|
||||
_file: '/other/config',
|
||||
'user.name': 'other',
|
||||
'core.autocrlf': 'false',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should sanitize the remote origin url', () => {
|
||||
const config = mockDeep<ConfigListSummary>({
|
||||
values: {
|
||||
'.git/config': {
|
||||
'remote.origin.url': 'https://user:password@github.com/test/test.git',
|
||||
'remote.origin.pushurl': undefined,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = mapGitConfigList(config);
|
||||
|
||||
expect(result).toEqual([
|
||||
{
|
||||
_file: '.git/config',
|
||||
'remote.origin.url': 'https://github.com/test/test.git',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should sanitize the remote origin urls', () => {
|
||||
const config = mockDeep<ConfigListSummary>({
|
||||
values: {
|
||||
'.git/config': {
|
||||
'remote.origin.url': [
|
||||
'https://user:password@github.com/test/test.git',
|
||||
'https://user:password@github.com/test/other.git',
|
||||
],
|
||||
'remote.origin.pushurl': undefined,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = mapGitConfigList(config);
|
||||
|
||||
expect(result).toEqual([
|
||||
{
|
||||
_file: '.git/config',
|
||||
'remote.origin.url': [
|
||||
'https://github.com/test/test.git',
|
||||
'https://github.com/test/other.git',
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should sanitize the remote origin push url', () => {
|
||||
const config = mockDeep<ConfigListSummary>({
|
||||
values: {
|
||||
'.git/config': {
|
||||
'remote.origin.pushurl': 'https://user:password@github.com/test/test.git',
|
||||
'remote.origin.url': undefined,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = mapGitConfigList(config);
|
||||
|
||||
expect(result).toEqual([
|
||||
{
|
||||
_file: '.git/config',
|
||||
'remote.origin.pushurl': 'https://github.com/test/test.git',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should sanitize the remote origin push urls', () => {
|
||||
const config = mockDeep<ConfigListSummary>({
|
||||
values: {
|
||||
'.git/config': {
|
||||
'remote.origin.pushurl': [
|
||||
'https://user:password@github.com/test/test.git',
|
||||
'https://user:password@github.com/test/other.git',
|
||||
],
|
||||
'remote.origin.url': undefined,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = mapGitConfigList(config);
|
||||
|
||||
expect(result).toEqual([
|
||||
{
|
||||
_file: '.git/config',
|
||||
'remote.origin.pushurl': [
|
||||
'https://github.com/test/test.git',
|
||||
'https://github.com/test/other.git',
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,186 @@
|
||||
import { DeploymentConfig, SecurityConfig } from '@n8n/config';
|
||||
import { Container } from '@n8n/di';
|
||||
import { mock } from 'jest-mock-extended';
|
||||
import type { IExecuteFunctions } from 'n8n-workflow';
|
||||
import type { SimpleGit } from 'simple-git';
|
||||
import simpleGit from 'simple-git';
|
||||
|
||||
import { Git } from '../Git.node';
|
||||
|
||||
const mockGit = {
|
||||
log: jest.fn(),
|
||||
env: jest.fn().mockReturnThis(),
|
||||
};
|
||||
|
||||
jest.mock('simple-git');
|
||||
const mockSimpleGit = simpleGit as jest.MockedFunction<typeof simpleGit>;
|
||||
mockSimpleGit.mockReturnValue(mockGit as unknown as SimpleGit);
|
||||
|
||||
describe('Git Node', () => {
|
||||
let gitNode: Git;
|
||||
let executeFunctions: jest.Mocked<IExecuteFunctions>;
|
||||
let deploymentConfig: jest.Mocked<DeploymentConfig>;
|
||||
let securityConfig: jest.Mocked<SecurityConfig>;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
deploymentConfig = mock<DeploymentConfig>({
|
||||
type: 'default',
|
||||
});
|
||||
securityConfig = mock<SecurityConfig>({
|
||||
disableBareRepos: false,
|
||||
enableGitNodeHooks: true,
|
||||
});
|
||||
Container.set(DeploymentConfig, deploymentConfig);
|
||||
Container.set(SecurityConfig, securityConfig);
|
||||
|
||||
executeFunctions = mock<IExecuteFunctions>({
|
||||
getInputData: jest.fn().mockReturnValue([{ json: {} }]),
|
||||
getNodeParameter: jest.fn(),
|
||||
helpers: {
|
||||
isFilePathBlocked: jest.fn(),
|
||||
returnJsonArray: jest
|
||||
.fn()
|
||||
.mockImplementation((data: unknown[]) => data.map((item: unknown) => ({ json: item }))),
|
||||
},
|
||||
});
|
||||
executeFunctions.getNodeParameter.mockImplementation((name: string) => {
|
||||
switch (name) {
|
||||
case 'operation':
|
||||
return 'log';
|
||||
case 'repositoryPath':
|
||||
return '/tmp/test-repo';
|
||||
case 'options':
|
||||
return {};
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
});
|
||||
|
||||
mockGit.log.mockResolvedValue({ all: [] });
|
||||
|
||||
gitNode = new Git();
|
||||
});
|
||||
|
||||
describe('Bare Repository Configuration', () => {
|
||||
it('should add safe.bareRepository=explicit when deployment type is cloud', async () => {
|
||||
deploymentConfig.type = 'cloud';
|
||||
securityConfig.disableBareRepos = false;
|
||||
|
||||
await gitNode.execute.call(executeFunctions);
|
||||
|
||||
expect(mockSimpleGit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
config: ['safe.bareRepository=explicit'],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should add safe.bareRepository=explicit when disableBareRepos is true', async () => {
|
||||
deploymentConfig.type = 'default';
|
||||
securityConfig.disableBareRepos = true;
|
||||
|
||||
await gitNode.execute.call(executeFunctions);
|
||||
|
||||
expect(mockSimpleGit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
config: ['safe.bareRepository=explicit'],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should add safe.bareRepository=explicit when both cloud and disableBareRepos are true', async () => {
|
||||
deploymentConfig.type = 'cloud';
|
||||
securityConfig.disableBareRepos = true;
|
||||
|
||||
await gitNode.execute.call(executeFunctions);
|
||||
|
||||
expect(mockSimpleGit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
config: ['safe.bareRepository=explicit'],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should not add safe.bareRepository=explicit when neither cloud nor disableBareRepos is true', async () => {
|
||||
deploymentConfig.type = 'default';
|
||||
securityConfig.disableBareRepos = false;
|
||||
|
||||
await gitNode.execute.call(executeFunctions);
|
||||
|
||||
expect(mockSimpleGit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
config: [],
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Hooks Configuration', () => {
|
||||
it('should add core.hooksPath=/dev/null when enableGitNodeHooks is false', async () => {
|
||||
securityConfig.enableGitNodeHooks = false;
|
||||
|
||||
await gitNode.execute.call(executeFunctions);
|
||||
|
||||
expect(mockSimpleGit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
config: ['core.hooksPath=/dev/null'],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should not add core.hooksPath=/dev/null when enableGitNodeHooks is true', async () => {
|
||||
securityConfig.enableGitNodeHooks = true;
|
||||
|
||||
await gitNode.execute.call(executeFunctions);
|
||||
|
||||
expect(mockSimpleGit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
config: [],
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Restricted file paths', () => {
|
||||
it('should throw an error if the repository path is blocked', async () => {
|
||||
(executeFunctions.helpers.isFilePathBlocked as jest.Mock).mockReturnValue(true);
|
||||
(executeFunctions.helpers.resolvePath as jest.Mock).mockResolvedValue('/tmp/test-repo');
|
||||
|
||||
await expect(gitNode.execute.call(executeFunctions)).rejects.toThrow(
|
||||
'Access to the repository path is not allowed',
|
||||
);
|
||||
});
|
||||
|
||||
it('should use the resolved repository path for git operations', async () => {
|
||||
const originalPath = '/tmp/link-to-repo';
|
||||
const resolvedPath = '/tmp/actual-repo';
|
||||
|
||||
executeFunctions.getNodeParameter.mockImplementation((name: string) => {
|
||||
switch (name) {
|
||||
case 'operation':
|
||||
return 'log';
|
||||
case 'repositoryPath':
|
||||
return originalPath;
|
||||
case 'options':
|
||||
return {};
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
});
|
||||
|
||||
(executeFunctions.helpers.resolvePath as jest.Mock).mockResolvedValue(resolvedPath);
|
||||
(executeFunctions.helpers.isFilePathBlocked as jest.Mock).mockReturnValue(false);
|
||||
|
||||
await gitNode.execute.call(executeFunctions);
|
||||
|
||||
// Verify git is initialized with the resolved path, not the original
|
||||
expect(mockSimpleGit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
baseDir: resolvedPath,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { INodeProperties } from 'n8n-workflow';
|
||||
|
||||
export const ALLOWED_CONFIG_KEYS = ['user.email', 'user.name', 'remote.origin.url'];
|
||||
|
||||
export const addConfigFields: INodeProperties[] = [
|
||||
{
|
||||
displayName: 'Key',
|
||||
name: 'key',
|
||||
type: 'options',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['addConfig'],
|
||||
'@version': [{ _cnd: { gte: 1.1 } }],
|
||||
},
|
||||
},
|
||||
options: ALLOWED_CONFIG_KEYS.map((key) => ({
|
||||
name: key,
|
||||
value: key,
|
||||
})),
|
||||
default: '',
|
||||
description: 'Name of the key to set',
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
displayName: 'Key',
|
||||
name: 'key',
|
||||
type: 'string',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['addConfig'],
|
||||
'@version': [{ _cnd: { lt: 1.1 } }],
|
||||
},
|
||||
},
|
||||
default: '',
|
||||
placeholder: 'user.email',
|
||||
description: 'Name of the key to set',
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
displayName: 'Value',
|
||||
name: 'value',
|
||||
type: 'string',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['addConfig'],
|
||||
},
|
||||
},
|
||||
default: '',
|
||||
placeholder: 'name@example.com',
|
||||
description: 'Value of the key to set',
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
displayName: 'Options',
|
||||
name: 'options',
|
||||
type: 'collection',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['addConfig'],
|
||||
},
|
||||
},
|
||||
placeholder: 'Add option',
|
||||
default: {},
|
||||
options: [
|
||||
{
|
||||
displayName: 'Mode',
|
||||
name: 'mode',
|
||||
type: 'options',
|
||||
options: [
|
||||
{
|
||||
name: 'Append',
|
||||
value: 'append',
|
||||
},
|
||||
{
|
||||
name: 'Set',
|
||||
value: 'set',
|
||||
},
|
||||
],
|
||||
default: 'set',
|
||||
description: 'Append setting rather than set it in the local config',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { INodeProperties } from 'n8n-workflow';
|
||||
|
||||
export const addFields: INodeProperties[] = [
|
||||
{
|
||||
displayName: 'Paths to Add',
|
||||
name: 'pathsToAdd',
|
||||
type: 'string',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['add'],
|
||||
},
|
||||
},
|
||||
default: '',
|
||||
placeholder: 'README.md',
|
||||
description:
|
||||
'Comma-separated list of paths (absolute or relative to Repository Path) of files or folders to add',
|
||||
required: true,
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { INodeProperties } from 'n8n-workflow';
|
||||
|
||||
export const cloneFields: INodeProperties[] = [
|
||||
{
|
||||
displayName: 'Source Repository',
|
||||
name: 'sourceRepository',
|
||||
type: 'string',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['clone'],
|
||||
},
|
||||
},
|
||||
default: '',
|
||||
placeholder: 'https://github.com/n8n-io/n8n',
|
||||
description: 'The URL or path of the repository to clone',
|
||||
required: true,
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { INodeProperties } from 'n8n-workflow';
|
||||
|
||||
export const commitFields: INodeProperties[] = [
|
||||
{
|
||||
displayName: 'Message',
|
||||
name: 'message',
|
||||
type: 'string',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['commit'],
|
||||
},
|
||||
},
|
||||
default: '',
|
||||
description: 'The commit message to use',
|
||||
},
|
||||
{
|
||||
displayName: 'Options',
|
||||
name: 'options',
|
||||
type: 'collection',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['commit'],
|
||||
},
|
||||
},
|
||||
placeholder: 'Add option',
|
||||
default: {},
|
||||
options: [
|
||||
{
|
||||
displayName: 'Branch',
|
||||
name: 'branch',
|
||||
type: 'string',
|
||||
default: '',
|
||||
placeholder: 'main',
|
||||
description:
|
||||
'The branch to switch to before committing. If empty or not set, will commit to current branch.',
|
||||
},
|
||||
{
|
||||
displayName: 'Paths to Add',
|
||||
name: 'pathsToAdd',
|
||||
type: 'string',
|
||||
default: '',
|
||||
placeholder: '/data/file1.json',
|
||||
description:
|
||||
'Comma-separated list of paths (absolute or relative to Repository Path) of files or folders to commit. If not set will all "added" files and folders be committed.',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { INodeProperties } from 'n8n-workflow';
|
||||
|
||||
export const logFields: INodeProperties[] = [
|
||||
{
|
||||
displayName: 'Return All',
|
||||
name: 'returnAll',
|
||||
type: 'boolean',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['log'],
|
||||
},
|
||||
},
|
||||
default: false,
|
||||
description: 'Whether to return all results or only up to a given limit',
|
||||
},
|
||||
{
|
||||
displayName: 'Limit',
|
||||
name: 'limit',
|
||||
type: 'number',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['log'],
|
||||
returnAll: [false],
|
||||
},
|
||||
},
|
||||
typeOptions: {
|
||||
minValue: 1,
|
||||
maxValue: 100,
|
||||
},
|
||||
default: 100,
|
||||
description: 'Max number of results to return',
|
||||
},
|
||||
{
|
||||
displayName: 'Options',
|
||||
name: 'options',
|
||||
type: 'collection',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['log'],
|
||||
},
|
||||
},
|
||||
placeholder: 'Add option',
|
||||
default: {},
|
||||
options: [
|
||||
{
|
||||
displayName: 'File',
|
||||
name: 'file',
|
||||
type: 'string',
|
||||
default: 'README.md',
|
||||
description:
|
||||
'The path (absolute or relative to Repository Path) of file or folder to get the history of',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { INodeProperties } from 'n8n-workflow';
|
||||
|
||||
export const pushFields: INodeProperties[] = [
|
||||
{
|
||||
displayName: 'Options',
|
||||
name: 'options',
|
||||
type: 'collection',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['push'],
|
||||
},
|
||||
},
|
||||
placeholder: 'Add option',
|
||||
default: {},
|
||||
options: [
|
||||
{
|
||||
displayName: 'Branch',
|
||||
name: 'branch',
|
||||
type: 'string',
|
||||
default: '',
|
||||
placeholder: 'main',
|
||||
description:
|
||||
'The branch to switch to before pushing. If empty or not set, will push current branch.',
|
||||
},
|
||||
{
|
||||
displayName: 'Target Repository',
|
||||
name: 'targetRepository',
|
||||
type: 'string',
|
||||
default: '',
|
||||
placeholder: 'https://github.com/n8n-io/n8n',
|
||||
description: 'The URL or path of the repository to push to',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { INodeProperties } from 'n8n-workflow';
|
||||
|
||||
export const reflogFields: INodeProperties[] = [
|
||||
{
|
||||
displayName: 'Return All',
|
||||
name: 'returnAll',
|
||||
type: 'boolean',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['reflog'],
|
||||
},
|
||||
},
|
||||
default: false,
|
||||
description: 'Whether to return all results or only up to a given limit',
|
||||
},
|
||||
{
|
||||
displayName: 'Limit',
|
||||
name: 'limit',
|
||||
type: 'number',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['reflog'],
|
||||
returnAll: [false],
|
||||
},
|
||||
},
|
||||
typeOptions: {
|
||||
minValue: 1,
|
||||
maxValue: 100,
|
||||
},
|
||||
default: 100,
|
||||
description: 'Max number of results to return',
|
||||
},
|
||||
{
|
||||
displayName: 'Options',
|
||||
name: 'options',
|
||||
type: 'collection',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['reflog'],
|
||||
},
|
||||
},
|
||||
placeholder: 'Add option',
|
||||
default: {},
|
||||
options: [
|
||||
{
|
||||
displayName: 'Reference',
|
||||
name: 'reference',
|
||||
type: 'string',
|
||||
default: '',
|
||||
placeholder: 'HEAD',
|
||||
description:
|
||||
'The reference to show the reflog for (e.g., HEAD, branch name). Leave empty for HEAD.',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { INodeProperties } from 'n8n-workflow';
|
||||
|
||||
export const switchBranchFields: INodeProperties[] = [
|
||||
{
|
||||
displayName: 'Branch Name',
|
||||
name: 'branchName',
|
||||
type: 'string',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['switchBranch'],
|
||||
},
|
||||
},
|
||||
default: '',
|
||||
placeholder: 'feature/new-feature',
|
||||
required: true,
|
||||
description: 'The name of the branch to switch to',
|
||||
},
|
||||
{
|
||||
displayName: 'Options',
|
||||
name: 'options',
|
||||
type: 'collection',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['switchBranch'],
|
||||
},
|
||||
},
|
||||
placeholder: 'Add option',
|
||||
default: {},
|
||||
options: [
|
||||
{
|
||||
displayName: 'Create Branch If Not Exists',
|
||||
name: 'createBranch',
|
||||
type: 'boolean',
|
||||
default: true,
|
||||
description: 'Whether to create the branch if it does not exist',
|
||||
},
|
||||
{
|
||||
displayName: 'Start Point',
|
||||
name: 'startPoint',
|
||||
type: 'string',
|
||||
default: '',
|
||||
placeholder: 'main',
|
||||
description:
|
||||
'The commit/branch/tag to create the new branch from. If not set, creates from current HEAD.',
|
||||
displayOptions: {
|
||||
show: {
|
||||
createBranch: [true],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
displayName: 'Force Switch',
|
||||
name: 'force',
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
description: 'Whether to force the branch switch, discarding any local changes',
|
||||
},
|
||||
{
|
||||
displayName: 'Set Upstream',
|
||||
name: 'setUpstream',
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
description: 'Whether to set up tracking to a remote branch when creating a new branch',
|
||||
displayOptions: {
|
||||
show: {
|
||||
createBranch: [true],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
displayName: 'Remote Name',
|
||||
name: 'remoteName',
|
||||
type: 'string',
|
||||
default: 'origin',
|
||||
placeholder: 'origin',
|
||||
description: 'The name of the remote to track',
|
||||
displayOptions: {
|
||||
show: {
|
||||
createBranch: [true],
|
||||
setUpstream: [true],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { INodeProperties } from 'n8n-workflow';
|
||||
|
||||
export const tagFields: INodeProperties[] = [
|
||||
{
|
||||
displayName: 'Name',
|
||||
name: 'name',
|
||||
type: 'string',
|
||||
displayOptions: {
|
||||
show: {
|
||||
operation: ['tag'],
|
||||
},
|
||||
},
|
||||
default: '',
|
||||
description: 'The name of the tag to create',
|
||||
required: true,
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,9 @@
|
||||
export * from './AddDescription';
|
||||
export * from './AddConfigDescription';
|
||||
export * from './CloneDescription';
|
||||
export * from './CommitDescription';
|
||||
export * from './LogDescription';
|
||||
export * from './PushDescription';
|
||||
export * from './ReflogDescription';
|
||||
export * from './SwitchBranchDescription';
|
||||
export * from './TagDescription';
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="97" height="97"><path fill="#F05133" d="M92.71 44.408 52.591 4.291a5.92 5.92 0 0 0-8.369 0l-8.33 8.332L46.459 23.19a7.02 7.02 0 0 1 7.229 1.685 7.03 7.03 0 0 1 1.67 7.275l10.186 10.185a7.03 7.03 0 0 1 7.275 1.671 7.043 7.043 0 0 1-9.961 9.958 7.04 7.04 0 0 1-1.531-7.658l-9.5-9.499v24.997a7.042 7.042 0 1 1-8.096 11.291 7.042 7.042 0 0 1 2.307-11.496v-25.23a7.04 7.04 0 0 1-3.823-9.235L31.798 16.715 4.288 44.222a5.92 5.92 0 0 0 0 8.371l40.121 40.118a5.92 5.92 0 0 0 8.369 0L92.71 52.779a5.92 5.92 0 0 0 0-8.371"/></svg>
|
||||
|
After Width: | Height: | Size: 567 B |
@@ -0,0 +1,766 @@
|
||||
import * as fsPromises from 'fs/promises';
|
||||
import { mock } from 'jest-mock-extended';
|
||||
import type { IExecuteFunctions } from 'n8n-workflow';
|
||||
import type { SimpleGit } from 'simple-git';
|
||||
import { Container } from '@n8n/di';
|
||||
import { SecurityConfig } from '@n8n/config';
|
||||
|
||||
import { Git } from '../Git.node';
|
||||
import { ALLOWED_CONFIG_KEYS } from '../descriptions';
|
||||
|
||||
// Mock simple-git
|
||||
const mockGit = {
|
||||
checkout: jest.fn(),
|
||||
checkoutBranch: jest.fn(),
|
||||
checkoutLocalBranch: jest.fn(),
|
||||
add: jest.fn(),
|
||||
commit: jest.fn(),
|
||||
push: jest.fn(),
|
||||
pull: jest.fn(),
|
||||
clone: jest.fn(),
|
||||
addConfig: jest.fn(),
|
||||
fetch: jest.fn(),
|
||||
log: jest.fn(),
|
||||
pushTags: jest.fn(),
|
||||
listConfig: jest.fn(),
|
||||
status: jest.fn(),
|
||||
addTag: jest.fn(),
|
||||
raw: jest.fn(),
|
||||
env: jest.fn().mockReturnThis(),
|
||||
} as unknown as jest.Mocked<SimpleGit>;
|
||||
|
||||
jest.mock('simple-git', () => ({
|
||||
__esModule: true,
|
||||
default: () => mockGit,
|
||||
}));
|
||||
|
||||
// Mock filesystem operations
|
||||
jest.mock('fs/promises', () => ({
|
||||
access: jest.fn(),
|
||||
mkdir: jest.fn(),
|
||||
}));
|
||||
|
||||
const mockFsPromises = jest.mocked(fsPromises);
|
||||
|
||||
describe('Git Node', () => {
|
||||
let gitNode: Git;
|
||||
let mockExecuteFunctions: jest.Mocked<IExecuteFunctions>;
|
||||
|
||||
beforeEach(() => {
|
||||
gitNode = new Git();
|
||||
mockExecuteFunctions = mock<IExecuteFunctions>({
|
||||
getInputData: jest.fn(() => [{ json: {} }]),
|
||||
getNodeParameter: jest.fn(),
|
||||
continueOnFail: jest.fn(() => false),
|
||||
helpers: {
|
||||
returnJsonArray: jest.fn((data: any[]) => data.map((item: any) => ({ json: item }))),
|
||||
resolvePath: jest.fn(async (path: string) => path as any),
|
||||
isFilePathBlocked: jest.fn(() => false),
|
||||
},
|
||||
});
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Branch switching', () => {
|
||||
it('should switch to existing branch for commit operation', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('commit')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({ branch: 'feature' })
|
||||
.mockReturnValueOnce('test commit');
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.checkout).toHaveBeenCalledWith('feature');
|
||||
expect(mockGit.commit).toHaveBeenCalledWith('test commit');
|
||||
});
|
||||
|
||||
it('should commit specific files when pathsToAdd is provided', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('commit')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({
|
||||
branch: 'feature-branch',
|
||||
files: true,
|
||||
pathsToAdd: 'src/file1.js,src/file2.js,README.md',
|
||||
})
|
||||
.mockReturnValueOnce('Add specific files');
|
||||
|
||||
mockGit.checkout.mockResolvedValueOnce('Switched to branch feature-branch' as any);
|
||||
|
||||
const result = await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.checkout).toHaveBeenCalledWith('feature-branch');
|
||||
// Uses -- separator to prevent argument injection
|
||||
expect(mockGit.commit).toHaveBeenCalledWith('Add specific files', [
|
||||
'--',
|
||||
'src/file1.js',
|
||||
'src/file2.js',
|
||||
'README.md',
|
||||
]);
|
||||
expect(result[0]).toEqual([{ json: { success: true }, pairedItem: { item: 0 } }]);
|
||||
});
|
||||
|
||||
it('should fail when trying to push to non-existent branch', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('push')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({ branch: 'non-existent-branch' })
|
||||
.mockReturnValueOnce('none');
|
||||
|
||||
const error = new Error('Branch not found');
|
||||
mockGit.checkout.mockRejectedValueOnce(error);
|
||||
|
||||
await expect(gitNode.execute.call(mockExecuteFunctions)).rejects.toThrow('Branch not found');
|
||||
|
||||
expect(mockGit.checkout).toHaveBeenCalledWith('non-existent-branch');
|
||||
expect(mockGit.checkoutLocalBranch).not.toHaveBeenCalled();
|
||||
expect(mockGit.push).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should set upstream when creating branch for commit operation', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('commit')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({ branch: 'feature-branch' })
|
||||
.mockReturnValueOnce('commit message');
|
||||
|
||||
mockGit.checkout.mockRejectedValueOnce(new Error('Branch not found'));
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.checkout).toHaveBeenCalledWith('feature-branch');
|
||||
expect(mockGit.checkoutLocalBranch).toHaveBeenCalledWith('feature-branch');
|
||||
expect(mockGit.addConfig).toHaveBeenCalledWith('branch.feature-branch.remote', 'origin');
|
||||
expect(mockGit.addConfig).toHaveBeenCalledWith(
|
||||
'branch.feature-branch.merge',
|
||||
'refs/heads/feature-branch',
|
||||
);
|
||||
expect(mockGit.commit).toHaveBeenCalledWith('commit message');
|
||||
});
|
||||
|
||||
it('should set upstream when switching to existing branch for push operation', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('push')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({ branch: 'existing-branch' })
|
||||
.mockReturnValueOnce('none');
|
||||
|
||||
// Branch exists, so checkout succeeds
|
||||
mockGit.checkout.mockResolvedValueOnce('Switched to branch existing-branch' as any);
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.checkout).toHaveBeenCalledWith('existing-branch');
|
||||
expect(mockGit.checkoutLocalBranch).not.toHaveBeenCalled();
|
||||
expect(mockGit.addConfig).toHaveBeenCalledWith('branch.existing-branch.remote', 'origin');
|
||||
expect(mockGit.addConfig).toHaveBeenCalledWith(
|
||||
'branch.existing-branch.merge',
|
||||
'refs/heads/existing-branch',
|
||||
);
|
||||
expect(mockGit.push).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should push to specific repository when repository option is provided', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('push')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({
|
||||
branch: 'feature-branch',
|
||||
repository: true,
|
||||
targetRepository: 'https://github.com/example/repo.git',
|
||||
})
|
||||
.mockReturnValueOnce('none');
|
||||
|
||||
// Branch exists, so checkout succeeds
|
||||
mockGit.checkout.mockResolvedValueOnce('Switched to branch feature-branch' as any);
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.checkout).toHaveBeenCalledWith('feature-branch');
|
||||
expect(mockGit.push).toHaveBeenCalledWith('https://github.com/example/repo.git');
|
||||
});
|
||||
|
||||
it('should not switch branch when pushing with empty branch string', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('push')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({ branch: '' }) // empty string branch
|
||||
.mockReturnValueOnce('gitPassword');
|
||||
|
||||
// Mock git config for push operation
|
||||
mockGit.listConfig.mockResolvedValueOnce({
|
||||
values: { '.git/config': { 'remote.origin.url': 'https://github.com/test/repo.git' } },
|
||||
} as any);
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.checkout).not.toHaveBeenCalled();
|
||||
expect(mockGit.push).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle switchBranch operation to existing branch', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('switchBranch')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({})
|
||||
.mockReturnValueOnce('existing-branch');
|
||||
|
||||
const result = await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.checkout).toHaveBeenCalledWith('existing-branch');
|
||||
expect(result[0]).toEqual([
|
||||
{ json: { success: true, branch: 'existing-branch' }, pairedItem: { item: 0 } },
|
||||
]);
|
||||
});
|
||||
|
||||
it('should create new branch when switchBranch fails and createBranch is true', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('switchBranch')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({ createBranch: true })
|
||||
.mockReturnValueOnce('new-branch');
|
||||
|
||||
mockGit.checkout.mockRejectedValueOnce(new Error('Branch not found'));
|
||||
|
||||
const result = await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.checkout).toHaveBeenCalledWith('new-branch');
|
||||
expect(mockGit.checkoutLocalBranch).toHaveBeenCalledWith('new-branch');
|
||||
expect(result[0]).toEqual([
|
||||
{ json: { success: true, branch: 'new-branch' }, pairedItem: { item: 0 } },
|
||||
]);
|
||||
});
|
||||
|
||||
it('should create branch from start point when specified', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('switchBranch')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({ createBranch: true, startPoint: 'main' })
|
||||
.mockReturnValueOnce('feature-branch');
|
||||
|
||||
mockGit.checkout.mockRejectedValueOnce(new Error('Branch not found'));
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.checkout).toHaveBeenCalledWith('feature-branch');
|
||||
expect(mockGit.checkoutBranch).toHaveBeenCalledWith('feature-branch', 'main');
|
||||
});
|
||||
|
||||
it('should force checkout when force option is enabled', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('switchBranch')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({ force: true })
|
||||
.mockReturnValueOnce('force-branch');
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.checkout).toHaveBeenCalledWith(['-f', 'force-branch']);
|
||||
});
|
||||
|
||||
it('should throw error when createBranch is false and branch does not exist', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('switchBranch')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({ createBranch: false })
|
||||
.mockReturnValueOnce('nonexistent-branch');
|
||||
|
||||
const error = new Error('Branch not found');
|
||||
mockGit.checkout.mockRejectedValueOnce(error);
|
||||
|
||||
await expect(gitNode.execute.call(mockExecuteFunctions)).rejects.toThrow('Branch not found');
|
||||
});
|
||||
|
||||
it('should set upstream tracking when creating new branch with setUpstream option', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('switchBranch')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({
|
||||
createBranch: true,
|
||||
setUpstream: true,
|
||||
remoteName: 'origin',
|
||||
})
|
||||
.mockReturnValueOnce('feature-branch');
|
||||
|
||||
mockGit.checkout.mockRejectedValueOnce(new Error('Branch not found'));
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.checkout).toHaveBeenCalledWith('feature-branch');
|
||||
expect(mockGit.checkoutLocalBranch).toHaveBeenCalledWith('feature-branch');
|
||||
expect(mockGit.addConfig).toHaveBeenCalledWith('branch.feature-branch.remote', 'origin');
|
||||
expect(mockGit.addConfig).toHaveBeenCalledWith(
|
||||
'branch.feature-branch.merge',
|
||||
'refs/heads/feature-branch',
|
||||
);
|
||||
});
|
||||
|
||||
it('should use default remote name when not specified', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('switchBranch')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({
|
||||
createBranch: true,
|
||||
setUpstream: true,
|
||||
// remoteName not specified, should default to 'origin'
|
||||
})
|
||||
.mockReturnValueOnce('feature-branch');
|
||||
|
||||
mockGit.checkout.mockRejectedValueOnce(new Error('Branch not found'));
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.addConfig).toHaveBeenCalledWith('branch.feature-branch.remote', 'origin');
|
||||
});
|
||||
|
||||
it('should continue successfully even if upstream setup fails', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('switchBranch')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({
|
||||
createBranch: true,
|
||||
setUpstream: true,
|
||||
remoteName: 'origin',
|
||||
})
|
||||
.mockReturnValueOnce('feature-branch');
|
||||
|
||||
mockGit.checkout.mockRejectedValueOnce(new Error('Branch not found'));
|
||||
mockGit.addConfig.mockRejectedValueOnce(new Error('Remote not found'));
|
||||
|
||||
const result = await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.checkoutLocalBranch).toHaveBeenCalledWith('feature-branch');
|
||||
expect(result[0]).toEqual([
|
||||
{
|
||||
json: { success: true, branch: 'feature-branch' },
|
||||
pairedItem: { item: 0 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should not switch branch when not specified', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('commit')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({}) // no branch
|
||||
.mockReturnValueOnce('test commit');
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.checkout).not.toHaveBeenCalled();
|
||||
expect(mockGit.commit).toHaveBeenCalledWith('test commit');
|
||||
});
|
||||
|
||||
it('should not switch branch when empty string is provided', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('commit')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({ branch: '' }) // empty string branch
|
||||
.mockReturnValueOnce('test commit');
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.checkout).not.toHaveBeenCalled();
|
||||
expect(mockGit.commit).toHaveBeenCalledWith('test commit');
|
||||
});
|
||||
});
|
||||
|
||||
describe('All operations coverage', () => {
|
||||
it('should handle add operation', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('add')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({})
|
||||
.mockReturnValueOnce('file.txt');
|
||||
|
||||
const result = await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
// Should use -- separator to prevent argument injection
|
||||
expect(mockGit.add).toHaveBeenCalledWith(['--', 'file.txt']);
|
||||
expect(result[0]).toEqual([{ json: { success: true }, pairedItem: { item: 0 } }]);
|
||||
});
|
||||
|
||||
ALLOWED_CONFIG_KEYS.forEach((key) => {
|
||||
it(`should handle addConfig with key '${key}' operation`, async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('addConfig')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({})
|
||||
.mockReturnValueOnce(key)
|
||||
.mockReturnValueOnce('test value');
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.addConfig).toHaveBeenCalledWith(key, 'test value', false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('enableGitNodeAllConfigKeys is false (default value)', () => {
|
||||
[
|
||||
'core.sshCommand',
|
||||
'core.hooksPath',
|
||||
'credential.helper',
|
||||
'remote.origin.uploadpack',
|
||||
'remote.origin.receivepack',
|
||||
'url.xxx.insteadOf',
|
||||
'user.name,core.sshCommand',
|
||||
].forEach((key) => {
|
||||
it(`should reject addConfig with key '${key}'`, async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('addConfig')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({})
|
||||
.mockReturnValueOnce(key)
|
||||
.mockReturnValueOnce('test value');
|
||||
|
||||
await expect(gitNode.execute.call(mockExecuteFunctions)).rejects.toThrow(
|
||||
`The provided git config key '${key}' is not allowed`,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('enableGitNodeAllConfigKeys is true', () => {
|
||||
beforeEach(() => {
|
||||
const securityConfig = mock<SecurityConfig>({
|
||||
enableGitNodeAllConfigKeys: true,
|
||||
});
|
||||
Container.set(SecurityConfig, securityConfig);
|
||||
});
|
||||
|
||||
[
|
||||
'core.sshCommand',
|
||||
'core.hooksPath',
|
||||
'credential.helper',
|
||||
'remote.origin.uploadpack',
|
||||
'remote.origin.receivepack',
|
||||
'url.xxx.insteadOf',
|
||||
'user.name,core.sshCommand',
|
||||
].forEach((key) => {
|
||||
it(`should handle addConfig with key '${key}'`, async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('addConfig')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({})
|
||||
.mockReturnValueOnce(key)
|
||||
.mockReturnValueOnce('test value');
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.addConfig).toHaveBeenCalledWith(key, 'test value', false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle addConfig operation', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('addConfig')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({})
|
||||
.mockReturnValueOnce('user.name')
|
||||
.mockReturnValueOnce('test user');
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.addConfig).toHaveBeenCalledWith('user.name', 'test user', false);
|
||||
});
|
||||
|
||||
it('should handle clone operation and create directory when it does not exist', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('clone')
|
||||
.mockReturnValueOnce('/new-repo')
|
||||
.mockReturnValueOnce({})
|
||||
.mockReturnValueOnce('https://github.com/test/repo.git');
|
||||
|
||||
// Simulate directory not existing - access() throws
|
||||
mockFsPromises.access.mockRejectedValueOnce(new Error('Directory does not exist'));
|
||||
mockFsPromises.mkdir.mockResolvedValueOnce(undefined);
|
||||
|
||||
const result = await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockFsPromises.access).toHaveBeenCalledWith('/new-repo');
|
||||
expect(mockFsPromises.mkdir).toHaveBeenCalledWith('/new-repo');
|
||||
expect(mockGit.clone).toHaveBeenCalledWith('https://github.com/test/repo.git', '.');
|
||||
expect(result[0]).toEqual([{ json: { success: true }, pairedItem: { item: 0 } }]);
|
||||
});
|
||||
|
||||
it('should handle clone operation when directory already exists', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('clone')
|
||||
.mockReturnValueOnce('/existing-repo')
|
||||
.mockReturnValueOnce({})
|
||||
.mockReturnValueOnce('https://github.com/test/repo.git');
|
||||
|
||||
// Simulate directory already exists - access() succeeds
|
||||
mockFsPromises.access.mockResolvedValueOnce(undefined);
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockFsPromises.access).toHaveBeenCalledWith('/existing-repo');
|
||||
expect(mockFsPromises.mkdir).not.toHaveBeenCalled();
|
||||
expect(mockGit.clone).toHaveBeenCalledWith('https://github.com/test/repo.git', '.');
|
||||
});
|
||||
|
||||
it('should handle fetch operation', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('fetch')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({});
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.fetch).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle pull operation', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('pull')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({});
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.pull).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle log operation', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('log')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({})
|
||||
.mockReturnValueOnce(false) // returnAll
|
||||
.mockReturnValueOnce(10); // limit
|
||||
|
||||
const mockLogData = [
|
||||
{ hash: 'abc123', message: 'test commit', author_name: 'John Doe' },
|
||||
{ hash: 'def456', message: 'another commit', author_name: 'Jane Smith' },
|
||||
];
|
||||
mockGit.log.mockResolvedValueOnce({ all: mockLogData } as any);
|
||||
|
||||
const result = await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.log).toHaveBeenCalledWith({ maxCount: 10 });
|
||||
expect(result[0]).toHaveLength(2);
|
||||
expect(result[0]).toEqual([
|
||||
{
|
||||
json: { hash: 'abc123', message: 'test commit', author_name: 'John Doe' },
|
||||
pairedItem: { item: 0 },
|
||||
},
|
||||
{
|
||||
json: { hash: 'def456', message: 'another commit', author_name: 'Jane Smith' },
|
||||
pairedItem: { item: 0 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should handle pushTags operation', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('pushTags')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({});
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.pushTags).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle listConfig operation', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('listConfig')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({});
|
||||
|
||||
mockGit.listConfig.mockResolvedValueOnce({
|
||||
values: { '.git/config': { 'user.name': 'test' } },
|
||||
} as any);
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.listConfig).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle status operation', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('status')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({});
|
||||
|
||||
mockGit.status.mockResolvedValueOnce({ current: 'main' } as any);
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.status).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle tag operation', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('tag')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({})
|
||||
.mockReturnValueOnce('v1.0.0');
|
||||
|
||||
await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.addTag).toHaveBeenCalledWith('v1.0.0');
|
||||
});
|
||||
|
||||
it('should handle reflog operation with default HEAD reference', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('reflog')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({}) // options - no custom reference
|
||||
.mockReturnValueOnce(false) // returnAll
|
||||
.mockReturnValueOnce(10); // limit
|
||||
|
||||
const mockReflogOutput = `abc123 HEAD@{0}: commit: Update README
|
||||
def456 HEAD@{1}: pull: Fast-forward
|
||||
789xyz HEAD@{2}: checkout: moving from main to feature`;
|
||||
|
||||
mockGit.raw.mockResolvedValueOnce(mockReflogOutput);
|
||||
|
||||
const result = await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.raw).toHaveBeenCalledWith(['reflog', 'HEAD']);
|
||||
expect(result[0]).toHaveLength(3);
|
||||
expect(result[0][0]).toEqual({
|
||||
json: {
|
||||
hash: 'abc123',
|
||||
ref: 'HEAD@{0}',
|
||||
action: 'commit',
|
||||
message: 'Update README',
|
||||
raw: 'abc123 HEAD@{0}: commit: Update README',
|
||||
},
|
||||
pairedItem: { item: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle reflog operation with custom reference', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('reflog')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({ reference: 'main' }) // custom reference
|
||||
.mockReturnValueOnce(false) // returnAll
|
||||
.mockReturnValueOnce(10); // limit
|
||||
|
||||
const mockReflogOutput = `abc123 main@{0}: commit: Feature complete
|
||||
def456 main@{1}: commit: Initial commit`;
|
||||
|
||||
mockGit.raw.mockResolvedValueOnce(mockReflogOutput);
|
||||
|
||||
const result = await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(mockGit.raw).toHaveBeenCalledWith(['reflog', 'main']);
|
||||
expect(result[0]).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should reject reflog with invalid reference to prevent argument injection', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('reflog')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({ reference: '-n' })
|
||||
.mockReturnValueOnce(false);
|
||||
|
||||
await expect(gitNode.execute.call(mockExecuteFunctions)).rejects.toThrow(
|
||||
'Reference cannot start with a hyphen',
|
||||
);
|
||||
|
||||
expect(mockGit.raw).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle reflog operation with limit', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('reflog')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({})
|
||||
.mockReturnValueOnce(false) // returnAll = false
|
||||
.mockReturnValueOnce(2); // limit = 2
|
||||
|
||||
const mockReflogOutput = `abc123 HEAD@{0}: commit: First
|
||||
def456 HEAD@{1}: commit: Second
|
||||
789xyz HEAD@{2}: commit: Third
|
||||
012abc HEAD@{3}: commit: Fourth`;
|
||||
|
||||
mockGit.raw.mockResolvedValueOnce(mockReflogOutput);
|
||||
|
||||
const result = await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(result[0]).toHaveLength(2); // Should only return 2 entries
|
||||
expect(result[0][0].json.hash).toBe('abc123');
|
||||
expect(result[0][1].json.hash).toBe('def456');
|
||||
});
|
||||
|
||||
it('should handle reflog operation with returnAll option', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('reflog')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({})
|
||||
.mockReturnValueOnce(true); // returnAll = true
|
||||
|
||||
const mockReflogOutput = `abc123 HEAD@{0}: commit: First
|
||||
def456 HEAD@{1}: commit: Second
|
||||
789xyz HEAD@{2}: commit: Third
|
||||
012abc HEAD@{3}: commit: Fourth`;
|
||||
|
||||
mockGit.raw.mockResolvedValueOnce(mockReflogOutput);
|
||||
|
||||
const result = await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(result[0]).toHaveLength(4); // Should return all entries
|
||||
});
|
||||
|
||||
it('should handle reflog with unparseable lines', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('reflog')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({})
|
||||
.mockReturnValueOnce(true); // returnAll
|
||||
|
||||
const mockReflogOutput = `abc123 HEAD@{0}: commit: Valid entry
|
||||
invalid line without proper format`;
|
||||
|
||||
mockGit.raw.mockResolvedValueOnce(mockReflogOutput);
|
||||
|
||||
const result = await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(result[0]).toHaveLength(2);
|
||||
expect(result[0][0].json).toHaveProperty('hash');
|
||||
expect(result[0][1].json).toEqual({ raw: 'invalid line without proper format' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error handling', () => {
|
||||
it('should continue on fail when enabled', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('commit')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({ branch: 'bad-branch' })
|
||||
.mockReturnValueOnce('test');
|
||||
|
||||
mockExecuteFunctions.continueOnFail.mockReturnValueOnce(true);
|
||||
mockGit.checkout.mockRejectedValueOnce(new Error('Branch error'));
|
||||
mockGit.checkoutLocalBranch.mockRejectedValueOnce(new Error('Create error'));
|
||||
|
||||
const result = await gitNode.execute.call(mockExecuteFunctions);
|
||||
|
||||
expect(result[0]).toEqual([
|
||||
{
|
||||
json: { error: 'Error: Create error' },
|
||||
pairedItem: { item: 0 },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should throw on fail when continueOnFail is disabled', async () => {
|
||||
mockExecuteFunctions.getNodeParameter
|
||||
.mockReturnValueOnce('add')
|
||||
.mockReturnValueOnce('/repo')
|
||||
.mockReturnValueOnce({})
|
||||
.mockReturnValueOnce('file.txt');
|
||||
|
||||
mockGit.add.mockRejectedValueOnce(new Error('Add failed'));
|
||||
|
||||
await expect(gitNode.execute.call(mockExecuteFunctions)).rejects.toThrow('Add failed');
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user