headreel 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -78,32 +78,59 @@ You need:
78
78
 
79
79
  The Action and the command use the same settings.
80
80
 
81
- | Action input | Command flag | Default | Description |
82
- | ---------------- | ---------------------- | ------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
83
- | `style` | `--style` | (required) | The banner style. See [Styles](#styles). |
84
- | `username` | `--user` | repository owner | The GitHub user to show. The command requires it. |
85
- | `tagline` | `--tagline` | empty | One line under your name. |
86
- | `website` | `--website` | empty | Your website. |
87
- | `handle` | `--handle` | empty | A handle, for styles that show one. |
88
- | `options` | `--option <key=value>` | empty | Style options. Action: one `key: value` on each line. Command: repeat the flag, for example `--option beacons=5`. |
89
- | `output` | `--out` | `headreel.gif` | The path of the banner. |
90
- | `token` | `--token` | `github.token` | The token that reads your GitHub data. |
91
- | `publish_mode` | - | `commit` | `commit` adds a commit on every update. `branch` keeps one commit on its own branch, replaced on every update. |
92
- | `commit_to` | - | checked-out branch / `headreel` | The branch that gets the banner. The default is `headreel` in `branch` mode. |
93
- | `commit_message` | - | `chore: update headreel banner` | The commit message. |
94
- | - | `--config <file>` | - | A JSON file with these settings. Flags replace its values. |
81
+ | Action input | Command flag | Default | Description |
82
+ | ---------------- | ---------------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
83
+ | `style` | `--style` | (required) | The banner style. See [Styles](#styles). |
84
+ | `username` | `--user` | repository owner | The GitHub user to show. The command requires it. |
85
+ | `tagline` | `--tagline` | empty | One line under your name. |
86
+ | `website` | `--website` | empty | Your website. |
87
+ | `handle` | `--handle` | empty | A handle, for styles that show one. |
88
+ | `options` | `--option <key=value>` | empty | Style options. Action: one `key: value` on each line. Command: repeat the flag, for example `--option accent=green`. |
89
+ | `output` | `--out` | `headreel.gif` | The path of the banner. |
90
+ | `token` | `--token` | `github.token` | The token that reads your GitHub data. |
91
+ | `publish_mode` | - | `commit` | `commit` adds a commit on every update. `branch` keeps one commit on its own branch, replaced on every update. |
92
+ | `commit_to` | - | checked-out branch / `headreel` | The branch that gets the banner. The default is `headreel` in `branch` mode. |
93
+ | `commit_message` | - | `chore: update headreel banner` | The commit message. |
94
+ | - | `--config <file>` | - | A JSON file with these settings. Flags replace its values. |
95
95
 
96
96
  Empty settings do not show on the banner. Your name comes from your GitHub profile. If your profile has no name, the banner shows your username.
97
97
 
98
98
  ## Styles
99
99
 
100
+ Set the style with `style: <name>` in the Action, or `--style <name>` in the command. Set an option with `options: 'accent: green'` in the Action, or `--option accent=green` in the command. For more than one option in the Action, put each on its own line.
101
+
100
102
  ### Contribution City
101
103
 
102
104
  `contribution-city`: each day of the last 12 months is one building. A taller building means more contributions. Beacons glow on your busiest days.
103
105
 
104
- | Option | Default | Description |
105
- | --------- | ------- | -------------------------------------------------- |
106
- | `beacons` | `8` | The number of busiest days with a beacon, 0 to 10. |
106
+ ![Contribution City banner](https://raw.githubusercontent.com/arifszn/headreel/main/docs/samples/contribution-city.gif)
107
+
108
+ | Option | Default | Description |
109
+ | -------- | ------- | --------------------------------------------------------------------------------------------- |
110
+ | `accent` | `cyan` | Color of the roofs, windows, lights and links: `cyan`, `cobalt`, `green`, `violet` or `pink`. |
111
+
112
+ ### Highlights Reel
113
+
114
+ `highlights-reel`: a few profile facts, each on its own card, filmed by one camera. The camera travels between the cards, pushes into your busiest week, and ends on a wide shot of the whole reel.
115
+
116
+ ![Highlights Reel banner](https://raw.githubusercontent.com/arifszn/headreel/main/docs/samples/highlights-reel.gif)
117
+
118
+ | Option | Default | Description |
119
+ | -------- | -------- | -------------------------------------------------------------------------------------- |
120
+ | `theme` | `light` | `light` or `dark`. Use `dark` if your profile is mostly viewed in GitHub dark mode. |
121
+ | `accent` | `cobalt` | Color of the bars, numbers and links: `cobalt`, `green`, `violet`, `orange` or `pink`. |
122
+
123
+ ### Now Playing
124
+
125
+ `now-playing`: a cassette deck playing the repository you committed to most in the last 30 days. The label names its language, your commit messages on it scroll across the deck's display as lyrics, and the level meter shows the month day by day. When nothing was committed in the last 30 days, the deck shows the repository you pushed to last as `LAST PLAYED`.
126
+
127
+ ![Now Playing banner](https://raw.githubusercontent.com/arifszn/headreel/main/docs/samples/now-playing.gif)
128
+
129
+ | Option | Default | Description |
130
+ | --------- | ------- | --------------------------------------------------------------------------------------------------- |
131
+ | `theme` | `dark` | `dark` (graphite deck) or `light` (silver deck). |
132
+ | `accent` | `cyan` | Display color, meter and links: `cyan`, `green` or `orange`. |
133
+ | `exclude` | empty | Comma-separated repositories never picked, for example your profile repository: `exclude: octocat`. |
107
134
 
108
135
  ### Repo Galaxy
109
136
 
@@ -117,8 +144,6 @@ Empty settings do not show on the banner. Your name comes from your GitHub profi
117
144
  | `include_forks` | `false` | Show forked repositories too. |
118
145
  | `labels` | `top3` | `top3` names the three most starred repositories. `none` hides names. |
119
146
 
120
- Set an option with `options: 'beacons: 5'` in the Action, or `--option beacons=5` in the command. For more than one option in the Action, put each on its own line.
121
-
122
147
  ## Troubleshooting
123
148
 
124
149
  | Problem | Fix |
@@ -126,3 +151,11 @@ Set an option with `options: 'beacons: 5'` in the Action, or `--option beacons=5
126
151
  | "Permission denied" or 403 error | Add `permissions: contents: write` to the workflow file. |
127
152
  | "Could not resolve to a User" | Set `username` to a valid GitHub username. |
128
153
  | "No GitHub token found" | Run `gh auth login`, or set `GITHUB_TOKEN`. |
154
+
155
+ ## Support
156
+
157
+ If headreel is useful to you, please [star the repository](https://github.com/arifszn/headreel). It helps other people find it.
158
+
159
+ ## License
160
+
161
+ [MIT License](./LICENSE).
Binary file
@@ -0,0 +1,93 @@
1
+ Copyright 2014 The Caveat Project Authors (https://github.com/googlefonts/caveat)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
package/dist/cli/run.js CHANGED
@@ -24,7 +24,7 @@ async function render(settings, io) {
24
24
  throw new Error(`Output must be a .gif file, got "${settings.out}".`);
25
25
  }
26
26
  // Fail on bad options before any API call.
27
- parseOptions(style, settings.options);
27
+ const options = parseOptions(style, settings.options);
28
28
  let login;
29
29
  let name;
30
30
  let data;
@@ -38,7 +38,7 @@ async function render(settings, io) {
38
38
  const user = settings.user;
39
39
  const [profile, fetched] = await Promise.all([
40
40
  fetchProfile(client, user),
41
- style.data.fetch(client, user, io.now()),
41
+ style.data.fetch(client, user, io.now(), options),
42
42
  ]);
43
43
  ({ login, name } = profile);
44
44
  data = fetched;
@@ -32,6 +32,17 @@ export const contributionsSchema = z.object({
32
32
  /** Calendar columns, oldest first. First and last weeks may be partial. */
33
33
  weeks: z.array(z.array(daySchema)),
34
34
  });
35
+ /** Normalizes the GraphQL contribution calendar into the stored shape. */
36
+ export function normalizeCalendar(calendar, from, to) {
37
+ return {
38
+ from,
39
+ to,
40
+ total: calendar.totalContributions,
41
+ weeks: calendar.weeks.map((week) => week.contributionDays
42
+ .map((d) => ({ date: d.date, weekday: d.weekday, count: d.contributionCount }))
43
+ .sort((a, b) => a.date.localeCompare(b.date))),
44
+ };
45
+ }
35
46
  const DAY_MS = 86_400_000;
36
47
  /**
37
48
  * The 365 days ending on `now` (UTC), matching GitHub's profile calendar.
@@ -51,13 +62,5 @@ export async function fetchContributions(client, login, now) {
51
62
  from: `${from}T00:00:00Z`,
52
63
  to: `${to}T23:59:59Z`,
53
64
  });
54
- const calendar = user.contributionsCollection.contributionCalendar;
55
- return {
56
- from,
57
- to,
58
- total: calendar.totalContributions,
59
- weeks: calendar.weeks.map((week) => week.contributionDays
60
- .map((d) => ({ date: d.date, weekday: d.weekday, count: d.contributionCount }))
61
- .sort((a, b) => a.date.localeCompare(b.date))),
62
- };
65
+ return normalizeCalendar(user.contributionsCollection.contributionCalendar, from, to);
63
66
  }
@@ -0,0 +1,141 @@
1
+ import { z } from 'zod';
2
+ import { contributionWindow, contributionsSchema, normalizeCalendar } from './contributions.js';
3
+ import { MAX_REPOS } from './repos.js';
4
+ // One query for the whole reel: the same 365-day window as Contribution City,
5
+ // the most starred owned public repos (the first is the top repo, the set
6
+ // counts the top languages and the total stars), and all-time merged pull
7
+ // requests.
8
+ const QUERY = /* GraphQL */ `
9
+ query Highlights($login: String!, $first: Int!, $from: DateTime!, $to: DateTime!) {
10
+ user(login: $login) {
11
+ contributionsCollection(from: $from, to: $to) {
12
+ contributionCalendar {
13
+ totalContributions
14
+ weeks {
15
+ contributionDays {
16
+ date
17
+ weekday
18
+ contributionCount
19
+ }
20
+ }
21
+ }
22
+ }
23
+ repos: repositories(
24
+ first: $first
25
+ ownerAffiliations: OWNER
26
+ privacy: PUBLIC
27
+ isFork: false
28
+ orderBy: { field: STARGAZERS, direction: DESC }
29
+ ) {
30
+ nodes {
31
+ name
32
+ stargazerCount
33
+ forkCount
34
+ primaryLanguage {
35
+ name
36
+ color
37
+ }
38
+ }
39
+ }
40
+ pullRequests(states: MERGED) {
41
+ totalCount
42
+ }
43
+ }
44
+ }
45
+ `;
46
+ const topRepoSchema = z.object({
47
+ name: z.string().min(1),
48
+ stars: z.number().int().min(0),
49
+ forks: z.number().int().min(0),
50
+ language: z
51
+ .object({
52
+ name: z.string().min(1),
53
+ /** Linguist color; null when the repo has no language or color. */
54
+ color: z
55
+ .string()
56
+ .regex(/^#[0-9a-fA-F]{6}$/)
57
+ .nullable(),
58
+ })
59
+ .nullable(),
60
+ });
61
+ /** Repos shown as pseudo cards around the top repo, most starred first. */
62
+ export const STARRED_REPOS = 6;
63
+ export const highlightsSchema = z.object({
64
+ contributions: contributionsSchema,
65
+ topRepo: topRepoSchema.nullable(),
66
+ /** Stars summed over the fetched repos. */
67
+ totalStars: z.number().int().min(0),
68
+ /** The most starred repos, top repo first, for the pseudo cards. */
69
+ starredRepos: z
70
+ .array(z.object({
71
+ name: z.string().min(1),
72
+ stars: z.number().int().min(0),
73
+ /** Linguist color of the primary language; null when none. */
74
+ color: z
75
+ .string()
76
+ .regex(/^#[0-9a-fA-F]{6}$/)
77
+ .nullable(),
78
+ }))
79
+ .max(STARRED_REPOS),
80
+ mergedPullRequests: z.number().int().min(0),
81
+ /** Top three languages by repo count over the fetched repos, most first. */
82
+ languages: z
83
+ .array(z.object({
84
+ name: z.string().min(1),
85
+ /** Linguist color; null when no repo sets one. */
86
+ color: z
87
+ .string()
88
+ .regex(/^#[0-9a-fA-F]{6}$/)
89
+ .nullable(),
90
+ count: z.number().int().min(1),
91
+ }))
92
+ .max(3),
93
+ });
94
+ export async function fetchHighlights(client, login, now) {
95
+ const { from, to } = contributionWindow(now);
96
+ const { user } = await client(QUERY, {
97
+ login,
98
+ first: MAX_REPOS,
99
+ from: `${from}T00:00:00Z`,
100
+ to: `${to}T23:59:59Z`,
101
+ });
102
+ const nodes = user.repos.nodes;
103
+ // Languages by repo count, ties by name; repos without a language are skipped.
104
+ const counts = new Map();
105
+ for (const n of nodes) {
106
+ if (!n.primaryLanguage)
107
+ continue;
108
+ const entry = counts.get(n.primaryLanguage.name) ?? {
109
+ color: n.primaryLanguage.color,
110
+ count: 0,
111
+ };
112
+ entry.count++;
113
+ counts.set(n.primaryLanguage.name, entry);
114
+ }
115
+ const languages = [...counts.entries()]
116
+ .sort((a, b) => b[1].count - a[1].count || a[0].localeCompare(b[0]))
117
+ .slice(0, 3)
118
+ .map(([name, { color, count }]) => ({ name, color, count }));
119
+ const top = nodes[0];
120
+ return {
121
+ contributions: normalizeCalendar(user.contributionsCollection.contributionCalendar, from, to),
122
+ topRepo: top
123
+ ? {
124
+ name: top.name,
125
+ stars: top.stargazerCount,
126
+ forks: top.forkCount,
127
+ language: top.primaryLanguage
128
+ ? { name: top.primaryLanguage.name, color: top.primaryLanguage.color }
129
+ : null,
130
+ }
131
+ : null,
132
+ totalStars: nodes.reduce((sum, n) => sum + n.stargazerCount, 0),
133
+ starredRepos: nodes.slice(0, STARRED_REPOS).map((n) => ({
134
+ name: n.name,
135
+ stars: n.stargazerCount,
136
+ color: n.primaryLanguage?.color ?? null,
137
+ })),
138
+ mergedPullRequests: user.pullRequests.totalCount,
139
+ languages,
140
+ };
141
+ }
@@ -0,0 +1,282 @@
1
+ import { z } from 'zod';
2
+ // The tape is the user's most active public repository of the last 30 days.
3
+ // Two queries when something is playing; a third one finds the fallback.
4
+ // Query 1: every repository the user committed to in the window, with its
5
+ // daily commit counts. The user's id feeds the author filter of query 2.
6
+ const QUERY = /* GraphQL */ `
7
+ query NowPlaying($login: String!, $from: DateTime!, $to: DateTime!) {
8
+ user(login: $login) {
9
+ id
10
+ contributionsCollection(from: $from, to: $to) {
11
+ commitContributionsByRepository(maxRepositories: 25) {
12
+ repository {
13
+ name
14
+ owner {
15
+ login
16
+ }
17
+ isPrivate
18
+ primaryLanguage {
19
+ name
20
+ color
21
+ }
22
+ }
23
+ contributions(first: 31) {
24
+ totalCount
25
+ nodes {
26
+ occurredAt
27
+ commitCount
28
+ }
29
+ }
30
+ }
31
+ }
32
+ }
33
+ }
34
+ `;
35
+ // Query 2: the playing repository's default-branch commits authored by the
36
+ // user since the window started. GitHub counts commit contributions on the
37
+ // default branch (or gh-pages) only, the same source as query 1.
38
+ const COMMIT_HISTORY = /* GraphQL */ `
39
+ edges {
40
+ node {
41
+ messageHeadline
42
+ parents {
43
+ totalCount
44
+ }
45
+ }
46
+ }
47
+ `;
48
+ const COMMITS_QUERY = /* GraphQL */ `
49
+ query NowPlayingCommits($owner: String!, $name: String!, $id: ID!, $since: GitTimestamp!) {
50
+ repository(owner: $owner, name: $name) {
51
+ defaultBranchRef {
52
+ target {
53
+ ... on Commit {
54
+ history(author: { id: $id }, since: $since, first: 30) {
55
+ ${COMMIT_HISTORY}
56
+ }
57
+ }
58
+ }
59
+ }
60
+ }
61
+ }
62
+ `;
63
+ // Fallback: the most recently pushed owned public repository and the user's
64
+ // latest commits on it, without `since`. The history rides on every node, so
65
+ // one query covers whichever repository the picker lands on.
66
+ const FALLBACK_QUERY = /* GraphQL */ `
67
+ query NowPlayingFallback($login: String!, $id: ID!, $first: Int!) {
68
+ user(login: $login) {
69
+ repositories(
70
+ first: $first
71
+ ownerAffiliations: OWNER
72
+ privacy: PUBLIC
73
+ isFork: false
74
+ orderBy: { field: PUSHED_AT, direction: DESC }
75
+ ) {
76
+ nodes {
77
+ name
78
+ owner {
79
+ login
80
+ }
81
+ primaryLanguage {
82
+ name
83
+ color
84
+ }
85
+ defaultBranchRef {
86
+ target {
87
+ ... on Commit {
88
+ history(author: { id: $id }, first: 30) {
89
+ ${COMMIT_HISTORY}
90
+ }
91
+ }
92
+ }
93
+ }
94
+ }
95
+ }
96
+ }
97
+ }
98
+ `;
99
+ export const WINDOW_DAYS = 30;
100
+ export const statusSchema = z.enum(['playing', 'last-played', 'empty']);
101
+ const languageSchema = z
102
+ .object({
103
+ name: z.string().min(1),
104
+ /** Linguist color; null when the repo has no language or color. */
105
+ color: z
106
+ .string()
107
+ .regex(/^#[0-9a-fA-F]{6}$/)
108
+ .nullable(),
109
+ })
110
+ .nullable();
111
+ export const nowPlayingSchema = z.object({
112
+ /** Fetch date, YYYY-MM-DD (UTC). */
113
+ asOf: z.iso.date(),
114
+ status: statusSchema,
115
+ repo: z
116
+ .object({
117
+ /** Not always the user: contributions to another user's project show as owner/name. */
118
+ owner: z.string().min(1),
119
+ name: z.string().min(1),
120
+ language: languageSchema,
121
+ })
122
+ .nullable(),
123
+ /** The playing repo's commits in the window; 0 on fallback. */
124
+ commits: z.number().int().min(0),
125
+ /** Its part of all public commits in the window, 0..1. */
126
+ share: z.number().min(0).max(1),
127
+ /** The playing repo's daily commits in the window, oldest first. */
128
+ days: z.array(z.number().int().min(0)).length(WINDOW_DAYS),
129
+ /** The repo's default-branch commit headlines, newest first, merges dropped. */
130
+ lyrics: z.array(z.string().min(1)).max(8),
131
+ });
132
+ const DAY_MS = 86_400_000;
133
+ /**
134
+ * The 30 days ending on `now` (UTC): `from` is 29 days back at midnight, `to`
135
+ * is today, matching the run date the banner is rendered on.
136
+ */
137
+ export function nowPlayingWindow(now) {
138
+ const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
139
+ return {
140
+ from: new Date(today - (WINDOW_DAYS - 1) * DAY_MS).toISOString().slice(0, 10),
141
+ to: new Date(today).toISOString().slice(0, 10),
142
+ asOf: new Date(today).toISOString().slice(0, 10),
143
+ };
144
+ }
145
+ /**
146
+ * The daily commit counts of one repository across the window, oldest first.
147
+ * `occurredAt` days outside the window are dropped.
148
+ */
149
+ export function windowDays(contributions, from, to) {
150
+ const counts = new Map();
151
+ for (const node of contributions.nodes ?? []) {
152
+ counts.set(node.occurredAt.slice(0, 10), (counts.get(node.occurredAt.slice(0, 10)) ?? 0) + node.commitCount);
153
+ }
154
+ const days = [];
155
+ for (let t = Date.parse(`${from}T00:00:00Z`); t <= Date.parse(`${to}T00:00:00Z`); t += DAY_MS) {
156
+ days.push(counts.get(new Date(t).toISOString().slice(0, 10)) ?? 0);
157
+ }
158
+ return days;
159
+ }
160
+ /** Index of the last day with a commit, -1 when the repository had none. */
161
+ function lastActiveIndex(days) {
162
+ for (let i = days.length - 1; i >= 0; i--) {
163
+ if (days[i] > 0)
164
+ return i;
165
+ }
166
+ return -1;
167
+ }
168
+ function excludedBy(exclude) {
169
+ const names = new Set(exclude.map((n) => n.trim().toLowerCase()));
170
+ return (owner, name) => names.has(name.toLowerCase()) || names.has(`${owner}/${name}`.toLowerCase());
171
+ }
172
+ /**
173
+ * Drops excluded names, then picks the playing one: most commits in the
174
+ * window, ties to the latest active day, then name.
175
+ */
176
+ export function pickRepo(candidates, exclude = []) {
177
+ const isExcluded = excludedBy(exclude);
178
+ let best = null;
179
+ for (const c of candidates) {
180
+ if (isExcluded(c.owner, c.name))
181
+ continue;
182
+ if (!best || better(c, best))
183
+ best = c;
184
+ }
185
+ return best;
186
+ }
187
+ function better(a, b) {
188
+ if (a.commits !== b.commits)
189
+ return a.commits > b.commits;
190
+ const ai = lastActiveIndex(a.days);
191
+ const bi = lastActiveIndex(b.days);
192
+ if (ai !== bi)
193
+ return ai > bi;
194
+ return a.name.localeCompare(b.name) < 0;
195
+ }
196
+ /** Merges (more than one parent) and empty headlines never become lyrics. */
197
+ export function lyricsFromHistory(nodes) {
198
+ return nodes
199
+ .filter((n) => n.parents.totalCount <= 1 && n.messageHeadline.trim().length > 0)
200
+ .map((n) => n.messageHeadline.trim())
201
+ .slice(0, 8);
202
+ }
203
+ const ZEROS = Array.from({ length: WINDOW_DAYS }).fill(0);
204
+ export async function fetchNowPlaying(client, login, now, options = {}) {
205
+ const { from, to, asOf } = nowPlayingWindow(now);
206
+ const since = `${from}T00:00:00Z`;
207
+ const { user } = await client(QUERY, {
208
+ login,
209
+ from: since,
210
+ to: `${to}T23:59:59Z`,
211
+ });
212
+ // Private repositories are dropped before anything is picked: repo names
213
+ // and commit messages of private repos never reach the banner.
214
+ const candidates = user.contributionsCollection.commitContributionsByRepository
215
+ .filter((entry) => !entry.repository.isPrivate)
216
+ .map((entry) => ({
217
+ owner: entry.repository.owner.login,
218
+ name: entry.repository.name,
219
+ commits: entry.contributions.totalCount,
220
+ days: windowDays(entry.contributions, from, to),
221
+ language: entry.repository.primaryLanguage
222
+ ? {
223
+ name: entry.repository.primaryLanguage.name,
224
+ color: entry.repository.primaryLanguage.color,
225
+ }
226
+ : null,
227
+ }));
228
+ const picked = pickRepo(candidates, options.exclude ?? []);
229
+ if (picked) {
230
+ const all = candidates.reduce((sum, c) => sum + c.commits, 0);
231
+ const { repository } = await client(COMMITS_QUERY, {
232
+ owner: picked.owner,
233
+ name: picked.name,
234
+ id: user.id,
235
+ since,
236
+ });
237
+ return {
238
+ asOf,
239
+ status: 'playing',
240
+ repo: { owner: picked.owner, name: picked.name, language: picked.language },
241
+ commits: picked.commits,
242
+ share: all > 0 ? picked.commits / all : 0,
243
+ days: picked.days,
244
+ lyrics: lyricsFromHistory(repository?.defaultBranchRef?.target?.history?.edges.map((e) => e.node) ?? []),
245
+ };
246
+ }
247
+ // Nothing playing: the most recently pushed owned public repository, whose
248
+ // latest default-branch commits become the lyrics without a window.
249
+ const fallback = await client(FALLBACK_QUERY, {
250
+ login,
251
+ id: user.id,
252
+ first: 25,
253
+ });
254
+ const isExcluded = excludedBy(options.exclude ?? []);
255
+ const repo = fallback.user.repositories.nodes.find((n) => !isExcluded(n.owner.login, n.name));
256
+ if (!repo) {
257
+ return {
258
+ asOf,
259
+ status: 'empty',
260
+ repo: null,
261
+ commits: 0,
262
+ share: 0,
263
+ days: [...ZEROS],
264
+ lyrics: [],
265
+ };
266
+ }
267
+ return {
268
+ asOf,
269
+ status: 'last-played',
270
+ repo: {
271
+ owner: repo.owner.login,
272
+ name: repo.name,
273
+ language: repo.primaryLanguage
274
+ ? { name: repo.primaryLanguage.name, color: repo.primaryLanguage.color }
275
+ : null,
276
+ },
277
+ commits: 0,
278
+ share: 0,
279
+ days: [...ZEROS],
280
+ lyrics: lyricsFromHistory(repo.defaultBranchRef?.target?.history?.edges.map((e) => e.node) ?? []),
281
+ };
282
+ }