Skip to content

Commit

Permalink
detect package manager and improve types (#3847)
Browse files Browse the repository at this point in the history
  • Loading branch information
FredKSchott authored Jul 7, 2022
1 parent 4fb0850 commit eedb32c
Show file tree
Hide file tree
Showing 7 changed files with 78 additions and 44 deletions.
5 changes: 5 additions & 0 deletions .changeset/silent-readers-behave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/telemetry': patch
---

Detect package manager, improve types
6 changes: 4 additions & 2 deletions packages/create-astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,21 @@
"create-astro.js"
],
"dependencies": {
"@types/degit": "^2.8.3",
"@types/prompts": "^2.0.14",
"chalk": "^5.0.1",
"degit": "^2.8.4",
"execa": "^6.1.0",
"kleur": "^4.1.4",
"ora": "^6.1.0",
"prompts": "^2.4.2",
"which-pm-runs": "^1.1.0",
"yargs-parser": "^21.0.1"
},
"devDependencies": {
"@types/chai": "^4.3.1",
"@types/degit": "^2.8.3",
"@types/mocha": "^9.1.1",
"@types/prompts": "^2.0.14",
"@types/which-pm-runs": "^1.0.0",
"@types/yargs-parser": "^21.0.0",
"astro-scripts": "workspace:*",
"chai": "^4.3.6",
Expand Down
18 changes: 2 additions & 16 deletions packages/create-astro/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import yargs from 'yargs-parser';
import { loadWithRocketGradient, rocketAscii } from './gradient.js';
import { defaultLogLevel, logger } from './logger.js';
import { TEMPLATES } from './templates.js';
import detectPackageManager from 'which-pm-runs';

function wait(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
Expand Down Expand Up @@ -48,7 +49,7 @@ const FILES_TO_REMOVE = ['.stackblitzrc', 'sandbox.config.json', 'CHANGELOG.md']

// Please also update the installation instructions in the docs at https://github.com/withastro/docs/blob/main/src/pages/en/install/auto.md if you make any changes to the flow or wording here.
export async function main() {
const pkgManager = pkgManagerFromUserAgent(process.env.npm_config_user_agent);
const pkgManager = detectPackageManager()?.name || 'npm';

logger.debug('Verbose logging turned on');
console.log(`\n${bold('Welcome to Astro!')} ${gray(`(create-astro v${version})`)}`);
Expand Down Expand Up @@ -251,18 +252,3 @@ function emojiWithFallback(char: string, fallback: string) {
return process.platform !== 'win32' ? char : fallback;
}

function pkgManagerFromUserAgent(userAgent?: string) {
if (!userAgent) return 'npm';
const pkgSpec = userAgent.split(' ')[0];
const pkgSpecArr = pkgSpec.split('/');
return pkgSpecArr[0];
}

function pkgManagerExecCommand(pkgManager: string) {
if (pkgManager === 'pnpm') {
return 'pnpx';
} else {
// note: yarn does not have an "npx" equivalent
return 'npx';
}
}
4 changes: 3 additions & 1 deletion packages/telemetry/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,13 @@
"git-up": "^4.0.5",
"is-docker": "^3.0.0",
"is-wsl": "^2.2.0",
"node-fetch": "^3.2.5"
"node-fetch": "^3.2.5",
"which-pm-runs": "^1.1.0"
},
"devDependencies": {
"@types/dlv": "^1.1.2",
"@types/node": "^14.18.21",
"@types/which-pm-runs": "^1.0.0",
"astro-scripts": "workspace:*"
},
"engines": {
Expand Down
32 changes: 14 additions & 18 deletions packages/telemetry/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,12 @@ import { getSystemInfo, SystemInfo } from './system-info.js';

export type AstroTelemetryOptions = { astroVersion: string; viteVersion: string };
export type TelemetryEvent = { eventName: string; payload: Record<string, any> };
interface EventContext {

interface EventMeta extends SystemInfo {}
interface EventContext extends ProjectInfo {
anonymousId: string;
anonymousProjectId: string;
anonymousSessionId: string;
}

interface EventMeta extends SystemInfo {
isGit: boolean;
}
export class AstroTelemetry {
private _anonymousSessionId: string | undefined;
private _anonymousProjectInfo: ProjectInfo | undefined;
Expand Down Expand Up @@ -118,29 +115,19 @@ export class AstroTelemetry {
return Promise.resolve();
}

if (this.debug.enabled) {
// Print to standard error to simplify selecting the output
events.forEach(({ eventName, payload }) =>
this.debug(JSON.stringify({ eventName, payload }, null, 2))
);
// Do not send the telemetry data if debugging. Users may use this feature
// to preview what data would be sent.
return Promise.resolve();
}

// Skip recording telemetry if the feature is disabled
if (this.isDisabled) {
this.debug('telemetry disabled');
return Promise.resolve();
}

const meta: EventMeta = {
...getSystemInfo({ astroVersion: this.astroVersion, viteVersion: this.viteVersion }),
isGit: this.anonymousProjectInfo.isGit,
};

const context: EventContext = {
...this.anonymousProjectInfo,
anonymousId: this.anonymousId,
anonymousProjectId: this.anonymousProjectInfo.anonymousProjectId,
anonymousSessionId: this.anonymousSessionId,
};

Expand All @@ -150,6 +137,15 @@ export class AstroTelemetry {
context.anonymousId = `CI.${meta.ciName || 'UNKNOWN'}`;
}

if (this.debug.enabled) {
// Print to standard error to simplify selecting the output
this.debug({ context, meta });
this.debug(JSON.stringify(events, null, 2));
// Do not send the telemetry data if debugging. Users may use this feature
// to preview what data would be sent.
return Promise.resolve();
}

return post({
context,
meta,
Expand Down
32 changes: 29 additions & 3 deletions packages/telemetry/src/project-info.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { execSync } from 'child_process';
import type { BinaryLike } from 'node:crypto';
import { createHash } from 'node:crypto';
import detectPackageManager from 'which-pm-runs';

/**
* Astro Telemetry -- Project Info
Expand Down Expand Up @@ -46,9 +47,13 @@ import { createHash } from 'node:crypto';

export interface ProjectInfo {
/* Your unique project identifier. This will be hashed again before sending. */
anonymousProjectId: string;
anonymousProjectId: string | undefined;
/* true if your project is connected to a git repository. false otherwise. */
isGit: boolean;
/* The package manager used to run Astro */
packageManager: string | undefined;
/* The version of the package manager used to run Astro */
packageManagerVersion: string | undefined;
}

function createAnonymousValue(payload: BinaryLike): string {
Expand All @@ -75,16 +80,37 @@ function getProjectIdFromGit(): string | null {
}
}

export function getProjectInfo(isCI: boolean): ProjectInfo {
function getProjectId(isCI: boolean): Pick<ProjectInfo, 'isGit' | 'anonymousProjectId'> {
const projectIdFromGit = getProjectIdFromGit();
if (projectIdFromGit) {
return {
isGit: true,
anonymousProjectId: createAnonymousValue(projectIdFromGit),
};
}
// If we're running in CI, the current working directory is not unique.
// If the cwd is a single level deep (ex: '/app'), it's probably not unique.
const cwd = process.cwd();
const isCwdGeneric = (cwd.match(/[\/|\\]/g) || []).length === 1;
if (isCI || isCwdGeneric) {
return {
isGit: false,
anonymousProjectId: undefined,
};
}
return {
isGit: false,
anonymousProjectId: isCI ? '' : createAnonymousValue(process.cwd()),
anonymousProjectId: createAnonymousValue(cwd),
};
}

export function getProjectInfo(isCI: boolean): ProjectInfo {
const projectId = getProjectId(isCI);
const packageManager = detectPackageManager();
return {
...projectId,
packageManager: packageManager?.name,
packageManagerVersion: packageManager?.version,
};
}
//
25 changes: 21 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit eedb32c

Please sign in to comment.