Repository: badges/shields (js)

Issue:
Badge request: Github number of files in directory filtering by type and/or extension
:clipboard: **Description**

For Github.
Include number of files inside repository directory.
Must filter by file extension and/or type. Valid types would be `file`, `dir` or without filtering (both types included).

![](https://img.shields.io/badge/files-100-brightgreen)
![](https://img.shields.io/badge/directories-45-brightgreen)


:link: **Data**

Data from [here](https://api.github.com/repos/badges/shields/contents/services) using the V3 Github API.
API key is optional.
[Endpoint documentation](https://developer.github.com/v3/repos/contents/#get-contents).

:microphone: **Motivation**
This feature will allow us to show how many services are supported currently for bages calling to [this endpoint](https://api.github.com/repos/badges/shields/contents/services) and filtering by `type="dir"`. For example:

![](https://img.shields.io/badge/services-180-brightgreen)

Pull request:
Add [GithubDirectoryFileCount] badge
Resolves #4899.

Patch:
diff --git a/services/github/github-directory-file-count.service.js b/services/github/github-directory-file-count.service.js
new file mode 100644
index 0000000000..fe8d7e14c1
--- /dev/null
+++ b/services/github/github-directory-file-count.service.js
@@ -0,0 +1,159 @@
+'use strict'
+
+const path = require('path')
+const Joi = require('joi')
+const { metric } = require('../text-formatters')
+const { InvalidParameter } = require('..')
+const { ConditionalGithubAuthV3Service } = require('./github-auth-service')
+const {
+  documentation: commonDocumentation,
+  errorMessagesFor,
+} = require('./github-helpers')
+
+const documentation = `${commonDocumentation}
+<p>
+  <b>Note:</b><br>
+  1. Parameter <code>type</code> accepts either <code>file</code> or <code>dir</code> value. Passing any other value will result in an error.<br>
+  2. Parameter <code>extension</code> accepts file extension without a leading dot.
+     For instance for <code>.js</code> extension pass <code>js</code>.
+     Only single <code>extension</code> value can be specified.
+     <code>extension</code> is applicable for <code>type</code> <code>file</code> only.
+     Passing it either without <code>type</code> or along with <code>type</code> <code>dir</code> will result in an error.<br>
+  3. GitHub API has an upper limit of 1,000 files for a directory.
+     In case a directory contains files above the limit, a badge might present inaccurate information.<br>
+</p>
+`
+
+const schema = Joi.alternatives(
+  /*
+   alternative empty object schema to provide a custom error message
+   in the event a file path is provided by the user instead of a directory
+  */
+  Joi.object({}).required(),
+  Joi.array()
+    .items(
+      Joi.object({
+        path: Joi.string().required(),
+        type: Joi.string().required(),
+      })
+    )
+    .required()
+)
+
+const queryParamSchema = Joi.object({
+  type: Joi.any().valid('dir', 'file'),
+  extension: Joi.string(),
+})
+
+module.exports = class GithubDirectoryFileCount extends ConditionalGithubAuthV3Service {
+  static category = 'size'
+
+  static route = {
+    base: 'github/directory-file-count',
+    pattern: ':user/:repo/:path*',
+    queryParamSchema,
+  }
+
+  static examples = [
+    {
+      title: 'GitHub repo file count',
+      pattern: ':user/:repo',
+      namedParams: { user: 'badges', repo: 'shields' },
+      staticPreview: this.render({ count: 20 }),
+      documentation,
+    },
+    {
+      title: 'GitHub repo file count (custom path)',
+      pattern: ':user/:repo/:path',
+      namedParams: { user: 'badges', repo: 'shields', path: 'services' },
+      staticPreview: this.render({ count: 10 }),
+      documentation,
+    },
+    {
+      title: 'GitHub repo directory count',
+      pattern: ':user/:repo',
+      namedParams: { user: 'badges', repo: 'shields' },
+      queryParams: { type: 'dir' },
+      staticPreview: this.render({ count: 8 }),
+      documentation,
+    },
+    {
+      title: 'GitHub repo directory count (custom path)',
+      pattern: ':user/:repo/:path',
+      namedParams: { user: 'badges', repo: 'shields', path: 'services' },
+      queryParams: { type: 'dir' },
+      staticPreview: this.render({ count: 8 }),
+      documentation,
+    },
+    {
+      title: 'GitHub repo file count (file type)',
+      pattern: ':user/:repo',
+      namedParams: { user: 'badges', repo: 'shields' },
+      queryParams: { type: 'file' },
+      staticPreview: this.render({ count: 2 }),
+      documentation,
+    },
+    {
+      title: 'GitHub repo file count (custom path & file type)',
+      pattern: ':user/:repo/:path',
+      namedParams: { user: 'badges', repo: 'shields', path: 'services' },
+      queryParams: { type: 'file' },
+      staticPreview: this.render({ count: 2 }),
+      documentation,
+    },
+    {
+      title: 'GitHub repo file count (file extension)',
+      pattern: ':user/:repo/:path',
+      namedParams: { user: 'badges', repo: 'shields', path: 'services' },
+      queryParams: { extension: 'js' },
+      staticPreview: this.render({ count: 1 }),
+      documentation,
+    },
+  ]
+
+  static defaultBadgeData = { color: 'blue', label: 'files' }
+
+  static render({ count }) {
+    return {
+      message: metric(count),
+    }
+  }
+
+  async fetch({ user, repo, path = '' }) {
+    return this._requestJson({
+      url: `/repos/${user}/${repo}/contents/${path}`,
+      schema,
+      errorMessages: errorMessagesFor('repo or directory not found'),
+    })
+  }
+
+  static transform(files, { type, extension }) {
+    if (!Array.isArray(files)) {
+      throw new InvalidParameter({ prettyMessage: 'not a directory' })
+    }
+
+    if (type !== 'file' && extension) {
+      throw new InvalidParameter({
+        prettyMessage: 'extension is applicable for type file only',
+      })
+    }
+
+    if (type) {
+      files = files.filter(file => file.type === type)
+    }
+
+    if (extension) {
+      files = files.filter(file => path.extname(file.path) === `.${extension}`)
+    }
+
+    return {
+      count: files.length,
+    }
+  }
+
+  async handle({ user, repo, path }, { type, extension }) {
+    const content = await this.fetch({ user, repo, path })
+    const { count } = this.constructor.transform(content, { type, extension })
+    return this.constructor.render({ count })
+  }
+}
diff --git a/services/github/github-directory-file-count.spec.js b/services/github/github-directory-file-count.spec.js
new file mode 100644
index 0000000000..721691ad5b
--- /dev/null
+++ b/services/github/github-directory-file-count.spec.js
@@ -0,0 +1,67 @@
+'use strict'
+
+const { expect } = require('chai')
+const { test, given } = require('sazerac')
+const { InvalidParameter } = require('..')
+const GithubDirectoryFileCount = require('./github-directory-file-count.service')
+
+describe('GithubDirectoryFileCount', function () {
+  const contents = [
+    { path: 'a', type: 'dir' },
+    { path: 'b', type: 'dir' },
+    { path: 'c.js', type: 'file' },
+    { path: 'd.js', type: 'file' },
+    { path: 'e.txt', type: 'file' },
+    { path: 'f', type: 'submodule' },
+  ]
+
+  test(GithubDirectoryFileCount.transform, () => {
+    given(contents, {
+      type: 'dir',
+    }).expect({
+      count: 2,
+    })
+    given(contents, {
+      type: 'file',
+    }).expect({
+      count: 3,
+    })
+    given(contents, {
+      type: 'file',
+      extension: 'js',
+    }).expect({
+      count: 2,
+    })
+  })
+
+  it('throws InvalidParameter on receving an object as contents instead of an array', function () {
+    expect(() => GithubDirectoryFileCount.transform({}, {}))
+      .to.throw(InvalidParameter)
+      .with.property('prettyMessage', 'not a directory')
+  })
+
+  it('throws InvalidParameter on receving type dir and extension', function () {
+    expect(() =>
+      GithubDirectoryFileCount.transform(contents, {
+        type: 'dir',
+        extension: 'js',
+      })
+    )
+      .to.throw(InvalidParameter)
+      .with.property(
+        'prettyMessage',
+        'extension is applicable for type file only'
+      )
+  })
+
+  it('throws InvalidParameter on receving no type and extension', function () {
+    expect(() =>
+      GithubDirectoryFileCount.transform(contents, { extension: 'js' })
+    )
+      .to.throw(InvalidParameter)
+      .with.property(
+        'prettyMessage',
+        'extension is applicable for type file only'
+      )
+  })
+})


Test patch:
diff --git a/services/github/github-directory-file-count.tester.js b/services/github/github-directory-file-count.tester.js
new file mode 100644
index 0000000000..2ea38495e3
--- /dev/null
+++ b/services/github/github-directory-file-count.tester.js
@@ -0,0 +1,30 @@
+'use strict'
+
+const { isMetric } = require('../test-validators')
+const t = (module.exports = require('../tester').createServiceTester())
+
+t.create('directory file count').get('/badges/shields.json').expectBadge({
+  label: 'files',
+  message: isMetric,
+})
+
+t.create('directory file count (custom path)')
+  .get('/badges/shields/services.json')
+  .expectBadge({
+    label: 'files',
+    message: isMetric,
+  })
+
+t.create('directory file count (directory not found)')
+  .get('/badges/shields/not_existing_directory.json')
+  .expectBadge({
+    label: 'files',
+    message: 'repo or directory not found',
+  })
+
+t.create('directory file count (not a directory)')
+  .get('/badges/shields/package.json.json')
+  .expectBadge({
+    label: 'files',
+    message: 'not a directory',
+  })