From 491039b9e351951b48c8d94539f820249a9f8044 Mon Sep 17 00:00:00 2001 From: CrazyMax <1951866+crazy-max@users.noreply.github.com> Date: Thu, 4 Jul 2024 16:33:39 +0200 Subject: [PATCH] util: isPathRelativeTo func Signed-off-by: CrazyMax <1951866+crazy-max@users.noreply.github.com> --- __tests__/util.test.ts | 28 ++++++++++++++++++++++++++++ src/util.ts | 7 +++++++ 2 files changed, 35 insertions(+) diff --git a/__tests__/util.test.ts b/__tests__/util.test.ts index 6889c1b..2a733d9 100644 --- a/__tests__/util.test.ts +++ b/__tests__/util.test.ts @@ -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()}`; diff --git a/src/util.ts b/src/util.ts index 91fc2f6..2587aca 100644 --- a/src/util.ts +++ b/src/util.ts @@ -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}`); + } }