util: isPathRelativeTo func

Signed-off-by: CrazyMax <1951866+crazy-max@users.noreply.github.com>
This commit is contained in:
CrazyMax 2024-07-04 16:33:39 +02:00
parent a777edf0f6
commit 491039b9e3
No known key found for this signature in database
GPG Key ID: ADE44D8C9D44FBE4
2 changed files with 35 additions and 0 deletions

View File

@ -416,6 +416,34 @@ lines`;
});
});
describe('isPathRelativeTo', () => {
it('should return true for a child path directly inside the parent path', () => {
const parentPath = '/home/user/projects';
const childPath = '/home/user/projects/subproject';
expect(Util.isPathRelativeTo(parentPath, childPath)).toBe(true);
});
it('should return true for a deeply nested child path inside the parent path', () => {
const parentPath = '/home/user';
const childPath = '/home/user/projects/subproject/module';
expect(Util.isPathRelativeTo(parentPath, childPath)).toBe(true);
});
it('should return false for a child path outside the parent path', () => {
const parentPath = '/home/user/projects';
const childPath = '/home/user/otherprojects/subproject';
expect(Util.isPathRelativeTo(parentPath, childPath)).toBe(false);
});
it('should return true for a child path specified with relative segments', () => {
const parentPath = '/home/user/projects';
const childPath = '/home/user/projects/../projects/subproject';
expect(Util.isPathRelativeTo(parentPath, childPath)).toBe(true);
});
it('should return false when the child path is actually a parent path', () => {
const parentPath = '/home/user/projects/subproject';
const childPath = '/home/user/projects';
expect(Util.isPathRelativeTo(parentPath, childPath)).toBe(false);
});
});
// See: https://github.com/actions/toolkit/blob/a1b068ec31a042ff1e10a522d8fdf0b8869d53ca/packages/core/src/core.ts#L89
function getInputName(name: string): string {
return `INPUT_${name.replace(/ /g, '_').toUpperCase()}`;

View File

@ -16,6 +16,7 @@
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import * as core from '@actions/core';
import * as io from '@actions/io';
import {parse} from 'csv-parse/sync';
@ -189,4 +190,10 @@ export class Util {
public static countLines(input: string): number {
return input.split(/\r\n|\r|\n/).length;
}
public static isPathRelativeTo(parentPath: string, childPath: string): boolean {
const rpp = path.resolve(parentPath);
const rcp = path.resolve(childPath);
return rcp.startsWith(rpp.endsWith(path.sep) ? rpp : `${rpp}${path.sep}`);
}
}