Skip to content

Commit e3bde20

Browse files
committed
Refactor and test
1 parent 473cb1b commit e3bde20

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

__tests__/authutil.test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import * as auth from '../src/authutil';
77
import * as cacheUtils from '../src/cache-utils';
88

99
let rcFile: string;
10+
let pkgJson: string;
1011

1112
describe('authutil tests', () => {
1213
const _runnerDir = path.join(__dirname, 'runner');
@@ -25,10 +26,12 @@ describe('authutil tests', () => {
2526
process.env['GITHUB_REPOSITORY'] = 'OwnerName/repo';
2627
process.env['RUNNER_TEMP'] = tempDir;
2728
rcFile = path.join(tempDir, '.npmrc');
29+
pkgJson = path.join(tempDir, 'package.json');
2830
}, 100000);
2931

3032
beforeEach(async () => {
3133
await io.rmRF(rcFile);
34+
await io.rmRF(pkgJson);
3235
// if (fs.existsSync(rcFile)) {
3336
// fs.unlinkSync(rcFile);
3437
// }
@@ -113,6 +116,15 @@ describe('authutil tests', () => {
113116
expect(rc['always-auth']).toBe('false');
114117
});
115118

119+
it('Automatically configures npm scope from package.json', async () => {
120+
process.env['INPUT_SCOPE'] = '';
121+
fs.writeFileSync(pkgJson, '{"name":"@myscope/mypackage"}');
122+
await auth.configAuthentication('https://registry.npmjs.org', '');
123+
124+
const rc = readRcFile(rcFile);
125+
expect(rc['@myscope:registry']).toBe('https://registry.npmjs.org/');
126+
});
127+
116128
it('Sets up npmrc for always-auth true', async () => {
117129
await auth.configAuthentication('https://registry.npmjs.org/', 'true');
118130
expect(fs.statSync(rcFile)).toBeDefined();

src/authutil.ts

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,10 @@ function writeRegistryToFile(
2626
scope = github.context.repo.owner;
2727
}
2828
if (!scope) {
29-
let namePrefix = require('./package').name.match('@[^/]+');
30-
if (namePrefix) {
31-
scope = namePrefix[0];
32-
}
29+
const namePrefix = packageJson('name')?.match(/^(@[^/]+)\//);
30+
if (namePrefix) {
31+
scope = namePrefix[1];
32+
}
3333
}
3434
if (scope && scope[0] != '@') {
3535
scope = '@' + scope;
@@ -63,3 +63,14 @@ function writeRegistryToFile(
6363
process.env.NODE_AUTH_TOKEN || 'XXXXX-XXXXX-XXXXX-XXXXX'
6464
);
6565
}
66+
67+
function packageJson(prop: string){
68+
const pkgPath: string = path.resolve(process.env['RUNNER_TEMP'] || process.cwd(), 'package.json');
69+
try {
70+
const json = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
71+
72+
return prop ? json[prop] : json;
73+
} catch(e) {
74+
core.debug(`Unable to read from package.json`);
75+
}
76+
}

0 commit comments

Comments
 (0)