Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

detect package manager and improve types #3847

Merged
merged 1 commit into from
Jul 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Callout that we have a which-pm helper in create-astro already! Pulled from Vite's create-vite package, and looks roughly the same as the which-pm-runs source code. Happy to pull in this package though given how small it is 🤷 Your call on which we'd prefer

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you mean preferred-pm, which I'd be happy to use but has an async-only API and this needs to be quick and sync. That's also more complex since it looks at your file system, reads up directory trees for different lockfiles, etc.

I actually wonder if create-astro should be moved to which-pm-runs, since actually don't want that data when running create-astro.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually wait, it looks like it's used in add, and not create-astro. That actually needs to rely on your file system and not just which pm you used to run command with, so we can keep as is.

create-astro is using a custom solution, which could probably be replaced with this to save us some maintainance.

},
"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) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved this down here so that it would output all data collected, not just the specific event payload.

// 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,
};
}
//
36 changes: 32 additions & 4 deletions pnpm-lock.yaml

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