pax_global_header 0000666 0000000 0000000 00000000064 14242001551 0014504 g ustar 00root root 0000000 0000000 52 comment=2c1b5591a61bf18fc604112896479f72c102e3e2
github-metadata-2.15.0/ 0000775 0000000 0000000 00000000000 14242001551 0014631 5 ustar 00root root 0000000 0000000 github-metadata-2.15.0/.editorconfig 0000664 0000000 0000000 00000000320 14242001551 0017301 0 ustar 00root root 0000000 0000000 # editorconfig.org
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
github-metadata-2.15.0/.github/ 0000775 0000000 0000000 00000000000 14242001551 0016171 5 ustar 00root root 0000000 0000000 github-metadata-2.15.0/.github/dependabot.yml 0000664 0000000 0000000 00000000223 14242001551 0021016 0 ustar 00root root 0000000 0000000 version: 2
updates:
- package-ecosystem: bundler
directory: "/"
schedule:
interval: daily
time: "11:00"
open-pull-requests-limit: 99
github-metadata-2.15.0/.github/workflows/ 0000775 0000000 0000000 00000000000 14242001551 0020226 5 ustar 00root root 0000000 0000000 github-metadata-2.15.0/.github/workflows/ci.yaml 0000664 0000000 0000000 00000001355 14242001551 0021511 0 ustar 00root root 0000000 0000000 ---
name: Continuous Integration
on:
push:
branches:
- main
- /.*-stable/
pull_request:
branches:
- main
- /.*-stable/
jobs:
ci:
if: "!contains(github.event.commits[0].message, '[ci skip]')"
name: 'Ruby ${{ matrix.ruby_version }} ${{ matrix.os }}'
runs-on: '${{ matrix.os }}'
strategy:
fail-fast: false
matrix:
ruby_version:
- 2.7
- '3.0'
os:
- ubuntu-latest
- windows-latest
steps:
- uses: actions/checkout@v2
- uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby_version }}
bundler-cache: true # runs 'bundle install' and caches installed gems automatically
- run: script/cibuild
github-metadata-2.15.0/.github/workflows/release.yml 0000664 0000000 0000000 00000001462 14242001551 0022374 0 ustar 00root root 0000000 0000000 name: Release Gem
on:
push:
branches:
- main
paths:
- "lib/**/version.rb"
jobs:
release:
if: "github.repository_owner == 'jekyll'"
name: "Release Gem (Ruby ${{ matrix.ruby_version }})"
runs-on: "ubuntu-latest"
strategy:
fail-fast: true
matrix:
ruby_version:
- 2.7
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: "Set up Ruby ${{ matrix.ruby_version }}"
uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby_version }}
bundler-cache: true
- name: Build and Publish Gem
uses: ashmaroli/release-gem@dist
with:
gemspec_name: jekyll-github-metadata
env:
GEM_HOST_API_KEY: ${{ secrets.RUBYGEMS_GEM_PUSH_API_KEY }}
github-metadata-2.15.0/.gitignore 0000664 0000000 0000000 00000000133 14242001551 0016616 0 ustar 00root root 0000000 0000000 .bundle/
vendor/
.tags*
Gemfile.lock
pkg
_site/
tmp/
*.gem
.jekyll-cache/
.jekyll-metadata
github-metadata-2.15.0/.rspec 0000664 0000000 0000000 00000000055 14242001551 0015746 0 ustar 00root root 0000000 0000000 --color
--require spec_helper
--order random
github-metadata-2.15.0/.rubocop.yml 0000664 0000000 0000000 00000001035 14242001551 0017102 0 ustar 00root root 0000000 0000000 inherit_from: .rubocop_todo.yml
require: rubocop-jekyll
inherit_gem:
rubocop-jekyll: .rubocop.yml
AllCops:
TargetRubyVersion: 2.5
Exclude:
- vendor/**/*
- script/*
Metrics/LineLength:
Enabled: false
Metrics/BlockLength:
Exclude:
- spec/**/*
Metrics/MethodLength:
Exclude:
- spec/**/*
Style/AccessModifierDeclarations:
Enabled: false
Style/FrozenStringLiteralComment:
Exclude:
- lib/jekyll-github-metadata/site_github_munger.rb
- spec/edit_link_tag_spec.rb
- spec/site_github_munger_spec.rb
github-metadata-2.15.0/.rubocop_todo.yml 0000664 0000000 0000000 00000006550 14242001551 0020136 0 ustar 00root root 0000000 0000000 # This configuration was generated by
# `rubocop --auto-gen-config`
# on 2022-04-20 05:48:15 UTC using RuboCop version 1.18.4.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.
# Offense count: 1
# Configuration parameters: Include.
# Include: **/*.gemspec
Gemspec/RequiredRubyVersion:
Exclude:
- 'jekyll-github-metadata.gemspec'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: AllowAliasSyntax, AllowedMethods.
# AllowedMethods: alias_method, public, protected, private
Layout/EmptyLinesAroundAttributeAccessor:
Exclude:
- 'lib/jekyll-github-metadata/repository_finder.rb'
# Offense count: 2
# Configuration parameters: AllowedMethods.
# AllowedMethods: enums
Lint/ConstantDefinitionInBlock:
Exclude:
- 'spec/owner_spec.rb'
# Offense count: 1
# Configuration parameters: IgnoreLiteralBranches, IgnoreConstantBranches.
Lint/DuplicateBranch:
Exclude:
- 'lib/jekyll-github-metadata/sanitizer.rb'
# Offense count: 1
# Configuration parameters: AllowComments, AllowEmptyLambdas.
Lint/EmptyBlock:
Exclude:
- 'spec/edit_link_tag_spec.rb'
# Offense count: 1
# Cop supports --auto-correct.
Lint/RedundantCopDisableDirective:
Exclude:
- 'lib/jekyll-github-metadata/client.rb'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: AllowedMethods.
# AllowedMethods: instance_of?, kind_of?, is_a?, eql?, respond_to?, equal?
Lint/RedundantSafeNavigation:
Exclude:
- 'lib/jekyll-github-metadata/repository_finder.rb'
# Offense count: 1
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
# SupportedStyles: strict, consistent
Lint/SymbolConversion:
Exclude:
- 'spec/github_metadata_spec.rb'
# Offense count: 1
# Configuration parameters: IgnoredMethods, CountRepeatedAttributes.
Metrics/AbcSize:
Max: 22
# Offense count: 1
# Configuration parameters: EnforcedStyle, CheckMethodNames, CheckSymbols, AllowedIdentifiers.
# SupportedStyles: snake_case, normalcase, non_integer
# AllowedIdentifiers: capture3, iso8601, rfc1123_date, rfc822, rfc2822, rfc3339
Naming/VariableNumber:
Exclude:
- 'spec/spec_helpers/web_mock_helper.rb'
# Offense count: 1
Performance/ChainArrayAllocation:
Exclude:
- 'lib/jekyll-github-metadata/repository_finder.rb'
# Offense count: 1
# Cop supports --auto-correct.
Style/NegatedIfElseCondition:
Exclude:
- 'lib/jekyll-github-metadata/pages.rb'
# Offense count: 1
# Configuration parameters: AllowedMethods.
# AllowedMethods: respond_to_missing?
Style/OptionalBooleanParameter:
Exclude:
- 'lib/jekyll-github-metadata/client.rb'
# Offense count: 3
# Cop supports --auto-correct.
Style/RedundantBegin:
Exclude:
- 'lib/jekyll-github-metadata/metadata_drop.rb'
- 'lib/jekyll-github-metadata/owner.rb'
- 'lib/jekyll-github-metadata/repository_finder.rb'
# Offense count: 3
# Cop supports --auto-correct.
Style/RedundantRegexpEscape:
Exclude:
- 'lib/jekyll-github-metadata/edit-link-tag.rb'
- 'lib/jekyll-github-metadata/repository_finder.rb'
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: Mode.
Style/StringConcatenation:
Exclude:
- 'spec/edit_link_tag_spec.rb'
- 'spec/value_spec.rb'
github-metadata-2.15.0/.travis.yml 0000664 0000000 0000000 00000001145 14242001551 0016743 0 ustar 00root root 0000000 0000000 # DO NOT EDIT THIS FILE DIRECTLY! Instead, modify it
# in the source repo: jekyll/carbon-copy-content.
language: ruby
cache: bundler
rvm:
- &latest_ruby 2.6
- 2.5
- 2.4
matrix:
include:
- rvm: *latest_ruby
env: JEKYLL_VERSION=4.0 FARADAY_VERSION=0.17
- rvm: *latest_ruby
env: JEKYLL_VERSION=3.7 FARADAY_VERSION=0.17
- rvm: *latest_ruby
env: JEKYLL_VERSION=3.7 FARADAY_VERSION=1.0
branches:
only:
- master
before_install:
- gem update --system
before_script: bundle update
script: script/cibuild
notifications:
email:
on_success: never
on_failure: never
github-metadata-2.15.0/Gemfile 0000664 0000000 0000000 00000000453 14242001551 0016126 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
source "https://rubygems.org"
gemspec
gem "faraday", "~> #{ENV["FARADAY_VERSION"]}" if ENV["FARADAY_VERSION"]
gem "jekyll", "~> #{ENV["JEKYLL_VERSION"]}" if ENV["JEKYLL_VERSION"]
group :test do
gem "webmock", "~> 3.14"
end
gem "webrick" if RUBY_VERSION.to_i >= 3
github-metadata-2.15.0/History.markdown 0000664 0000000 0000000 00000017473 14242001551 0020052 0 ustar 00root root 0000000 0000000 ## 2.15.0 / 2022-05-20
### Bug Fixes
* Inject `site.github` via `:pre_render` step rather than `:after_init` (#238)
### Documentation
* Add GitHub Actions badge and remove Travis one (#236)
## 2.14.0 / 2022-05-04
### Minor Enhancements
* Use owner name as site title for User and Organization sites. (#197)
* Add `site.github.public_repositories[].releases` (#224)
* Add `site.github.public_repositories[].contributors` (#234)
### Documentation
* docs: Add dev docs (#212)
* set `PAGES_GITHUB_HOSTNAME` to hostname without protocol (#191)
* Add `JEKYLL_ENV` limitation for git remote (#185)
### Development Fixes
* Restore log level after running tests that modify it. (#202)
* Add GitHub Actions CI (#211)
* Update rubocop-jekyll requirement from `~> 0.5.0` to `~> 0.12.0` (#226)
* Create dependabot.yml (#225)
* Add rubocop todo file (#230)
* Upgrade rspec to 3.11.x (#231)
* CI: use 'main' branch instead of 'master' (#232)
* Add release workflow (#235)
## 2.13.0 / 2020-01-15
### Minor Enhancements
* Lessen Jekyll dependency (#164)
* Enable support for `topics` property (#166)
* Allow detecting archived or disabled repos (#176)
### Bug Fixes
* Conditionally memoize certain private methods in EditLinkTag (#163)
* Fix faraday connectionfailed issue (#178)
* MetadataDrop: don't use instance variable to check mutations (#173)
### Documentation Fixes
* List the fields this repo generates for `site.github` (#171)
* Use HTML entities to prevent Liquid from processing this documentation (#172)
## 2.12.1 / 2019-02-11
### Bug Fixes
* Add `Owner#to_liquid` (#161)
## 2.12.0 / 2019-02-11
### Bug Fixes
* `site.owner` should be a `Hash` in the final value (#160)
## 2.11.0 / 2019-01-29
### Minor Enhancements
* Expose User/Org information under `site.github.owner` (#151)
* Add new attributes to return for users and repositories (#158)
* Move `owner_metadata` to an Owner class and add specs (#159)
### Development Fixes
* Fix specs to be compatible with forked repositories (#152)
* Update CI settings and use rubocop-jekyll (#150)
## 2.10.0 / 2019-01-02
### Minor Enhancements
* Allow detecting repository on GitHub Enterprise (#147)
* Remove redundant code (#140)
* Constant accessors for `def_delegation` (#141)
### Bug Fixes
* Fixes for repository detection on Windows (#136)
* Make github.com repo URLs always https (#133)
### Documentation
* Add instructions for using DotEnv (#92)
### Development Fixes
* Test against Ruby 2.5 (#119)
* Add script/console to help debug (#124)
## 2.9.4 / 2017-12-08
### Minor Enhancements
* Warn and do nothing when site.name is set (#113)
### Documentation
* Docs: use plugins config key (#115)
## 2.9.3 / 2017-09-07
* Mutable drops should fallback to their own methods when a mutation isn't present #112
## 2.9.2 / 2017-09-07
### Minor Enhancements
* Allow user values to override drop-determined values (#110)
## 2.9.1 / 2017-08-28
* Fix for "undefined method `path` for Hash" error
## 2.9.0 / 2017-08-28
* GitHub edit link tag (#108)
* Define path with __dir__ (#109)
## 2.8.0 / 2017-08-15
### Minor Enhancements
* Expose site source (#107)
## 2.7.0 / 2017-08-14
### Minor Enhancements
* Expose repo license (#106)
## 2.6.0 / 2017-08-08
### Minor Enhancements
* Set title and description in dev (#104)
* Detect whether the client is connected to the internet. Only allow client calls if connected. (#90)
* Expose repo visibility (#105)
## 2.5.0 / 2017-07-17
* Set default `site.title` and `site.description` (#101)
* Modernize Travis configuration (#102)
* Allow user to set empty `baseurl` (#97)
* add `latest_release` and `latest_release_url` (#88)
* Make the Octokit client more configurable. (#84)
## 2.4.0 / 2017-03-30
### Minor Enhancements
* Don't double-process the site.github namespace. (#95)
* Add .configuration and .page_build? methods to Pages (#89)
## 2.3.1 / 2017-01-18
* Remove log on Octokit::NotFound (#86)
## 2.3.0 / 2017-01-09
### Minor Enhancements
* Respect source passed from the API (#85)
## 2.2.0 / 2016-10-25
### Minor Enhancements
* If a user provides bad credentials, throw an error. (#75)
### Bug Fixes
* Add `MetadataDrop#to_s` which outputs pretty JSON representation (#78)
* Lock Octokit to v4.3.0 (#79)
* Revert "Lock Octokit to v4.3.0", but disallow v4.4.0 (#81)
## 2.1.1 / 2016-10-07
### Bug Fixes
* Remove the `path` before setting `site.url` (#77)
## 2.1.0 / 2016-10-05
### Major Enhancements
* Set site.url and site.baseurl (#76)
* Use `localhost:4000` as the default pages host in development (#50)
* Default to development in dev (#49)
### Minor Enhancements
* Fix a typo in the documentation of `PAGES_API_URL` (#66)
* Additional feedback for failed Octokit calls (#68)
* Add Rubocop (#69)
## 2.0.2 / 2016-06-22
* Remove trailing slash from html_url if present (#64)
## 2.0.1 / 2016-06-19
* Fix issue where `git` not being in `$PATH` would error (#57)
* Handle dots in repository names when parsing from Git remote output (#63)
## 2.0.0 / 2016-05-26
### Major Enhancements
* Only allow Jekyll 3.1 and above (#61)
### Minor Enhancements
* Use html_url from Pages endpoint (behind preview env flag) (#60)
* Only determine repo when data is requested using a Drop (#61)
## 1.11.1 / 2016-04-22
* Make the `Client::API_CALLS` a Set (#56)
## 1.11.0 / 2016-04-08
* make empty string fallback for missing git remote (#54)
* Refactor some of the git things & better docs (#55)
## 1.10.0 / 2016-03-25
* Use git remote url to determine nwo (#45)
## 1.9.0 / 2016-03-16
* Mark the generator as safe so in safe mode it'll work (#42)
## 1.8.0 / 2016-03-09
* Properly determine project page domain by breaking the cache on different args (#40)
## 1.7.0 / 2016-03-02
* Properly calculate the url scheme (#37)
## 1.6.0 / 2016-03-02
* `site.github.environment` should be the same as `site.github.pages_env` (#36)
* Add `Repository#url_scheme` for the pages URL scheme. (#35)
## 1.5.0 / 2016-02-29
* All values should have a corresponding field on `Repository` (#34)
* Happy Leap Day!
## 1.4.0 / 2016-02-19
* Client: whitelist certain `Octokit::Client` methods (#32)
## 1.3.0 / 2016-02-12
* Don't require Jekyll, and only require the Generator when Jekyll has been required
* Client: Fix bug with method call memoization collision with special characters
* Generator: Properly memoize the repository so each regen doesn't re-call
* Pages: `ssl?` should be `true` in test mode
* Pages: `github_hostname` should only include the domain, not the protocol
* Pages: handle subdomain isolation
* Pages: helper methods for `dotcom?`, `test?`, `enterprise?`
* Pages: hardcode https for dotcom GitHub URL
* Pages: api_url, help_url, github_hostname, and pages_hostname should all look at env vars without `PAGES_` prefix
* Repository: `#organization_repository?` should use `Value` to save from errors
* Repository: add in enterprise support & smarter CNAME/domain lookup
## 1.2.0 / 2016-02-05
* Bring up-to-date with current `site.github` offerings on GitHub Pages (#30)
* Add integration tests and ensure we're up-and-running with github-pages (#29)
* Travis: test against Jekyll 2.5 and 3 (#21)
## 1.1.0 / 2015-09-07
* Enable `auto_paginate` for Octokit client so you get everything (#18)
## v1.0.0 / 2015-06-02
* Add `site.github.releases`, an array of your repo's releases. (#9)
* Don't overwrite `site.github` if it's already set. Merge if it's a hash and just leave along if it's non-nil something else. (#15)
* Fall back to Octokit values to be more compatible with the GitHub ecosystem (#10)
* Fix bug where nil, true, false, and hashes were stringified by JSON (#11)
* Add test site to as an integration test (#11)
* Upgrade to Octokit v4.x (#10)
## v0.1.0 / 2014-09-19
* Birthday!
github-metadata-2.15.0/LICENSE 0000664 0000000 0000000 00000002144 14242001551 0015637 0 ustar 00root root 0000000 0000000 The MIT License (MIT)
Copyright (c) 2014-present GitHub, Inc. and the github-metadata contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
github-metadata-2.15.0/Rakefile 0000664 0000000 0000000 00000000073 14242001551 0016276 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "bundler/gem_tasks"
github-metadata-2.15.0/appveyor.yml 0000664 0000000 0000000 00000001564 14242001551 0017227 0 ustar 00root root 0000000 0000000 version: "{build}"
clone_depth: 5
branches:
only:
- main
build: off
environment:
matrix:
- RUBY_FOLDER_VER: "26"
JEKYLL_VERSION: "4.0"
FARADAY_VERSION: "1.0"
- RUBY_FOLDER_VER: "26"
JEKYLL_VERSION: "4.0"
FARADAY_VERSION: "0.17"
- RUBY_FOLDER_VER: "26"
JEKYLL_VERSION: "3.7"
FARADAY_VERSION: "1.0"
- RUBY_FOLDER_VER: "26"
JEKYLL_VERSION: "3.7"
FARADAY_VERSION: "0.17"
- RUBY_FOLDER_VER: "25"
install:
- SET PATH=C:\Ruby%RUBY_FOLDER_VER%-x64\bin;%PATH%
- bundle install --retry 5 --jobs=%NUMBER_OF_PROCESSORS% --clean --path vendor\bundle
test_script:
- ruby --version
- gem --version
- bundler --version
- bash ./script/test
cache:
# If one of the files after the right arrow changes, cache will be invalidated
- 'vendor\bundle -> appveyor.yml,Gemfile,jekyll-github-metadata.gemspec'
github-metadata-2.15.0/docs/ 0000775 0000000 0000000 00000000000 14242001551 0015561 5 ustar 00root root 0000000 0000000 github-metadata-2.15.0/docs/README.md 0000664 0000000 0000000 00000003102 14242001551 0017034 0 ustar 00root root 0000000 0000000 # GitHub Metadata, a.k.a. `site.github`
[](https://github.com/jekyll/github-metadata/actions/workflows/ci.yaml)
[][appveyor]
[travis]: https://travis-ci.org/jekyll/github-metadata
[appveyor]: https://ci.appveyor.com/project/jekyll/github-metadata
Jekyll plugin to propagate the `site.github` namespace and set default values for use with GitHub Pages.
## What it does
* Propagates the `site.github` namespace with [repository metadata](site.github.md)
* Sets `site.title` as the repository name, if none is set
* Sets `site.description` as the repository tagline if none is set
* Sets `site.url` as the GitHub Pages domain (cname or user domain), if none is set
* Sets `site.baseurl` as the project name for project pages if none is set
## Usage
Usage of this gem is pretty straight-forward. Add it to your `Gemfile` like this:
```ruby
gem "jekyll-github-metadata"
```
Add it to your `_config.yml`:
```yaml
plugins:
- "jekyll-github-metadata"
```
:warning: If you are using Jekyll < 3.5.0, use the `gems` key instead of `plugins`.
Then go ahead and run `bundle install`.
Now, whenever you build or serve with Jekyll, the `jekyll-github-metadata` plugin will run.
## Further reading
* [Authentication](authentication.md)
* [Configuration](configuration.md)
* [Using `site.github`](site.github.md)
* [Edit on GitHub link](edit-on-github-link.md)
* [Development](development.md)
github-metadata-2.15.0/docs/_config.yml 0000664 0000000 0000000 00000000051 14242001551 0017704 0 ustar 00root root 0000000 0000000 permalink: pretty
title: GitHub Metadata
github-metadata-2.15.0/docs/authentication.md 0000664 0000000 0000000 00000004002 14242001551 0021116 0 ustar 00root root 0000000 0000000 ## Authentication
For some fields, like `cname`, you need to authenticate yourself. Luckily it's pretty easy. First, you need to generate a personal access token (an oauth token will work too but it's good to have a token for each purpose so you can revoke them later without breaking everything):
To generate a new personal access token on GitHub.com:
- Open https://github.com/settings/tokens/new
- Select the scope *public_repository*, and add a description.
- Confirm and save the settings. Copy the token you see on the page.
Once you have your token, you have three ways to pass it to this program:
### 1. `JEKYLL_GITHUB_TOKEN`
These tokens are easy to use and delete so if you move around from machine-to-machine, we'd recommend this route. Set `JEKYLL_GITHUB_TOKEN` to your access token (with `public_repo` scope for public repositories or `repo` scope for private repositories) when you run `jekyll`, like this:
```bash
$ JEKYLL_GITHUB_TOKEN=123abc [bundle exec] jekyll serve
```
### 2. `~/.netrc`
If you prefer to use the good ol' `~/.netrc` file, just make sure the `netrc` gem is bundled and run `jekyll` like normal. So if I were to add it, I'd add `gem 'netrc'` to my `Gemfile`, run `bundle install`, then run `bundle exec jekyll build`. The `machine` directive should be `api.github.com`.
```netrc
machine api.github.com
login github-username
password 123abc-your-token
```
### 3. Octokit
We use [Octokit](https://github.com/octokit/octokit.rb) to make the appropriate API responses to fetch the metadata. You may set `OCTOKIT_ACCESS_TOKEN` and it will be used to access GitHub's API.
```bash
$ OCTOKIT_ACCESS_TOKEN=123abc [bundle exec] jekyll serve
```
## DotEnv
Rather than prefixing your shell commands with the environmental variables all the time, you can use the
[Dotenv](https://github.com/bkeepers/dotenv) gem. Simply install it by adding it to your Gemfile, then create a `.env` file and populate it with your `JEKYLL_GITHUB_TOKEN` or `OCTOKIT_ACCESS_TOKEN`. Be sure you do not commit your `.env` file!
github-metadata-2.15.0/docs/configuration.md 0000664 0000000 0000000 00000005446 14242001551 0020763 0 ustar 00root root 0000000 0000000 ## Configuration
In order for jekyll-github-metadata to know what metadata to fetch it must
be able to determine the repository NWO (name with owner, e.g. `jekyll/jekyll-github-metadata`) to ask GitHub about.
The easiest way to accomplish this is by setting an "origin" remote with a
github.com URL. If you ran `git clone` from GitHub, this is almost 100% the
case & no further action is needed. If you run `git remote -v` in your
repository, you should see your repo's URL. However, this only works if the
environment variable `JEKYLL_ENV` is either `development` or `test`.
The default value of `JEKYLL_ENV` is `development`.
If you don't have a git remote available, you have two other options:
1. Set the environment variable `PAGES_REPO_NWO` to your repository name
with owner, e.g. `"jekyll/github-metadata"`. This is useful if you don't
want to commit your repository to your git history.
2. Add your repository name with organization to your site's configuration
in the `repository` key.
```yaml
repository: username/repo-name
```
"NWO" stands for "name with owner." It is GitHub lingo for the username of
the owner of the repository plus a forward slash plus the name of the
repository, e.g. 'parkr/blog', where 'parkr' is the owner and 'blog' is the
repository name.
Your `site.github.*` fields should fill in like normal. If you run Jekyll
with the `--verbose` flag, you should be able to see all the API calls
made.
## Overrides
- `PAGES_REPO_NWO` – overrides `site.repository` as the repo name with owner to fetch (e.g. `jekyll/github-metadata`)
Some `site.github` values can be overridden by environment variables.
- `JEKYLL_BUILD_REVISION` – the `site.github.build_revision`, git SHA of the source site being built. (default: `git rev-parse HEAD`)
- `PAGES_ENV` – the `site.github.pages_env` (default: `development`)
- `PAGES_API_URL` – the `site.github.api_url` (default: `https://api.github.com`)
- `PAGES_HELP_URL` – the `site.github.help_url` (default: `https://help.github.com`)
- `PAGES_GITHUB_HOSTNAME` – the `site.github.hostname` (default: `github.com`)
- `PAGES_PAGES_HOSTNAME` – the `site.github.pages_hostname` (default: `github.io`)
- `NO_NETRC` – set if you don't want the fallback to `~/.netrc`
## Using with GitHub Enterprise
Working with `jekyll-github-metadata` and GitHub Enterprise? No sweat. You can configure which API endpoints this plugin will hit to fetch data.
- `SSL` – if "true", sets a number of endpoints to use `https://`, default: `"false"`
- `OCTOKIT_API_ENDPOINT` – the full hostname and protocol for the api, default: `https://api.github.com`
- `OCTOKIT_WEB_ENDPOINT` – the full hostname and protocol for the website, default: `https://github.com`
- `PAGES_PAGES_HOSTNAME` – the full hostname from where GitHub Pages sites are served, default: `github.io`.
github-metadata-2.15.0/docs/development.md 0000664 0000000 0000000 00000003205 14242001551 0020425 0 ustar 00root root 0000000 0000000 ## Development
Guide to local development of this plugin
### Installation
#### Requirements
- Ruby
- Bundler
#### Install system dependencies
- Install Ruby - see the [Downloads](https://www.ruby-lang.org/en/downloads/) page.
- Install Bundler - see the [Bundler](https://bundler.io/) homepage.
#### Clone
Clone the repo, or your fork.
```bash
$ git clone git@github.com:jekyll/github-metadata.git
$ cd github-metadata
```
#### Install project dependencies
Configure Bundler.
```bash
$ bundle config set --local path vendor/bundle
```
Install gems.
```bash
$ bundle install
```
Or, for a faster install.
```bash
$ script/bootstrap
```
### Usage
See the [script](/script/) directory.
#### Format
Check for code formatting issues - recommended before you commit.
```bash
$ script/fmt
```
Fix formatting issues.
```bash
$ script/fmt -a
```
#### Open interactive console
```bash
$ script/console
```
#### Test
Run all unit tests.
```bash
$ script/test
```
Run a target unit test file by specifying a path.
```bash
$ script/test spec/owner_spec.rb
```
See some recommended flags below.
Run tests in the order they are written (not a random order).
```bash
$ script/test --order defined
```
Run tests in the same random order as a previous run.
```bash
$ script/test --seed 12345
```
Run tests with verbose trace logs.
```bash
$ script/test --format documentation
```
#### Start dev server
Preview the plugin in Jekyll by running the repo's sample Jekyll site.
```bash
$ script/test-site
```
Then open in the browser at:
- http://127.0.0.1:4000
### Release
Run tests, formatting and create a release.
```bash
$ script/release
```
github-metadata-2.15.0/docs/edit-on-github-link.md 0000664 0000000 0000000 00000001423 14242001551 0021655 0 ustar 00root root 0000000 0000000 ## Edit on GitHub link
The plugin also makes a tag available that generates links to edit the current page on GitHub.
### To generate a link
```liquid
This site is open source. {% raw %}{% github_edit_link "Improve this page" %}{% endraw %}
```
Produces:
```html
This site is open source. Improve this page
```
### To generate a path
If you'd prefer to build your own link, simply don't pass link text
```liquid
This site is open source. Improve this page
```
Produces:
```html
This site is open source. Improve this page
```
github-metadata-2.15.0/docs/site.github.md 0000664 0000000 0000000 00000006324 14242001551 0020335 0 ustar 00root root 0000000 0000000 ## Using `site.github`
Common repository information, such as the project name and description, is available to Jekyll sites using `jekyll-github-metadata` including GitHub Pages sites.
#### Usage
Repository metadata is exposed to your Jekyll site's configuration in the `site.github` namespace.
Simply, reference any of the below keys as you would any other site configuration value present in your `_config.yml` file, prefacing the key with `site.github`.
For example, to list a project's name, you might write something like `The project is called {{ site.github.project_title }}` or to list an organization's open source repositories, you might use the following:
```liquid
{% for repository in site.github.public_repositories %}
* [{{ repository.name }}]({{ repository.html_url }})
{% endfor %}
```
#### Available repository metadata
The following sample information is exposed to Jekyll templates in the `site.github` namespace:
```text
{
"versions": {
"jekyll": ,
"kramdown": ,
"liquid": ,
"maruku": ,
"rdiscount": ,
"redcarpet": ,
"RedCloth": ,
"jemoji": ,
"jekyll-mentions": ,
"jekyll-redirect-from": ,
"jekyll-sitemap": ,
"github-pages": ,
"ruby": "
},
"hostname": "github.com",
"pages_hostname": "github.io",
"api_url": "https://api.github.com",
"help_url": "https://help.github.com",
"environment": "dotcom",
"pages_env": "dotcom",
"public_repositories": [ Repository Objects ],
"organization_members": [ User Objects ],
"build_revision": "cbd866ebf142088896cbe71422b949de7f864bce",
"project_title": "metadata-example",
"project_tagline": "A GitHub Pages site to showcase repository metadata",
"owner_name": "github",
"owner_url": "https://github.com/github",
"owner_gravatar_url": "https://github.com/github.png",
"repository_url": "https://github.com/github/metadata-example",
"repository_nwo": "github/metadata-example",
"repository_name": "metadata-example",
"zip_url": "https://github.com/github/metadata-example/zipball/gh-pages",
"tar_url": "https://github.com/github/metadata-example/tarball/gh-pages",
"clone_url": "https://github.com/github/metadata-example.git",
"releases_url": "https://github.com/github/metadata-example/releases",
"issues_url": "https://github.com/github/metadata-example/issues",
"wiki_url": "https://github.com/github/metadata-example/wiki",
"language": null,
"is_user_page": false,
"is_project_page": true,
"show_downloads": true,
"url": "http://username.github.io/metadata-example", // (or the CNAME)
"baseurl": "/metadata-example",
"contributors": [ User Objects ],
"releases": [ Release Objects ],
"latest_release": [ Release Object ],
"private": false,
"archived": false,
"disabled": false,
"license": {
"key": "mit",
"name": "MIT License",
"spdx_id": "MIT",
"url": "https://api.github.com/licenses/mit"
},
"source": {
"branch": "gh-pages",
"path": "/"
}
}
```
github-metadata-2.15.0/jekyll-github-metadata.gemspec 0000664 0000000 0000000 00000002043 14242001551 0022525 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
lib = File.expand_path("lib", __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "jekyll-github-metadata/version"
Gem::Specification.new do |spec|
spec.name = "jekyll-github-metadata"
spec.version = Jekyll::GitHubMetadata::VERSION
spec.authors = ["Parker Moore"]
spec.email = ["parkrmoore@gmail.com"]
spec.summary = "The site.github namespace"
spec.homepage = "https://github.com/jekyll/github-metadata"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").grep(%r!^(lib|bin)/!)
spec.require_paths = ["lib"]
spec.add_runtime_dependency "jekyll", ">= 3.4", "< 5.0"
spec.add_runtime_dependency "octokit", "~> 4.0", "!= 4.4.0"
spec.add_development_dependency "bundler"
spec.add_development_dependency "netrc"
spec.add_development_dependency "pry"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec", "~> 3.11.0"
spec.add_development_dependency "rubocop-jekyll", "~> 0.12.0"
end
github-metadata-2.15.0/lib/ 0000775 0000000 0000000 00000000000 14242001551 0015377 5 ustar 00root root 0000000 0000000 github-metadata-2.15.0/lib/jekyll-github-metadata.rb 0000664 0000000 0000000 00000004324 14242001551 0022257 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "jekyll"
require "octokit"
if Jekyll.env == "development"
begin
require "dotenv"
Dotenv.load
rescue LoadError
Jekyll.logger.debug "Dotenv not found. Skipping"
end
end
module Jekyll
module GitHubMetadata
autoload :Client, "jekyll-github-metadata/client"
autoload :EditLinkTag, "jekyll-github-metadata/edit-link-tag"
autoload :MetadataDrop, "jekyll-github-metadata/metadata_drop"
autoload :Owner, "jekyll-github-metadata/owner"
autoload :Pages, "jekyll-github-metadata/pages"
autoload :Repository, "jekyll-github-metadata/repository"
autoload :RepositoryFinder, "jekyll-github-metadata/repository_finder"
autoload :RepositoryCompat, "jekyll-github-metadata/repository_compat"
autoload :Sanitizer, "jekyll-github-metadata/sanitizer"
autoload :Value, "jekyll-github-metadata/value"
autoload :VERSION, "jekyll-github-metadata/version"
NoRepositoryError = RepositoryFinder::NoRepositoryError
require_relative "jekyll-github-metadata/site_github_munger" if Jekyll.const_defined? :Site
class << self
attr_reader :repository_finder
attr_writer :client, :logger
def site
repository_finder.site
end
def environment
Jekyll.env
end
def logger
@logger ||= Jekyll.logger
end
def log(severity, message)
if logger.method(severity).arity.abs >= 2
logger.public_send(severity, "GitHub Metadata:", message.to_s)
else
logger.public_send(severity, "GitHub Metadata: #{message}")
end
end
def client
@client ||= Client.new
end
def repository
@repository ||= GitHubMetadata::Repository.new(repository_finder.nwo).tap do |repo|
log :debug, "Generating for #{repo.nwo}"
end
end
def site=(new_site)
reset!
@repository_finder = GitHubMetadata::RepositoryFinder.new(new_site)
end
def reset!
@logger = @client = @repository = @nwo = @site = nil
end
end
end
end
Liquid::Template.register_tag("github_edit_link", Jekyll::GitHubMetadata::EditLinkTag)
github-metadata-2.15.0/lib/jekyll-github-metadata/ 0000775 0000000 0000000 00000000000 14242001551 0021727 5 ustar 00root root 0000000 0000000 github-metadata-2.15.0/lib/jekyll-github-metadata/client.rb 0000664 0000000 0000000 00000010571 14242001551 0023536 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "digest"
module Jekyll
module GitHubMetadata
class Client
InvalidMethodError = Class.new(NoMethodError)
BadCredentialsError = Class.new(StandardError)
# Whitelisted API calls.
API_CALLS = Set.new(%w(
repository
organization
user
repository?
pages
contributors
releases
latest_release
list_repos
organization_public_members
))
def initialize(options = nil)
@client = build_octokit_client(options)
end
def safe_require(gem_name)
require gem_name
true
rescue LoadError
false
end
def default_octokit_options
{
:api_endpoint => Jekyll::GitHubMetadata::Pages.api_url,
:web_endpoint => Jekyll::GitHubMetadata::Pages.github_url,
:auto_paginate => true,
}
end
def build_octokit_client(options = nil)
options ||= {}
options.merge!(pluck_auth_method) unless options.key?(:access_token)
Octokit::Client.new(default_octokit_options.merge(options))
end
def accepts_client_method?(method_name)
API_CALLS.include?(method_name.to_s) && @client.respond_to?(method_name)
end
def respond_to_missing?(method_name, include_private = false)
accepts_client_method?(method_name) || super
end
def method_missing(method_name, *args, &block)
method = method_name.to_s
if accepts_client_method?(method_name)
key = cache_key(method_name, args)
GitHubMetadata.log :debug, "Calling @client.#{method}(#{args.map(&:inspect).join(", ")})"
cache[key] ||= save_from_errors { @client.public_send(method_name, *args, &block) }
elsif @client.respond_to?(method_name)
raise InvalidMethodError, "#{method_name} is not whitelisted on #{inspect}"
else
super
end
end
# NOTE: Faraday's error classes has been promoted to under Faraday module from v1.0.0.
# This patch aims to prevent on locking specific version of Faraday.
FARADAY_FAILED_CONNECTION =
begin
Faraday::Error::ConnectionFailed
rescue NameError
Faraday::ConnectionFailed
end
def save_from_errors(default = false)
unless internet_connected?
GitHubMetadata.log :warn, "No internet connection. GitHub metadata may be missing or incorrect."
return default
end
yield @client
rescue Octokit::Unauthorized
raise BadCredentialsError, "The GitHub API credentials you provided aren't valid."
rescue FARADAY_FAILED_CONNECTION, Octokit::TooManyRequests => e
GitHubMetadata.log :warn, e.message
default
rescue Octokit::NotFound
default
end
def inspect
"#<#{self.class.name} @client=#{client_inspect} @internet_connected=#{internet_connected?}>"
end
def authenticated?
!@client.access_token.to_s.empty?
end
def internet_connected?
return @internet_connected if defined?(@internet_connected)
require "resolv"
begin
Resolv::DNS.open do |dns|
dns.timeouts = 2
dns.getaddress("api.github.com")
end
@internet_connected = true
rescue Resolv::ResolvError
@internet_connected = false
end
end
private
def client_inspect
if @client.nil?
"nil"
else
"#<#{@client.class.name} (#{"un" unless authenticated?}authenticated)>"
end
end
# rubocop:disable Metrics/CyclomaticComplexity
def pluck_auth_method
if ENV["JEKYLL_GITHUB_TOKEN"] || Octokit.access_token
{ :access_token => ENV["JEKYLL_GITHUB_TOKEN"] || Octokit.access_token }
elsif !ENV["NO_NETRC"] && File.exist?(File.join(ENV["HOME"], ".netrc")) && safe_require("netrc")
{ :netrc => true }
else
GitHubMetadata.log :warn, "No GitHub API authentication could be found." \
" Some fields may be missing or have incorrect data."
{}.freeze
end
end
# rubocop:enable Metrics/CyclomaticComplexity
def cache_key(method, *args)
Digest::SHA1.hexdigest(method.to_s + args.join(", "))
end
def cache
@cache ||= {}
end
end
end
end
github-metadata-2.15.0/lib/jekyll-github-metadata/edit-link-tag.rb 0000664 0000000 0000000 00000007257 14242001551 0024720 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module Jekyll
module GitHubMetadata
class EditLinkTag < Liquid::Tag
attr_reader :context
# Defines an instance method that delegates to a hash's key
#
# hash_method - a symbol representing the instance method to delegate to. The
# instance method should return a hash or respond to #[]
# key - the key to call within the hash
# method - (optional) the instance method the key should be aliased to.
# If not specified, defaults to the hash key
# default - (optional) value to return if value is nil (defaults to nil)
#
# Returns a symbol representing the instance method
def self.def_hash_delegator(hash_method, key, method, default = nil)
define_method(method) do
hash = send(hash_method)
if hash.respond_to? :[]
hash[key.to_s] || default
else
default
end
end
end
MISSING_DATA_MSG = "Cannot generate edit URLs due to missing site.github data"
LINK_TEXT_REGEX = %r!(?:\"(.*)\"|'(.*)')!.freeze
extend Forwardable
private def_hash_delegator :site, :github, :site_github, {}
private def_hash_delegator :site_github, :repository_url, :repository_url
private def_hash_delegator :site_github, :source, :source, {}
private def_hash_delegator :source, :branch, :branch
private def_hash_delegator :source, :path, :source_path
private def_hash_delegator :page, :path, :page_path
def render(context)
@context = context
if link_text
link
else
uri.to_s
end
end
private
def link_text
@link_text ||= begin
matches = @markup.match LINK_TEXT_REGEX
matches[1] || matches[2] if matches
end
end
def link
"#{link_text}"
end
def uri
if parts.any?(&:nil?)
Jekyll.logger.warn "JekyllEditLink: ", MISSING_DATA_MSG
""
else
Addressable::URI.join(*parts_normalized).normalize
end
end
def parts
memoize_conditionally { [repository_url, "edit/", branch, source_path, page_path] }
end
def parts_normalized
memoize_conditionally do
parts.map.with_index do |part, index|
part = remove_leading_slash(part.to_s)
part = ensure_trailing_slash(part) unless index == parts.length - 1
ensure_not_just_a_slash(part)
end
end
end
def page
memoize_conditionally { context.registers[:page] }
end
# Utility function for compatibility with Jekyll 4.0
def memoize_conditionally
if renderer_cached?
yield
else
dispatcher = "@#{caller_locations(1..1).first.label}".to_sym
if instance_variable_defined?(dispatcher)
instance_variable_get(dispatcher)
else
instance_variable_set(dispatcher, yield)
end
end
end
# Utility function to detect Jekyll 4.0
def renderer_cached?
@renderer_cached ||= context.registers[:site].liquid_renderer.respond_to?(:cache)
end
def site
@site ||= context.registers[:site].site_payload["site"]
end
def remove_leading_slash(part)
part.start_with?("/") ? part[1..-1] : part
end
def ensure_trailing_slash(part)
part.end_with?("/") ? part : "#{part}/"
end
def ensure_not_just_a_slash(part)
part == "/" ? "" : part
end
end
end
end
github-metadata-2.15.0/lib/jekyll-github-metadata/metadata_drop.rb 0000664 0000000 0000000 00000010235 14242001551 0025061 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "jekyll"
require "forwardable"
module Jekyll
module GitHubMetadata
class MetadataDrop < Jekyll::Drops::Drop
extend Forwardable
mutable true
# See https://github.com/jekyll/jekyll/pull/6338
alias_method :invoke_drop, :[]
def key?(key)
return false if key.nil?
return true if self.class.mutable? && mutations.key?(key)
respond_to?(key) || fallback_data.key?(key)
end
def to_s
require "json"
JSON.pretty_generate to_h
end
alias_method :to_str, :to_s
def content_methods
super - %w(to_s to_str)
end
def keys
super.sort
end
def_delegator Jekyll::GitHubMetadata::Pages, :env, :environment
def_delegator Jekyll::GitHubMetadata::Pages, :env, :pages_env
def_delegator Jekyll::GitHubMetadata::Pages, :github_hostname, :hostname
def_delegator Jekyll::GitHubMetadata::Pages, :pages_hostname, :pages_hostname
def_delegator Jekyll::GitHubMetadata::Pages, :api_url, :api_url
def_delegator Jekyll::GitHubMetadata::Pages, :help_url, :help_url
private def_delegator Jekyll::GitHubMetadata, :repository
def_delegator :repository, :owner_public_repositories, :public_repositories
def_delegator :repository, :organization_public_members, :organization_members
def_delegator :repository, :name, :project_title
def_delegator :repository, :tagline, :project_tagline
def_delegator :repository, :owner_metadata, :owner
def_delegator :repository, :owner, :owner_name
def_delegator :repository, :owner_display_name, :owner_display_name
def_delegator :repository, :owner_url, :owner_url
def_delegator :repository, :owner_gravatar_url, :owner_gravatar_url
def_delegator :repository, :repository_url, :repository_url
def_delegator :repository, :nwo, :repository_nwo
def_delegator :repository, :name, :repository_name
def_delegator :repository, :zip_url, :zip_url
def_delegator :repository, :tar_url, :tar_url
def_delegator :repository, :repo_clone_url, :clone_url
def_delegator :repository, :releases_url, :releases_url
def_delegator :repository, :issues_url, :issues_url
def_delegator :repository, :wiki_url, :wiki_url
def_delegator :repository, :language, :language
def_delegator :repository, :user_page?, :is_user_page
def_delegator :repository, :project_page?, :is_project_page
def_delegator :repository, :show_downloads?, :show_downloads
def_delegator :repository, :html_url, :url
def_delegator :repository, :baseurl, :baseurl
def_delegator :repository, :contributors, :contributors
def_delegator :repository, :releases, :releases
def_delegator :repository, :latest_release, :latest_release
def_delegator :repository, :private?, :private
def_delegator :repository, :archived?, :archived
def_delegator :repository, :disabled?, :disabled
def_delegator :repository, :license, :license
def_delegator :repository, :source, :source
def versions
return @versions if defined?(@versions)
begin
require "github-pages"
@versions = GitHubPages.versions
rescue LoadError
@versions = {}
end
end
def build_revision
@build_revision ||= begin
ENV["JEKYLL_BUILD_REVISION"] || `git rev-parse HEAD`.strip
end
end
private
# Nothing to see here.
def fallback_data
@fallback_data ||= {}
end
def mutations
@mutations ||= {}
end
end
end
end
github-metadata-2.15.0/lib/jekyll-github-metadata/owner.rb 0000664 0000000 0000000 00000005261 14242001551 0023412 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module Jekyll
module GitHubMetadata
class Owner
extend Forwardable
# Defines an instance method that delegates to a hash's key
#
# hash - a symbol representing the instance method to delegate to. The
# instance method should return a hash or respond to #[]
# key - the key to call within the hash
# method - (optional) the instance method the key should be aliased to.
# If not specified, defaults to the hash key
#
# Returns a symbol representing the instance method
def self.def_hash_delegators(hash, *methods)
content_methods.concat(methods)
methods.each do |method|
define_method(method) do
send(hash)[method.to_s]
end
end
end
def self.content_methods
@content_methods ||= []
end
# List of whitelisted keys.
def_hash_delegators :owner_info,
:avatar_url,
:bio,
:blog,
:collaborators,
:company,
:created_at,
:description,
:email,
:followers,
:following,
:has_organization_projects,
:has_repository_projects,
:hireable,
:html_url,
:id,
:is_verified,
:location,
:login,
:name,
:node_id,
:public_gists,
:public_gists,
:public_repos,
:public_repos,
:type,
:updated_at
attr_reader :owner_login
def initialize(owner_login)
@owner_login = owner_login
end
def to_h
@to_h ||= self.class.content_methods
.each_with_object({}) { |method, hash| hash[method.to_s] = public_send(method) }
end
alias_method :to_hash, :to_h
def_delegator :to_h, :to_json, :to_json
def_delegator :to_h, :to_liquid, :to_liquid
def_delegator :to_h, :to_s, :to_s
alias_method :to_str, :to_s
private
def owner_info
@owner_info ||= begin
Value.new(
"owner",
proc do |c|
(c.organization(owner_login) || c.user(owner_login) || {}).to_h
end
).render || {}
end
end
end
end
end
github-metadata-2.15.0/lib/jekyll-github-metadata/pages.rb 0000664 0000000 0000000 00000005641 14242001551 0023361 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module Jekyll
module GitHubMetadata
class Pages
class << self
DEFAULTS = {
"PAGES_ENV" => "development",
"PAGES_API_URL" => "https://api.github.com",
"PAGES_HELP_URL" => "https://help.github.com",
"PAGES_GITHUB_HOSTNAME" => "github.com",
"PAGES_PAGES_HOSTNAME" => "github.io",
"SSL" => "false",
"SUBDOMAIN_ISOLATION" => "false",
"PAGES_PREVIEW_HTML_URL" => nil,
"PAGE_BUILD_ID" => nil,
}.freeze
# Whether the GitHub instance supports HTTPS
# Note: this will be the same as how sites are served in Enterprise,
# but may be different from how sites are served on GitHub.com.
# See Repository#url_scheme
def ssl?
env_var("SSL") == "true" || test?
end
def scheme
ssl? ? "https" : "http"
end
def subdomain_isolation?
env_var("SUBDOMAIN_ISOLATION").eql? "true"
end
def test?
env == "test"
end
def dotcom?
env == "dotcom"
end
def enterprise?
env == "enterprise"
end
def development?
env == "development"
end
def custom_domains_enabled?
dotcom? || test?
end
def env
env_var "PAGES_ENV", ENV["JEKYLL_ENV"]
end
def repo_pages_html_url_preview?
env_var "PAGES_PREVIEW_HTML_URL"
end
def github_url
if dotcom? || github_hostname == "github.com"
"https://github.com"
else
"#{scheme}://#{github_hostname}"
end
end
def api_url
trim_last_slash env_var("PAGES_API_URL", ENV["API_URL"])
end
def help_url
trim_last_slash env_var("PAGES_HELP_URL", ENV["HELP_URL"])
end
def github_hostname
trim_last_slash env_var("PAGES_GITHUB_HOSTNAME", ENV["GITHUB_HOSTNAME"])
end
def pages_hostname
intermediate_default = ENV["PAGES_HOSTNAME"]
intermediate_default ||= "localhost:4000" if development?
trim_last_slash env_var("PAGES_PAGES_HOSTNAME", intermediate_default)
end
def page_build?
!env_var("PAGE_BUILD_ID").to_s.empty?
end
def configuration
(methods - Object.methods - [:configuration]).sort.each_with_object({}) do |meth, memo|
memo[meth.to_s] = public_send(meth)
end
end
private
def env_var(key, intermediate_default = nil)
!ENV[key].to_s.empty? ? ENV[key] : (intermediate_default || DEFAULTS[key])
end
def trim_last_slash(url)
if url[-1] == "/"
url[0..-2]
else
url
end
end
end
end
end
end
github-metadata-2.15.0/lib/jekyll-github-metadata/repository.rb 0000664 0000000 0000000 00000014322 14242001551 0024475 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module Jekyll
module GitHubMetadata
class Repository
attr_reader :nwo, :owner, :name
# Defines an instance method that delegates to a hash's key
#
# hash - a symbol representing the instance method to delegate to. The
# instance method should return a hash or respond to #[]
# key - the key to call within the hash
# method - (optional) the instance method the key should be aliased to.
# If not specified, defaults to the hash key
#
# Returns a symbol representing the instance method
def self.def_hash_delegator(hash, key, method)
define_method(method) do
public_send(hash)[key.to_s]
end
end
extend Forwardable
def_hash_delegator :repo_info, :license, :license
def_hash_delegator :repo_info, :language, :language
def_hash_delegator :repo_info, :description, :tagline
def_hash_delegator :repo_info, :has_downloads, :show_downloads?
def_hash_delegator :repo_info, :private, :private?
def_hash_delegator :repo_info, :archived, :archived?
def_hash_delegator :repo_info, :disabled, :disabled?
def_hash_delegator :latest_release, :url, :latest_release_url
def_hash_delegator :source, :branch, :git_ref
def_delegator :uri, :host, :domain
def_delegator :uri, :scheme, :url_scheme
def_delegator :uri, :path, :baseurl
def initialize(name_with_owner)
@nwo = name_with_owner
@owner = nwo.split("/").first
@name = nwo.split("/").last
end
def repo_compat
@repo_compat ||= Jekyll::GitHubMetadata::RepositoryCompat.new(self)
end
def repo_info
@repo_info ||= begin
options = { :accept => "application/vnd.github.drax-preview+json" }
(Value.new("repo_info", proc { |c| c.repository(nwo, options) }).render || {})
end
end
def repo_pages_info
@repo_pages_info ||= (Value.new("repo_pages_info", proc { |c| c.pages(nwo, repo_pages_info_opts) }).render || {})
end
def repo_pages_info_opts
if Pages.repo_pages_html_url_preview?
{ :accept => "application/vnd.github.mister-fantastic-preview+json" }
else
{}
end
end
def owner_display_name
owner_metadata.name
end
def owner_metadata
@owner_metadata ||= Jekyll::GitHubMetadata::Owner.new(owner)
end
def owner_url
"#{Pages.github_url}/#{owner}"
end
def owner_gravatar_url
"#{owner_url}.png"
end
def repo_clone_url
"#{repository_url}.git"
end
def repository_url
"#{owner_url}/#{name}"
end
def zip_url
"#{repository_url}/zipball/#{git_ref}"
end
def tar_url
"#{repository_url}/tarball/#{git_ref}"
end
def releases_url
"#{repository_url}/releases"
end
def issues_url
"#{repository_url}/issues" if repo_info["has_issues"]
end
def wiki_url
"#{repository_url}/wiki" if repo_info["has_wiki"]
end
def organization_repository?
memoize_value :@is_organization_repository, Value.new("organization_repository?", proc { |c| !!c.organization(owner) })
end
def owner_public_repositories
options = {
:type => "public",
:accept => "application/vnd.github.mercy-preview+json",
}
memoize_value :@owner_public_repositories, Value.new("owner_public_repositories", proc do |c|
c.list_repos(owner, options).map do |r|
r[:releases] = Value.new("owner_public_repositories_releases", proc { c.releases(r[:full_name]) })
r[:contributors] = Value.new("owner_public_repositories_contributors", proc { c.contributors(r[:full_name]) })
r
end
end)
end
def organization_public_members
memoize_value :@organization_public_members, Value.new("organization_public_members", proc do |c|
c.organization_public_members(owner) if organization_repository?
end)
end
def contributors
memoize_value :@contributors, Value.new("contributors", proc { |c| c.contributors(nwo) })
end
def releases
memoize_value :@releases, Value.new("releases", proc { |c| c.releases(nwo) })
end
def latest_release
memoize_value :@latest_release, Value.new("latest_release", proc { |c| c.latest_release(nwo) })
end
def source
repo_pages_info["source"] || repo_compat.source
end
def project_page?
!user_page?
end
def github_repo?
!Pages.enterprise? && owner.eql?("github")
end
def primary?
if Pages.enterprise?
name.downcase == "#{owner.to_s.downcase}.#{Pages.github_hostname}"
else
user_page_domains.include? name.downcase
end
end
alias_method :user_page?, :primary?
def user_page_domains
domains = [default_user_domain]
domains.push "#{owner}.github.com".downcase unless Pages.enterprise?
domains
end
def default_user_domain
if github_repo?
"#{owner}.#{Pages.github_hostname}".downcase
elsif Pages.enterprise?
Pages.pages_hostname.downcase
else
"#{owner}.#{Pages.pages_hostname}".downcase
end
end
def cname
return nil unless Pages.custom_domains_enabled?
repo_pages_info["cname"]
end
def html_url
@html_url ||= (repo_pages_info["html_url"] || repo_compat.pages_url).chomp("/")
end
def uri
@uri ||= URI(html_url)
end
def url_without_path
uri.dup.tap { |u| u.path = "" }.to_s
end
def stargazers_count
repo_pages_info["stargazers_count"] || 0
end
def forks_count
repo_pages_info["forks_count"] || 0
end
private
def memoize_value(var_name, value)
return instance_variable_get(var_name) if instance_variable_defined?(var_name)
instance_variable_set(var_name, value.render)
end
end
end
end
github-metadata-2.15.0/lib/jekyll-github-metadata/repository_compat.rb 0000664 0000000 0000000 00000004203 14242001551 0026035 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module Jekyll
module GitHubMetadata
class RepositoryCompat
attr_reader :repo
def initialize(repo)
@repo = repo
end
# In enterprise, the site's scheme will be the same as the instance's
# In dotcom, this will be `https` for GitHub-owned sites that end with
# `.github.com` and will be `http` for all other sites.
# Note: This is not the same as *instance*'s scheme, which may differ
def url_scheme
if Pages.enterprise?
Pages.scheme
elsif repo.owner == "github" && domain.end_with?(".github.com")
"https"
else
"http"
end
end
def user_domain
domain = repo.default_user_domain
repo.user_page_domains.each do |user_repo|
candidate_nwo = "#{repo.owner}/#{user_repo}"
next unless Jekyll::GitHubMetadata.client.repository?(candidate_nwo)
domain = Jekyll::GitHubMetadata::Repository.new(candidate_nwo).repo_compat.domain
end
domain
end
def pages_url
return enterprise_url unless Pages.custom_domains_enabled?
if repo.cname || repo.primary?
"#{url_scheme}://#{domain}"
else
URI.join("#{url_scheme}://#{domain}", repo.name).to_s
end
end
alias_method :html_url, :pages_url
def domain
@domain ||=
if !Pages.custom_domains_enabled?
Pages.github_hostname
elsif repo.cname # explicit CNAME
repo.cname
elsif repo.primary? # user/org repo
repo.default_user_domain
else # project repo
user_domain
end
end
def source
{
"branch" => (repo.user_page? ? "master" : "gh-pages"),
"path" => "/",
}
end
private
def enterprise_url
path = repo.user_page? ? repo.owner : repo.nwo
if Pages.subdomain_isolation?
URI.join("#{Pages.scheme}://#{Pages.pages_hostname}/", path).to_s
else
URI.join("#{Pages.github_url}/pages/", path).to_s
end
end
end
end
end
github-metadata-2.15.0/lib/jekyll-github-metadata/repository_finder.rb 0000664 0000000 0000000 00000004343 14242001551 0026026 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module Jekyll
module GitHubMetadata
class RepositoryFinder
NoRepositoryError = Class.new(Jekyll::Errors::FatalException)
attr_reader :site
def initialize(site)
@site = site
end
# Public: fetches the repository name with owner to fetch metadata for.
# In order of precedence, this method uses:
# 1. the environment variable $PAGES_REPO_NWO
# 2. 'repository' variable in the site config
# 3. the 'origin' git remote's URL
#
# site - the Jekyll::Site being processed
#
# Return the name with owner (e.g. 'parkr/my-repo') or raises an
# error if one cannot be found.
def nwo
@nwo ||= begin
nwo_from_env || \
nwo_from_config || \
nwo_from_git_origin_remote || \
proc do
raise NoRepositoryError, "No repo name found. " \
"Specify using PAGES_REPO_NWO environment variables, " \
"'repository' in your configuration, or set up an 'origin' " \
"git remote pointing to your github.com repository."
end.call
end
end
private
def nwo_from_env
ENV["PAGES_REPO_NWO"]
end
def nwo_from_config
repo = site.config["repository"]
repo if repo&.is_a?(String) && repo&.include?("/")
end
def git_remotes
_process, output = Jekyll::Utils::Exec.run("git", "remote", "--verbose")
output.to_s.strip.split("\n")
rescue Errno::ENOENT => e
Jekyll.logger.warn "Not Installed:", e.message
[]
end
def git_remote_url
git_remotes.grep(%r!\Aorigin\t!).map do |remote|
remote.sub(%r!\Aorigin\t(.*) \([a-z]+\)!, "\\1")
end.uniq.first || ""
end
def nwo_from_git_origin_remote
return unless Jekyll.env == "development" || Jekyll.env == "test"
matches = git_remote_url.chomp(".git").match github_remote_regex
matches[2..3].join("/") if matches
end
def github_remote_regex
github_host_regex = Regexp.escape(Jekyll::GitHubMetadata::Pages.github_hostname)
%r!#{github_host_regex}(:|/)([\w-]+)/([\w\.-]+)!
end
end
end
end
github-metadata-2.15.0/lib/jekyll-github-metadata/sanitizer.rb 0000664 0000000 0000000 00000003520 14242001551 0024264 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module Jekyll
module GitHubMetadata
module Sanitizer
extend self
# Sanitize an object.
# When the resource is either `false`, `true`, `nil` or a number,
# it returns the resource as-is. When the resource is an array,
# it maps over the entire array, sanitizing each of its values.
# When the resource responds to the #to_hash method, it returns
# the value of #sanitize_resource (see below). If none of the
# aforementioned conditions are met, the return value of #to_s
# is used.
#
# resource - an Object
#
# Returns the sanitized resource.
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/MethodLength
def sanitize(resource)
case resource
when Array
resource.map { |item| sanitize(item) }
when Numeric, Time
resource
when FalseClass
false
when TrueClass
true
when NilClass
nil
when String
resource
when Value
resource.render
else
if resource.respond_to?(:to_hash)
sanitize_resource(resource)
else
resource.to_s
end
end
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/MethodLength
# Sanitize the Sawyer Resource or Hash
# Note: the object must respond to :to_hash for this to work.
# Consider using #sanitize instead of this method directly.
#
# resource - an Object which responds to :to_hash
#
# Returns the sanitized sawyer resource or hash as a hash.
def sanitize_resource(resource)
resource.to_hash.each_with_object({}) do |(k, v), result|
result[k.to_s] = sanitize(v)
result
end
end
end
end
end
github-metadata-2.15.0/lib/jekyll-github-metadata/site_github_munger.rb 0000664 0000000 0000000 00000005476 14242001551 0026153 0 ustar 00root root 0000000 0000000 require "jekyll"
require "uri"
module Jekyll
module GitHubMetadata
class SiteGitHubMunger
extend Forwardable
class << self
attr_accessor :global_munger
end
def_delegators Jekyll::GitHubMetadata, :site, :repository
private :repository
def initialize(site)
Jekyll::GitHubMetadata.site = site
end
def munge!
Jekyll::GitHubMetadata.log :debug, "Initializing..."
add_title_and_description_fallbacks!
add_url_and_baseurl_fallbacks! if should_add_url_fallbacks?
end
def inject_metadata!(payload)
payload.site["github"] = github_namespace
end
private
def github_namespace
case site.config["github"]
when nil
drop
when Hash
Jekyll::Utils.deep_merge_hashes(drop, site.config["github"])
else
site.config["github"]
end
end
def drop
@drop ||= MetadataDrop.new(GitHubMetadata.site)
end
# Set `site.url` and `site.baseurl` if unset.
def add_url_and_baseurl_fallbacks!
site.config["url"] ||= Value.new("url", proc { |_c, r| r.url_without_path })
return unless should_set_baseurl?
site.config["baseurl"] = Value.new("baseurl", proc { |_c, r| r.baseurl })
end
def add_title_and_description_fallbacks!
if should_warn_about_site_name?
msg = "site.name is set in _config.yml, but many plugins and themes expect "
msg << "site.title to be used instead. To avoid potential inconsistency, "
msg << "Jekyll GitHub Metadata will not set site.title to the repository's name."
Jekyll::GitHubMetadata.log :warn, msg
else
site.config["title"] ||= Value.new("title", proc { |_context, repository|
if repository.project_page?
repository.name
else
repository.owner_display_name || repository.owner
end
})
end
site.config["description"] ||= Value.new("description", proc { |_c, r| r.tagline })
end
# Set the baseurl only if it is `nil` or `/`
# Baseurls should never be "/". See http://bit.ly/2s1Srid
def should_set_baseurl?
site.config["baseurl"].nil? || site.config["baseurl"] == "/"
end
def should_add_url_fallbacks?
Jekyll.env == "production" || Pages.page_build?
end
def should_warn_about_site_name?
site.config["name"] && !site.config["title"]
end
end
Jekyll::Hooks.register :site, :after_init do |site|
SiteGitHubMunger.global_munger = SiteGitHubMunger.new(site)
SiteGitHubMunger.global_munger.munge!
end
Jekyll::Hooks.register :site, :pre_render do |_site, payload|
SiteGitHubMunger.global_munger.inject_metadata!(payload)
end
end
end
github-metadata-2.15.0/lib/jekyll-github-metadata/value.rb 0000664 0000000 0000000 00000003003 14242001551 0023364 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "json"
module Jekyll
module GitHubMetadata
class Value
extend Forwardable
def_delegators :render, :+, :to_s, :to_json, :eql?, :hash
attr_reader :key, :value
def initialize(*args)
case args.size
when 1
@key = "{anonymous}"
@value = args.first
when 2
@key = args.first.to_s
@value = args.last
else
raise ArgumentError, "#{args.size} args given but expected 1 or 2"
end
end
def render
return @rendered if defined? @rendered
@rendered = @value = Sanitizer.sanitize(call_or_value)
rescue RuntimeError, NameError => e
Jekyll::GitHubMetadata.log :error, "Error processing value '#{key}':"
raise e
end
def to_liquid
case render
when nil, true, false, Hash, String, Numeric, Array
value
else
to_json
end
end
private
# Calls the value Proc with the appropriate number of arguments
# or returns the raw value if it's a literal
def call_or_value
return value unless value.respond_to?(:call)
case value.arity
when 0
value.call
when 1
value.call(GitHubMetadata.client)
when 2
value.call(GitHubMetadata.client, GitHubMetadata.repository)
else
raise ArgumentError, "Whoa, arity of 0, 1, or 2 please in your procs."
end
end
end
end
end
github-metadata-2.15.0/lib/jekyll-github-metadata/version.rb 0000664 0000000 0000000 00000000146 14242001551 0023742 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module Jekyll
module GitHubMetadata
VERSION = "2.15.0"
end
end
github-metadata-2.15.0/script/ 0000775 0000000 0000000 00000000000 14242001551 0016135 5 ustar 00root root 0000000 0000000 github-metadata-2.15.0/script/bootstrap 0000775 0000000 0000000 00000000047 14242001551 0020101 0 ustar 00root root 0000000 0000000 #!/bin/bash
bundle install --jobs=8 $@
github-metadata-2.15.0/script/cibuild 0000775 0000000 0000000 00000000160 14242001551 0017473 0 ustar 00root root 0000000 0000000 #!/bin/bash
set -e
export PAGES_ENV=test
export JEKYLL_ENV=test
script/test
script/fmt
bundle exec rake build
github-metadata-2.15.0/script/console 0000775 0000000 0000000 00000000133 14242001551 0017522 0 ustar 00root root 0000000 0000000 #!/bin/sh
PAGES_ENV=dotcom PAGES_PREVIEW_HTML_URL=true bundle exec ruby script/console.rb
github-metadata-2.15.0/script/console.rb 0000664 0000000 0000000 00000000634 14242001551 0020127 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "octokit"
require "pry"
stack = Faraday::RackBuilder.new do |builder|
builder.use Octokit::Middleware::FollowRedirects
builder.use Octokit::Response::RaiseError
builder.use Octokit::Response::FeedParser
builder.response :logger
builder.adapter Faraday.default_adapter
end
Octokit.middleware = stack
require_relative "../lib/jekyll-github-metadata"
binding.pry
github-metadata-2.15.0/script/fmt 0000775 0000000 0000000 00000000343 14242001551 0016651 0 ustar 00root root 0000000 0000000 #!/bin/bash
set -e
echo "Rubocop $(bundle exec rubocop --version)"
bundle exec rubocop -S -D -E $@
success=$?
if ((success != 0)); then
echo -e "\nTry running \`script/fmt -a\` to automatically fix errors"
fi
exit $success
github-metadata-2.15.0/script/release 0000664 0000000 0000000 00000000077 14242001551 0017504 0 ustar 00root root 0000000 0000000 #! /bin/bash
script/test
script/fmt
bundle exec rake release
github-metadata-2.15.0/script/spec 0000777 0000000 0000000 00000000000 14242001551 0017707 2test ustar 00root root 0000000 0000000 github-metadata-2.15.0/script/test 0000775 0000000 0000000 00000000142 14242001551 0017037 0 ustar 00root root 0000000 0000000 #!/bin/bash
echo Testing with $(bundle exec jekyll --version)
PAGES_ENV=test bundle exec rspec $@
github-metadata-2.15.0/script/test-site 0000775 0000000 0000000 00000000072 14242001551 0020003 0 ustar 00root root 0000000 0000000 #!/bin/bash
bundle exec jekyll serve -s spec/test-site $@
github-metadata-2.15.0/script/webmock-repopulate 0000775 0000000 0000000 00000001620 14242001551 0021667 0 ustar 00root root 0000000 0000000 #!/bin/bash
set -e
curl_me() {
(set -x; curl \
-H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.${3:-v3}+json" \
-H "Accept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3" \
-H "Content-Type: application/json" \
-H "User-Agent: Octokit Ruby Gem 4.2.0" \
https://api.github.com${1} | gunzip > \
spec/webmock/api_get_${2}.json)
}
curl_me "/repos/jekyll/github-metadata?per_page=100" "repo"
curl_me "/repos/jekyll/github-metadata/contributors?per_page=100" "repo_contributors"
curl_me "/repos/jekyll/github-metadata/releases?per_page=100" "repo_releases"
curl_me "/orgs/jekyll" "org"
curl_me "/orgs/jekyll/public_members" "org_members"
curl_me "/users/jekyll/repos?per_page=100&type=public" "owner_repos" "mercy-preview"
curl_me "/repos/jekyll/github-metadata/pages" "repo_pages"
curl_me "/repos/jekyll/github-metadata/releases/latest" "latest_release"
github-metadata-2.15.0/spec/ 0000775 0000000 0000000 00000000000 14242001551 0015563 5 ustar 00root root 0000000 0000000 github-metadata-2.15.0/spec/client_spec.rb 0000664 0000000 0000000 00000003005 14242001551 0020376 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "spec_helper"
RSpec.describe(Jekyll::GitHubMetadata::Client) do
let(:token) { "abc1234" }
subject { described_class.new(:access_token => token) }
it "whitelists certain api calls" do
described_class::API_CALLS.each do |method_name|
expect(subject).to respond_to(method_name.to_sym)
end
end
it "raises an error if an Octokit::Client method is called that's not whitelisted" do
expect do
subject.combined_status("jekyll/github-metadata", "refs/master")
end.to raise_error(described_class::InvalidMethodError, "combined_status is not whitelisted on # @internet_connected=true>")
end
it "can check if it's authenticated" do
expect(subject.authenticated?).to be(true)
expect(described_class.new(:access_token => nil).authenticated?).to be(false)
expect(described_class.new(:access_token => "").authenticated?).to be(false)
end
it "raises an error for any api call with bad credentials" do
stub_request(:get, url("/repos/jekyll/github-metadata/contributors?per_page=100"))
.with(:headers => request_headers.merge(
"Authorization" => "token #{token}"
))
.to_return(
:status => 401,
:headers => WebMockHelper::RESPONSE_HEADERS,
:body => webmock_data("bad_credentials")
)
expect do
subject.contributors("jekyll/github-metadata")
end.to raise_error(described_class::BadCredentialsError)
end
end
github-metadata-2.15.0/spec/edit_link_tag_spec.rb 0000664 0000000 0000000 00000012746 14242001551 0021731 0 ustar 00root root 0000000 0000000 RSpec.describe Jekyll::GitHubMetadata::EditLinkTag do
let(:repository_url) { "https://github.com/jekyll/github-metadata" }
let(:branch) { "gh-pages" }
let(:path) { "/" }
let(:source) { { "branch" => branch, "path" => path } }
let(:github) { { "repository_url" => repository_url, "source" => source } }
let(:config) { { "github" => github, "plugins" => ["jekyll-github-metadata"] } }
let(:page) { make_page }
let(:site) { make_site(config) }
let(:render_context) { make_context(:page => page, :site => site) }
let(:tag_name) { "github_edit_link" }
let(:markup) { "" }
let(:tokenizer) { Liquid::Tokenizer.new("") }
let(:parse_context) { Liquid::ParseContext.new }
let(:uri) { subject.send(:uri).to_s }
let(:rendered) { subject.render(render_context) }
let(:liquid_output) do
Liquid::Template.parse("{% #{tag_name} #{markup} %}").render!(render_context, {})
end
before { Jekyll.logger.log_level = :error }
before { stub_all_api_requests }
# Allow the stubs above to override any Munger behavior
before { site.config["github"] = github }
subject do
tag = described_class.parse(tag_name, markup, tokenizer, parse_context)
tag.instance_variable_set("@context", render_context)
tag
end
it "knows the page" do
expect(subject.send(:page)).to be_a(Jekyll::Page)
end
it "knows the site" do
expect(subject.send(:site)).to be_a(Jekyll::Drops::SiteDrop)
end
it "knows there's no link text" do
expect(subject.send(:link_text)).to be_nil
end
context "building the URL" do
it "builds the URL" do
expect(uri).to eql("#{repository_url}/edit/#{branch}/page.md")
end
context "a docs/ site" do
let(:path) { "docs/" }
it "builds the URL" do
expect(uri).to eql("#{repository_url}/edit/#{branch}/docs/page.md")
end
end
context "a gh-pages site" do
let(:branch) { "gh-pages" }
it "builds the URL" do
expect(uri).to eql("#{repository_url}/edit/gh-pages/page.md")
end
end
context "an arbitrary branch" do
let(:branch) { "foo" }
it "builds the URL" do
expect(uri).to eql("#{repository_url}/edit/foo/page.md")
end
end
end
context "with no site.github" do
let(:github) {}
it "returns an empty string" do
expect(uri).to eql("")
end
end
context "with site.github as a string" do
let(:github) { "@benbalter" }
it "returns an empty string" do
expect(uri).to eql("")
end
end
context "with repository_url as a hash" do
let(:repository_url) { { "foo" => "bar" } }
it "doesn't blow up" do
expect { uri }.to_not raise_error
end
end
context "normalization" do
it "ensures a string is not just a slash" do
expect(subject.send(:ensure_not_just_a_slash, "/")).to eql("")
end
it "adds a trailing slash" do
expect(subject.send(:ensure_trailing_slash, "foo")).to eql("foo/")
end
it "doesn't double add a trailing slash" do
expect(subject.send(:ensure_trailing_slash, "foo/")).to eql("foo/")
end
it "strips a leading slash" do
expect(subject.send(:remove_leading_slash, "/foo/")).to eql("foo/")
end
end
context "parts" do
it "builds the parts" do
expected = [github["repository_url"], "edit/", branch.to_s, "/", "page.md"]
expect(subject.send(:parts)).to eql(expected)
end
it "normalizes parts" do
expected = [github["repository_url"] + "/", "edit/", "#{branch}/", "", "page.md"]
expect(subject.send(:parts_normalized)).to eql(expected)
end
end
context "when passed text with single quotes" do
let(:markup) { " 'Improve this page' " }
it "pulls the link text" do
expect(subject.send(:link_text)).to eql("Improve this page")
end
end
context "when passed text with double quotes" do
let(:markup) { ' "Improve this page" ' }
it "pulls the link text" do
expect(subject.send(:link_text)).to eql("Improve this page")
end
end
context "rendering" do
it "returns a URL" do
expect(rendered).to eql("#{repository_url}/edit/#{branch}/page.md")
end
context "is conditionally context-aware" do
it "returns correct URL" do
# create a static instance. `subject` creates a different instance on each call.
tag = described_class.parse(tag_name, markup, tokenizer, parse_context)
expect(tag.render(render_context)).to eql("#{repository_url}/edit/#{branch}/page.md")
filename = site.liquid_renderer.respond_to?(:cache) ? "dummy_page.md" : "page.md"
new_context = make_context(
:page => make_page("path" => "dummy_page.md"),
:site => site
)
expect(tag.render(new_context)).to eql("#{repository_url}/edit/#{branch}/#{filename}")
end
end
context "when passed markup" do
let(:markup) { '"Improve this page"' }
it "returns a link" do
expected = ""
expected << "Improve this page"
expect(rendered).to match(expected)
end
end
end
context "integration" do
context "when empty" do
it "renders the URL" do
expect(liquid_output).to match("#{repository_url}/edit/#{branch}/page.md")
end
end
context "when passed a string" do
let(:markup) { '"Improve this page"' }
it "renders the link" do
expected = "Improve this page"
expect(liquid_output).to match(expected)
end
end
end
end
github-metadata-2.15.0/spec/github_metadata_spec.rb 0000664 0000000 0000000 00000000641 14242001551 0022245 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "spec_helper"
RSpec.describe(Jekyll::GitHubMetadata) do
let(:key_value_pair) { %w(some_key some_value) }
it "has a global GitHub API client" do
expect(described_class.client).to be_a(Jekyll::GitHubMetadata::Client)
end
it "does auto_paginate" do
expect(
described_class.client.instance_variable_get(:"@client").auto_paginate
).to be(true)
end
end
github-metadata-2.15.0/spec/integration_spec.rb 0000664 0000000 0000000 00000003635 14242001551 0021454 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "spec_helper"
require "jekyll"
require "jekyll-github-metadata/site_github_munger"
RSpec.describe("integration into a jekyll site") do
extend IntegrationHelper
let!(:stubs) { stub_all_api_requests }
before(:each) do
# Run Jekyll
ENV.delete("JEKYLL_ENV")
ENV["JEKYLL_ENV"] = "production"
ENV["PAGES_ENV"] = "dotcom"
Jekyll.logger.log_level = :error
Jekyll::Commands::Build.process(config_defaults)
end
after(:each) do
ENV.delete("PAGES_ENV")
ENV["JEKYLL_ENV"] = "test"
end
subject { SafeYAML.load(in_dest_dir("rendered.txt").read) }
expected_values.each do |key, value|
it "contains the correct #{key}" do
expect(subject).to have_key(key)
if value.is_a? Regexp
expect(subject[key].to_s).to match value
else
expect(subject[key]).to eql value
end
end
end
it "contains the correct public_repositories.releases" do
expect(subject).to have_key("public_repositories")
expect(subject["public_repositories"].first).to have_key("releases")
expect(subject["public_repositories"].first["releases"].size).to eql(3)
expect(subject["public_repositories"].first["releases"].first["name"]).to eql("v1.1.0")
expect(subject["public_repositories"].first["releases"].first["target_commitish"]).to eql("master")
end
it "contains the correct public_repositories.contributors" do
expect(subject).to have_key("public_repositories")
expect(subject["public_repositories"].first).to have_key("contributors")
expect(subject["public_repositories"].first["contributors"].size).to eql(1)
expect(subject["public_repositories"].first["contributors"].first["login"]).to eql("parkr")
end
it "calls all the stubs" do
stubs.each do |stub|
expect(stub).to have_been_requested
end
end
it "presents the owner data as a Hash" do
expect(subject["owner"]).to be_a(Hash)
end
end
github-metadata-2.15.0/spec/metadata_drop_spec.rb 0000664 0000000 0000000 00000005540 14242001551 0021732 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "spec_helper"
RSpec.describe(Jekyll::GitHubMetadata::MetadataDrop) do
extend IntegrationHelper
let(:overrides) { { "repository" => "jekyll/another-repo" } }
let(:config) { Jekyll::Configuration.from(overrides) }
let(:site) { Jekyll::Site.new config }
subject { described_class.new(site) }
before { stub_all_api_requests }
context "in Liquid" do
before(:each) do
site.config.delete("repository")
site.config["github"] = subject
end
it "renders as a pretty JSON object in Liquid" do
require "json"
payload = site.site_payload
expect(payload["site"]["github"]).to be_instance_of(described_class)
expect(
Liquid::Template.parse("{{ site.github }}").render!(
payload, :registers => { :site => site }
)
).to eql(JSON.pretty_generate(subject.to_h))
end
end
context "payload" do
let!(:payload) { subject.to_h }
expected_values.each do |key, value|
it "contains the #{key} key" do
expect(payload).to have_key(key)
end
it "contains the correct value for #{key}" do
if value.is_a? Regexp
expect(payload[key].to_s).to match value
else
expect(payload[key]).to eql value
end
end
end
# Test to ensure we're testing all the values in the drop payload
# If this test fails, you likely need to update a value in spec_helper.rb
it "validates all values" do
expect(payload.keys).to match_array(expected_values.keys)
end
end
context "returning values" do
context "native methods" do
it "returns a value via #[]" do
expect(subject["url"]).to eql("http://jekyll.github.io/github-metadata")
end
it "returns a value via #invoke_drop" do
expect(subject.invoke_drop("url")).to eql("http://jekyll.github.io/github-metadata")
end
it "responds to #key?" do
expect(subject.key?("url")).to be_truthy
end
end
context "with mutated values" do
before { subject["url"] = "foo" }
it "returns the mutated value via #[]" do
expect(subject["url"]).to eql("foo")
end
it "returns the mutated via #invoke_drop" do
expect(subject.invoke_drop("url")).to eql("foo")
end
it "responds to #key?" do
expect(subject.key?("url")).to be_truthy
end
end
context "with fallback data" do
let(:fallback_data) { { "foo" => "bar" } }
before { subject.instance_variable_set("@fallback_data", fallback_data) }
it "returns the mutated value via #[]" do
expect(subject["foo"]).to eql("bar")
end
it "returns the mutated via #invoke_drop" do
expect(subject.invoke_drop("foo")).to eql("bar")
end
it "responds to #key?" do
expect(subject.key?("foo")).to be_truthy
end
end
end
end
github-metadata-2.15.0/spec/owner_spec.rb 0000664 0000000 0000000 00000006037 14242001551 0020262 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "spec_helper"
RSpec.describe(Jekyll::GitHubMetadata::Owner) do
subject { described_class.new(login) }
before(:each) do
ENV["JEKYLL_GITHUB_TOKEN"] = "allthespecs"
end
context "is an ORG" do
let(:login) { "jekyll" }
let!(:stub) do
stub_api("/orgs/#{login}", "org")
end
EXPECTED_ATTRIBUTES_ORG = {
:login => "jekyll",
:id => 3_083_652,
:node_id => "MDEyOk9yZ2FuaXphdGlvbjMwODM2NTI=",
:avatar_url => "https://avatars0.githubusercontent.com/u/3083652?v=4",
:description => "Jekyll is a blog-aware, static site generator in Ruby.",
:name => "Jekyll",
:company => nil,
:blog => "https://jekyllrb.com",
:location => nil,
:email => "",
:is_verified => true,
:has_organization_projects => true,
:has_repository_projects => true,
:public_repos => 50,
:public_gists => 0,
:followers => 0,
:following => 0,
:html_url => "https://github.com/jekyll",
:created_at => Time.parse("2012-12-19 19:37:35 UTC"),
:updated_at => Time.parse("2019-01-27 15:27:32 UTC"),
:type => "Organization",
}.freeze
EXPECTED_ATTRIBUTES_ORG.each do |attribute, expected_value|
it "fetches #{attribute}" do
expect(subject.public_send(attribute)).to eq(expected_value)
end
end
it "blocks denied attributes" do
expect(subject).not_to respond_to(:repos_url)
end
end
context "is a USER" do
let(:login) { "jekyllbot" }
let!(:stub) do
stub_api_404("/orgs/#{login}")
stub_api("/users/#{login}", "user")
end
EXPECTED_ATTRIBUTES_USER = {
:login => "jekyllbot",
:id => 6_166_343,
:node_id => "MDQ6VXNlcjYxNjYzNDM=",
:avatar_url => "https://avatars0.githubusercontent.com/u/6166343?v=4",
:type => "User",
:name => "jekyllbot",
:company => nil,
:blog => "https://github.com/parkr/auto-reply",
:location => nil,
:email => nil,
:hireable => nil,
:bio => "I help make working with @jekyll fun and easy.",
:public_repos => 2,
:public_gists => 0,
:followers => 68,
:following => 0,
:created_at => Time.parse("2013-12-12 02:49:00 UTC"),
:updated_at => Time.parse("2017-12-05 21:23:41 UTC"),
}.freeze
EXPECTED_ATTRIBUTES_USER.each do |attribute, expected_value|
it "fetches #{attribute}" do
expect(subject.public_send(attribute)).to eq(expected_value)
end
end
it "blocks denied attributes" do
expect(subject).not_to respond_to(:site_admin)
expect(subject).not_to respond_to(:repos_url)
end
end
end
github-metadata-2.15.0/spec/pages_spec.rb 0000664 0000000 0000000 00000011373 14242001551 0020226 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "spec_helper"
RSpec.describe(Jekyll::GitHubMetadata::Pages) do
context "enterprise" do
before(:each) { ENV["PAGES_ENV"] = "enterprise" }
after(:each) { ENV["PAGES_ENV"] = "test" }
let(:ghe_domain) { "ghe.io" }
it "disables custom domains" do
expect(described_class.custom_domains_enabled?).to be false
end
it "looks for the domain specified" do
with_env("GITHUB_HOSTNAME", ghe_domain) do
expect(described_class.github_url).to eql("http://#{ghe_domain}")
expect(described_class.github_hostname).to eql ghe_domain
end
end
it "handles a separate pages hostname" do
pages_hostname = "pages.#{ghe_domain}"
with_env("PAGES_HOSTNAME", pages_hostname) do
expect(described_class.pages_hostname).to eql pages_hostname
end
end
end
context ".configuration" do
it "returns the entire configuration" do
expect(described_class.configuration).to eql(
"api_url" => "https://api.github.com",
"custom_domains_enabled?" => true,
"development?" => false,
"dotcom?" => false,
"enterprise?" => false,
"env" => "test",
"github_hostname" => "github.com",
"github_url" => "https://github.com",
"help_url" => "https://help.github.com",
"page_build?" => false,
"pages_hostname" => "github.io",
"repo_pages_html_url_preview?" => nil,
"scheme" => "https",
"ssl?" => true,
"subdomain_isolation?" => false,
"test?" => true
)
end
end
context ".env" do
it "picks up on PAGES_ENV" do
with_env("PAGES_ENV", "halp") do
expect(described_class.env).to eql("halp")
end
end
it "picks up on JEKYLL_ENV" do
with_env "PAGES_ENV", "" do
with_env "JEKYLL_ENV", "halp" do
expect(described_class.env).to eql("halp")
end
end
end
it "has convenience methods for various envs" do
with_env("PAGES_ENV", "test") do
expect(described_class.test?).to be true
expect(described_class.dotcom?).to be false
expect(described_class.enterprise?).to be false
expect(described_class.development?).to be false
end
with_env("PAGES_ENV", "dotcom") do
expect(described_class.test?).to be false
expect(described_class.dotcom?).to be true
expect(described_class.enterprise?).to be false
expect(described_class.development?).to be false
end
with_env("PAGES_ENV", "enterprise") do
expect(described_class.test?).to be false
expect(described_class.dotcom?).to be false
expect(described_class.enterprise?).to be true
expect(described_class.development?).to be false
end
with_env("PAGES_ENV", "development") do
expect(described_class.test?).to be false
expect(described_class.dotcom?).to be false
expect(described_class.enterprise?).to be false
expect(described_class.development?).to be true
end
end
end
context ".ssl?" do
before(:each) { ENV["PAGES_ENV"] = "dotcom" }
after(:each) { ENV["PAGES_ENV"] = "test" }
it "only returns true when $SSL is set to 'true'" do
with_env "SSL", "true" do
expect(described_class.ssl?).to be true
end
with_env "SSL", "trueish" do
expect(described_class.ssl?).to be false
end
end
it "is true in PAGES_ENV=test" do
with_env(
"PAGES_ENV" => "test",
"SSL" => "false"
) do
expect(described_class.ssl?).to be true
end
end
end
context ".subdomain_isolation?" do
it "returns true when $SUBDOMAIN_ISOLATION is set to 'true'" do
with_env "SUBDOMAIN_ISOLATION", "true" do
expect(described_class.subdomain_isolation?).to be true
end
end
it "returns false for any other value" do
with_env "SUBDOMAIN_ISOLATION", "" do
expect(described_class.subdomain_isolation?).to be false
end
end
end
context "development" do
it "uses the local pages hostname" do
with_env "PAGES_ENV", "development" do
expect(described_class.pages_hostname).to eql("localhost:4000")
end
end
end
context ".page_build?" do
it "returns true when $PAGE_BUILD_ID is set" do
with_env "PAGE_BUILD_ID", "123" do
expect(described_class.page_build?).to be(true)
end
end
it "returns false by default" do
expect(described_class.page_build?).to be(false)
end
end
end
github-metadata-2.15.0/spec/repository_compat_spec.rb 0000664 0000000 0000000 00000005452 14242001551 0022712 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "spec_helper"
RSpec.describe(Jekyll::GitHubMetadata::RepositoryCompat) do
let(:repo) { Jekyll::GitHubMetadata::Repository.new(nwo) }
let(:repo_compat) { repo.repo_compat }
context "hubot.github.com" do
let(:nwo) { "github/hubot.github.com" }
before(:each) { allow(repo).to receive(:cname).and_return("hubot.github.com") }
it "returns the CNAME as its domain" do
expect(repo_compat.domain).to eql("hubot.github.com")
end
it "always returns HTTP for the scheme" do
expect(repo_compat.url_scheme).to eql("https")
end
it "forces HTTPS for the URL" do
expect(repo_compat.pages_url).to eql("https://hubot.github.com")
end
it "returns the source" do
expect(repo_compat.source).to eql("branch" => "gh-pages", "path" => "/")
end
end
context "ben.balter.com" do
let(:nwo) { "benbalter/benbalter.github.com" }
before(:each) { allow(repo).to receive(:cname).and_return("ben.balter.com") }
it "returns the CNAME as its domain" do
expect(repo_compat.domain).to eql("ben.balter.com")
end
it "always returns HTTP for the scheme" do
expect(repo_compat.url_scheme).to eql("http")
end
it "uses Pages.scheme to determine scheme for domain" do
expect(repo_compat.pages_url).to eql("http://ben.balter.com")
end
it "returns the source" do
expect(repo_compat.source).to eql("branch" => "master", "path" => "/")
end
end
context "parkr.github.io" do
let(:nwo) { "parkr/parkr.github.io" }
before(:each) { allow(repo).to receive(:cname).and_return(nil) }
it "returns the CNAME as its domain" do
expect(repo_compat.domain).to eql("parkr.github.io")
end
it "returns Pages.scheme for the scheme" do
expect(repo_compat.url_scheme).to eql("http")
end
it "uses Pages.scheme to determine scheme for domain" do
expect(repo_compat.pages_url).to eql("http://parkr.github.io")
end
it "returns the source" do
expect(repo_compat.source).to eql("branch" => "master", "path" => "/")
end
context "on enterprise" do
it "uses Pages.scheme to determine scheme for pages URL" do
# With SSL=true
with_env(
"PAGES_ENV" => "enterprise",
"SSL" => "true"
) do
expect(Jekyll::GitHubMetadata::Pages.ssl?).to be(true)
expect(Jekyll::GitHubMetadata::Pages.scheme).to eql("https")
expect(repo_compat.url_scheme).to eql("https")
end
# With no SSL
with_env(
"PAGES_ENV" => "enterprise"
) do
expect(Jekyll::GitHubMetadata::Pages.ssl?).to be(false)
expect(Jekyll::GitHubMetadata::Pages.scheme).to eql("http")
expect(repo_compat.url_scheme).to eql("http")
end
end
end
end
end
github-metadata-2.15.0/spec/repository_finder_spec.rb 0000664 0000000 0000000 00000006616 14242001551 0022701 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "spec_helper"
RSpec.describe Jekyll::GitHubMetadata::RepositoryFinder do
let(:overrides) { { "repository" => "jekyll/another-repo" } }
let(:config) { Jekyll::Configuration.from(overrides) }
let(:site) { Jekyll::Site.new config }
subject { described_class.new(site) }
context "with no repository set" do
before(:each) do
site.config.delete("repository")
ENV["PAGES_REPO_NWO"] = nil
end
context "without a git nwo" do
it "raises a NoRepositoryError" do
allow(subject).to receive(:git_remote_url).and_return("")
expect do
subject.send(:nwo)
end.to raise_error(Jekyll::GitHubMetadata::NoRepositoryError)
end
end
it "retrieves the git remote" do
expect(subject.send(:git_remotes)).not_to be_empty
end
it "extracts the origin from remotes returned by git" do
allow(subject).to receive(:git_remotes).and_return([
"origin\thttps://github.com/jekyll/github-metadata.git (fetch)",
"origin\thttps://github.com/jekyll/github-metadata.git (push)",
])
allow(subject).to receive(:git_remote_url).and_call_original
expect(subject.send(:git_remote_url)).to eql("https://github.com/jekyll/github-metadata.git")
end
{
:https => "https://github.com/foo/bar",
:ssh => "git@github.com:foo/bar.git",
}.each do |type, url|
context "with a #{type} git URL" do
before(:each) do
site.config.delete("repository")
ENV["PAGES_REPO_NWO"] = nil
ENV.delete("JEKYLL_ENV")
end
after(:each) { ENV["JEKYLL_ENV"] = "test" }
it "parses the name with owner from the git URL" do
allow(subject).to receive(:git_remote_url).and_return(url)
expect(subject.send(:nwo)).to eql("foo/bar")
end
end
end
end
context "with PAGES_REPO_NWO and site.repository set" do
before(:each) { ENV["PAGES_REPO_NWO"] = "jekyll/some-repo" }
it "uses the value from PAGES_REPO_NWO" do
expect(subject.send(:nwo)).to eql("jekyll/some-repo")
end
end
context "with only site.repository set" do
before(:each) { ENV["PAGES_REPO_NWO"] = nil }
it "uses the value from site.repository" do
expect(subject.send(:nwo)).to eql("jekyll/another-repo")
end
end
context "when determining the nwo via git" do
before(:each) { ENV.delete("JEKYLL_ENV") }
after(:each) { ENV["JEKYLL_ENV"] = "test" }
it "handles periods in repo names" do
allow(subject).to receive(:git_remote_url).and_return "https://github.com/afeld/hackerhours.org.git"
expect(subject.send(:nwo_from_git_origin_remote)).to eql("afeld/hackerhours.org")
end
it "handles private github instance addresses" do
allow(Jekyll::GitHubMetadata::Pages).to receive(:github_hostname).and_return "github.myorg.com"
allow(subject).to receive(:git_remote_url).and_return "https://github.myorg.com/myorg/myrepo.git"
expect(subject.send(:nwo_from_git_origin_remote)).to eql("myorg/myrepo")
end
context "when git doesn't exist" do
before(:each) do
@old_path = ENV["PATH"]
ENV["PATH"] = ""
end
after(:each) { ENV["PATH"] = @old_path }
it "fails with a nice error message" do
allow(subject).to receive(:git_remote_url).and_call_original
expect(subject.send(:git_remote_url)).to be_empty
end
end
end
end
github-metadata-2.15.0/spec/repository_spec.rb 0000664 0000000 0000000 00000013420 14242001551 0021341 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "spec_helper"
RSpec.describe(Jekyll::GitHubMetadata::Repository) do
let(:repo) { described_class.new(nwo) }
before(:each) do
ENV["JEKYLL_GITHUB_TOKEN"] = "allthespecs"
end
context "with the html_url preview API turned on" do
let(:nwo) { "jekyll/jekyll" }
let!(:stub) do
stub_api(
"/repos/#{nwo}/pages",
"jekyll_repo_pages",
"Accept" => "application/vnd.github.mister-fantastic-preview+json"
)
end
before(:each) { ENV["PAGES_PREVIEW_HTML_URL"] = "true" }
after(:each) { ENV.delete("PAGES_PREVIEW_HTML_URL") }
it "uses the html_url" do
expect(repo.html_url).to eql("http://jekyllrb.com")
expect(repo.repo_pages_info["html_url"]).to eql("#{repo.html_url}/")
end
it "sees the preview env" do
expect(Jekyll::GitHubMetadata::Pages.repo_pages_html_url_preview?).to be_truthy
end
it "uses the preview accept header" do
expect(repo.repo_pages_info_opts).to eql(
:accept => "application/vnd.github.mister-fantastic-preview+json"
)
end
it "respects the source branch" do
expect(repo.git_ref).to eql("master")
end
end
context "repository information" do
let(:nwo) { "jekyll/jekyll" }
let!(:stub) do
stub_api(
"/repos/#{nwo}/pages",
"repo",
"Accept" => "application/vnd.github.v3+json"
)
end
it "returns the stargazers_count" do
expect(repo.stargazers_count).to eq(22)
end
it "returns the fork count" do
expect(repo.forks_count).to eq(4)
end
end
context "hubot.github.com" do
let(:nwo) { "github/hubot.github.com" }
let!(:stub) { stub_api("/repos/#{nwo}/pages", "hubot_repo_pages") }
it "forces HTTPS for the URL" do
expect(repo.html_url).to eql("https://hubot.github.com")
end
it "returns the source" do
expect(repo.source).to eql("branch" => "gh-pages", "path" => "docs/")
end
end
context "ben.balter.com" do
let(:nwo) { "benbalter/benbalter.github.com" }
let!(:stub) { stub_api("/repos/#{nwo}/pages", "benbalter_repo_pages") }
it "returns the CNAME as its domain" do
expect(repo.domain).to eql("ben.balter.com")
end
it "always returns HTTP for the scheme" do
expect(repo.url_scheme).to eql("http")
end
it "uses Pages.scheme to determine scheme for domain" do
expect(repo.html_url).to eql("http://ben.balter.com")
end
it "parses the baseurl" do
expect(repo.baseurl).to eql("")
end
it "returns the source" do
expect(repo.source).to eql("branch" => "master", "path" => "/")
end
end
context "parkr.github.io" do
let(:nwo) { "parkr/parkr.github.io" }
let!(:stub) { stub_api("/repos/#{nwo}/pages", "parkr_repo_pages") }
it "returns the CNAME as its domain" do
expect(repo.domain).to eql("parkermoore.de")
end
it "returns Pages.scheme for the scheme" do
expect(repo.url_scheme).to eql("http")
end
it "uses Pages.scheme to determine scheme for domain" do
expect(repo.html_url).to eql("http://parkermoore.de")
end
it "parses the baseurl" do
expect(repo.baseurl).to eql("")
end
it "returns the source" do
expect(repo.source).to eql("branch" => "master", "path" => "/")
end
end
context "jldec.github.io" do
let(:nwo) { "jldec/jldec.github.io" }
let!(:stub) { stub_api("/repos/#{nwo}/pages", "jldec_repo_pages") }
it "returns the CNAME as its domain" do
expect(repo.domain).to eql("jldec.github.io")
end
it "always returns HTTP for the scheme" do
expect(repo.url_scheme).to eql("https")
end
it "uses Pages.scheme to determine scheme for domain" do
expect(repo.html_url).to eql("https://jldec.github.io")
end
it "parses the baseurl" do
expect(repo.baseurl).to eql("")
end
it "returns the source" do
expect(repo.source).to eql("branch" => "master", "path" => "/")
end
context "on enterprise" do
let!(:stub) { stub_api("/repos/#{nwo}/pages", "jldec_enterprise_repo_pages") }
it "uses Pages.scheme when SSL set to determine scheme for Pages URL" do
# With SSL=true
with_env(
"PAGES_ENV" => "enterprise",
"SSL" => "true",
"PAGES_GITHUB_HOSTNAME" => "github.acme.com"
) do
expect(Jekyll::GitHubMetadata::Pages.ssl?).to be(true)
expect(Jekyll::GitHubMetadata::Pages.scheme).to eql("https")
expect(repo.html_url).to eql("https://github.acme.com/pages/#{nwo}")
expect(repo.url_scheme).to eql("https")
expect(repo.baseurl).to eql("/pages/#{nwo}")
end
end
it "uses Pages.scheme when SSL not set to determine scheme for Pages URL" do
with_env(
"PAGES_ENV" => "enterprise",
"PAGES_GITHUB_HOSTNAME" => "github.acme.com"
) do
expect(Jekyll::GitHubMetadata::Pages.ssl?).to be(false)
expect(Jekyll::GitHubMetadata::Pages.scheme).to eql("http")
expect(repo.html_url).to eql("http://github.acme.com/pages/#{nwo}")
expect(repo.url_scheme).to eql("http")
end
end
end
context "in development" do
let(:nwo) { "jekyll/jekyll" }
it "github.com repo URL always https" do
with_env(
"GITHUB_HOSTNAME" => "github.com",
"PAGES_ENV" => "development"
) do
expect(repo.repository_url).to eql("https://github.com/#{nwo}")
end
end
it "non-github.com repo URL always http" do
with_env(
"GITHUB_HOSTNAME" => "xyz.example",
"PAGES_ENV" => "development"
) do
expect(repo.repository_url).to eql("http://xyz.example/#{nwo}")
end
end
end
end
end
github-metadata-2.15.0/spec/site_github_munger_spec.rb 0000664 0000000 0000000 00000015764 14242001551 0023022 0 ustar 00root root 0000000 0000000 require "spec_helper"
require "jekyll"
require "jekyll-github-metadata/site_github_munger"
RSpec.describe(Jekyll::GitHubMetadata::SiteGitHubMunger) do
let(:source) { File.expand_path("test-site", __dir__) }
let(:dest) { File.expand_path("../tmp/test-site-build", __dir__) }
let(:github_namespace) { nil }
let(:user_config) { { "github" => github_namespace } }
let(:site) { Jekyll::Site.new(Jekyll::Configuration.from(user_config)) }
subject { described_class.new(site) }
let!(:stubs) { stub_all_api_requests }
let(:unified_payload) { site.site_payload }
context "generating" do
before(:each) do
ENV["JEKYLL_ENV"] = "production"
subject.munge!
subject.inject_metadata!(unified_payload)
end
context "with site.github as nil" do
it "sets site.github to the drop" do
expect(unified_payload.site["github"]).to be_a(Liquid::Drop)
end
end
context "without site.github" do
let(:user_config) { {} }
it "replaces site.github with the drop" do
expect(unified_payload.site["github"]).to be_a(Liquid::Drop)
end
end
context "with site.github as a non-hash" do
let(:github_namespace) { "foo" }
it "doesn't munge" do
expect(unified_payload.site["github"]).to eql("foo")
end
end
context "with site.github as a hash" do
let(:github_namespace) { { "source" => { "branch" => "foo" } } }
it "lets user-specified values override the drop" do
expect(unified_payload.site["github"].invoke_drop("source")["branch"]).to eql("foo")
end
it "still sets other values" do
expect(unified_payload.site["github"].invoke_drop("source")["path"]).to eql("/")
end
end
context "with site.url set" do
let(:user_config) { { "url" => "http://example.com" } }
it "doesn't mangle site.url" do
expect(site.config["url"]).to eql("http://example.com")
end
end
context "with site.baseurl set" do
let(:user_config) { { "baseurl" => "/foo" } }
it "doesn't mangle site.url" do
expect(site.config["baseurl"]).to eql("/foo")
end
end
context "with site.baseurl set to ''" do
let(:user_config) { { "baseurl" => "" } }
it "doesn't mangle site.baseurl" do
expect(site.config["baseurl"]).to eql("")
end
end
context "with site.baseurl set to '/'" do
let(:user_config) { { "baseurl" => "/" } }
it "mangles site.url" do
expect(site.config["baseurl"]).to eql("/github-metadata")
end
end
context "without site.url set" do
it "sets site.url" do
expect(site.config["url"]).to eql("http://jekyll.github.io")
end
end
context "without site.baseurl set" do
it "sets site.baseurl" do
expect(site.config["baseurl"]).to eql("/github-metadata")
end
end
context "title and description" do
context "with title and description set" do
let(:user_config) do
{ "title" => "My title", "description" => "My description" }
end
it "respects the title and tagline" do
expect(site.config["title"]).to eql("My title")
expect(site.config["description"]).to eql("My description")
end
end
it "sets the title and description" do
expect(site.config["title"]).to eql("github-metadata")
expect(site.config["description"]).to eql(":octocat: `site.github`")
end
end
context "with name set, but no title" do
let(:user_config) { { "name" => "My site name" } }
it "respects the site name" do
expect(site.config["name"]).to eql("My site name")
expect(site.config["title"]).to be_nil
end
end
context "with site name and title" do
let(:user_config) { { "name" => "Name", "title" => "Title" } }
it "respects the user's settings" do
expect(site.config["name"]).to eql("Name")
expect(site.config["title"]).to eql("Title")
end
end
end
context "generating repo for user with displayname" do
before(:each) do
ENV["JEKYLL_ENV"] = "production"
ENV["PAGES_REPO_NWO"] = "jekyllbot/jekyllbot.github.io"
stub_api("/repos/jekyllbot/jekyllbot.github.io", "user_site")
stub_api_404("/orgs/jekyllbot")
stub_api("/users/jekyllbot", "user_with_displayname")
subject.munge!
end
it "sets title to user's displayname" do
expect(site.config["title"]).to eql("Jekyll Bot")
end
end
context "generating repo for user without displayname" do
before(:each) do
ENV["JEKYLL_ENV"] = "production"
ENV["PAGES_REPO_NWO"] = "jekyllbot/jekyllbot.github.io"
stub_api("/repos/jekyllbot/jekyllbot.github.io", "user_site")
stub_api_404("/orgs/jekyllbot")
stub_api("/users/jekyllbot", "user_without_displayname")
subject.munge!
end
it "sets title to user's login" do
expect(site.config["title"]).to eql("jekyllbot")
end
end
context "generating repo for org with displayname" do
before(:each) do
ENV["JEKYLL_ENV"] = "production"
ENV["PAGES_REPO_NWO"] = "jekyll/jekyll.github.io"
stub_api("/repos/jekyll/jekyll.github.io", "repo")
stub_api("/orgs/jekyll", "org")
subject.munge!
end
it "sets title to org's displayname" do
expect(site.config["title"]).to eql("Jekyll")
end
end
context "generating repo for org without displayname" do
before(:each) do
ENV["JEKYLL_ENV"] = "production"
ENV["PAGES_REPO_NWO"] = "jekyll/jekyll.github.io"
stub_api("/repos/jekyll/jekyll.github.io", "repo")
stub_api("/orgs/jekyll", "org_without_displayname")
subject.munge!
end
it "sets title to org's login" do
expect(site.config["title"]).to eql("jekyll")
end
end
context "with a client with no credentials" do
before(:each) do
Jekyll::GitHubMetadata.client = Jekyll::GitHubMetadata::Client.new(:access_token => "")
end
it "does not fail upon call to #munge" do
expect do
subject.munge!
end.not_to raise_error
end
it "sets the site.github config" do
subject.inject_metadata!(unified_payload)
expect(unified_payload.site["github"]).to be_instance_of(Jekyll::GitHubMetadata::MetadataDrop)
end
end
context "with a client with bad credentials" do
before(:each) do
Jekyll::GitHubMetadata.client = Jekyll::GitHubMetadata::Client.new(:access_token => "1234abc")
stub_request(:get, url("/repos/jekyll/github-metadata/pages"))
.with(:headers => request_headers.merge(
"Authorization" => "token 1234abc"
))
.to_return(
:status => 401,
:headers => WebMockHelper::RESPONSE_HEADERS,
:body => webmock_data("bad_credentials")
)
end
it "fails loudly upon call to any drop method" do
subject.munge!
subject.inject_metadata!(unified_payload)
expect do
unified_payload.site["github"]["url"]
end.to raise_error(Jekyll::GitHubMetadata::Client::BadCredentialsError)
end
end
end
github-metadata-2.15.0/spec/spec_helper.rb 0000664 0000000 0000000 00000005651 14242001551 0020410 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "jekyll"
require "jekyll-github-metadata"
require "webmock/rspec"
require "pathname"
require_relative "spec_helpers/env_helper"
require_relative "spec_helpers/integration_helper"
require_relative "spec_helpers/web_mock_helper"
require_relative "spec_helpers/stub_helper"
require_relative "spec_helpers/fixture_helper"
SPEC_DIR = Pathname.new(__dir__)
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
# Limits the available syntax to the non-monkey patched syntax that is recommended.
# For more details, see:
# - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
# - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = false
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
# config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
config.include WebMockHelper
config.include StubHelper
config.include IntegrationHelper
config.include EnvHelper
config.include FixtureHelper
WebMock.enable!
WebMock.disable_net_connect!
config.before(:all) do
FileUtils.mkdir_p("tmp")
end
config.before(:each) do
Jekyll::GitHubMetadata.reset!
Jekyll::GitHubMetadata.logger = Logger.new(StringIO.new) unless ENV["DEBUG"]
@original_log_level = Jekyll.logger.level
ENV.delete("JEKYLL_ENV")
ENV["PAGES_ENV"] = "test"
ENV["PAGES_REPO_NWO"] = nil
end
config.after(:each) do
Jekyll.logger.log_level = @original_log_level
end
end
github-metadata-2.15.0/spec/spec_helpers/ 0000775 0000000 0000000 00000000000 14242001551 0020237 5 ustar 00root root 0000000 0000000 github-metadata-2.15.0/spec/spec_helpers/env_helper.rb 0000664 0000000 0000000 00000001151 14242001551 0022711 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module EnvHelper
def with_env(*args)
env_hash = env_args_to_hash(*args)
old_env = {}
env_hash.each do |name, value|
old_env[name] = ENV[name]
ENV[name] = value
end
yield
ensure
old_env.each do |name, value|
ENV[name] = value
end
end
private
def env_args_to_hash(*args)
case args.length
when 2
env_hash = {}
env_hash[args.first] = args.last
return env_hash
when 1
return args.first if args.first.is_a? Hash
end
raise ArgumentError, "Expect 2 strings or a Hash of VAR => VAL"
end
end
github-metadata-2.15.0/spec/spec_helpers/fixture_helper.rb 0000664 0000000 0000000 00000001744 14242001551 0023617 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module FixtureHelper
def in_dest_dir(*files)
dest_dir.join(*files)
end
def dest_dir
@dest_dir ||= Pathname.new(File.expand_path("../../tmp/test-site-build", __dir__))
end
def source_dir
@source_dir ||= Pathname.new(File.expand_path("../test-site", __dir__))
end
def config_defaults
{
"source" => source_dir.to_s,
"destination" => dest_dir.to_s,
"plugins" => ["jekyll-github-metadata"],
"gems" => ["jekyll-github-metadata"],
}
end
def make_page(data = {})
Jekyll::Page.new(site, config_defaults["source"], "", "page.md").tap { |page| page.data = data }
end
def make_site(options = {})
config = Jekyll.configuration config_defaults.merge(options)
Jekyll::Site.new(config)
end
def make_context(registers = {}, environments = {})
context = { :site => make_site, :page => make_page }.merge(registers)
Liquid::Context.new(environments, {}, context)
end
end
github-metadata-2.15.0/spec/spec_helpers/integration_helper.rb 0000664 0000000 0000000 00000004604 14242001551 0024452 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module IntegrationHelper
def expected_values
{
"environment" => "dotcom",
"hostname" => "github.com",
"pages_env" => "dotcom",
"pages_hostname" => "github.io",
"help_url" => "https://help.github.com",
"api_url" => "https://api.github.com",
"versions" => {},
"public_repositories" => Regexp.new('"id"=>17261694, "name"=>"atom-jekyll"'),
"organization_members" => Regexp.new('"login"=>"parkr", "id"=>237985'),
"build_revision" => %r![a-f0-9]{40}!,
"project_title" => "github-metadata",
"project_tagline" => ":octocat: `site.github`",
"owner" => Regexp.new('"html_url"=>"https://github.com/jekyll",\s+"id"=>3083652'),
"owner_name" => "jekyll",
"owner_display_name" => "Jekyll",
"owner_url" => "https://github.com/jekyll",
"owner_gravatar_url" => "https://github.com/jekyll.png",
"repository_url" => "https://github.com/jekyll/github-metadata",
"repository_nwo" => "jekyll/github-metadata",
"repository_name" => "github-metadata",
"zip_url" => "https://github.com/jekyll/github-metadata/zipball/gh-pages",
"tar_url" => "https://github.com/jekyll/github-metadata/tarball/gh-pages",
"clone_url" => "https://github.com/jekyll/github-metadata.git",
"releases_url" => "https://github.com/jekyll/github-metadata/releases",
"issues_url" => "https://github.com/jekyll/github-metadata/issues",
"wiki_url" => nil, # disabled
"language" => "Ruby",
"is_user_page" => false,
"is_project_page" => true,
"show_downloads" => true,
"url" => "http://jekyll.github.io/github-metadata",
"baseurl" => "/github-metadata",
"contributors" => %r!"login"=>"parkr", "id"=>237985!,
"releases" => %r!"tag_name"=>"v1.1.0"!,
"latest_release" => %r!assets_url!,
"private" => false,
"archived" => false,
"disabled" => false,
"license" => %r!"key"=>"mit"!,
"source" => { "branch" => "gh-pages", "path" => "/" },
}
end
end
github-metadata-2.15.0/spec/spec_helpers/stub_helper.rb 0000664 0000000 0000000 00000003253 14242001551 0023103 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module StubHelper
include WebMockHelper
# Returns all stubs created.
def stub_all_api_requests
reset_env_for_stubs
stubs = {
"/users/jekyll/repos?per_page=100&type=public" => "owner_repos",
"/repos/jekyll/github-metadata" => "repo",
"/orgs/jekyll" => "org",
"/orgs/jekyll/public_members?per_page=100" => "org_members",
"/repos/jekyll/github-metadata/pages" => "repo_pages",
"/repos/jekyll/github-metadata/releases?per_page=100" => "repo_releases",
"/repos/jekyll/github-metadata/contributors?per_page=100" => "repo_contributors",
"/repos/jekyll/jekyll.github.io" => "not_found",
"/repos/jekyll/jekyll.github.com" => "repo",
"/repos/jekyll/jekyll.github.com/pages" => "repo_pages",
"/repos/jekyll/jekyll.github.io/pages" => "repo_pages",
"/repos/jekyll/github-metadata/releases/latest" => "latest_release",
}.map { |path, file| stub_api(path, file) }
owner_repos = JSON.parse(webmock_data("owner_repos"))
owner_repos.each do |r|
stubs << stub_api("/repos/#{r["full_name"]}/releases?per_page=100", "repo_releases")
stubs << stub_api("/repos/#{r["full_name"]}/contributors?per_page=100", "repo_contributors")
end
stubs
end
def reset_env_for_stubs
# Reset some stuffs
ENV["NO_NETRC"] = "true"
ENV["JEKYLL_GITHUB_TOKEN"] = "1234abc"
ENV["PAGES_REPO_NWO"] = "jekyll/github-metadata"
ENV["PAGES_ENV"] = "dotcom"
end
end
github-metadata-2.15.0/spec/spec_helpers/web_mock_helper.rb 0000664 0000000 0000000 00000003304 14242001551 0023711 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module WebMockHelper
REQUEST_HEADERS = {
"Accept" => %r!application/vnd\.github\.(v3|drax-preview|mercy-preview)\+json!,
"Accept-Encoding" => "gzip;q=1.0,deflate;q=0.6,identity;q=0.3",
"Content-Type" => "application/json",
"User-Agent" => "Octokit Ruby Gem #{Octokit::VERSION}",
}.freeze
RESPONSE_HEADERS = {
"Transfer-Encoding" => "chunked",
"Content-Type" => "application/json; charset=utf-8",
"Vary" => "Accept-Encoding",
"Content-Encoding" => "gzip",
"X-GitHub-Media-Type" => "github.v3; format=json",
}.freeze
def stub_api(path, filename, req_headers = {})
WebMock.disable_net_connect!
stub_request(:get, url(path))
.with(:headers => request_headers.merge(req_headers))
.to_return(
:status => 200,
:headers => RESPONSE_HEADERS,
:body => webmock_data(filename)
)
end
def stub_api_404(path, req_headers = {})
WebMock.disable_net_connect!
stub_request(:get, url(path))
.with(:headers => request_headers.merge(req_headers))
.to_return(
:status => 404,
:headers => RESPONSE_HEADERS
)
end
def expect_api_call(path)
expect(WebMock).to have_requested(:get, url(path))
.with(:headers => request_headers).once
end
def request_headers
REQUEST_HEADERS.merge(
"Authorization" => "token #{ENV.fetch("JEKYLL_GITHUB_TOKEN", "1234abc")}"
)
end
private
def url(path)
"#{Jekyll::GitHubMetadata::Pages.api_url}#{path}"
end
def webmock_data(filename)
@webmock_data ||= {}
@webmock_data[filename] ||= SPEC_DIR.join("webmock/api_get_#{filename}.json").read
end
end
github-metadata-2.15.0/spec/test-site/ 0000775 0000000 0000000 00000000000 14242001551 0017504 5 ustar 00root root 0000000 0000000 github-metadata-2.15.0/spec/test-site/_config.yml 0000664 0000000 0000000 00000000326 14242001551 0021634 0 ustar 00root root 0000000 0000000 repository: jekyll/github-metadata
github:
in_your_config:
setting_your: keyz
plugins:
- jekyll-github-metadata
# remove this once we drop support for Jekyll v3.4 and below
gems:
- jekyll-github-metadata
github-metadata-2.15.0/spec/test-site/index.html 0000664 0000000 0000000 00000000615 14242001551 0021503 0 ustar 00root root 0000000 0000000 ---
---
Page Title
github-metadata-2.15.0/spec/test-site/rendered.txt 0000664 0000000 0000000 00000000044 14242001551 0022033 0 ustar 00root root 0000000 0000000 ---
---
{{ site.github | jsonify }}
github-metadata-2.15.0/spec/test-site/renderjson.js 0000664 0000000 0000000 00000017275 14242001551 0022227 0 ustar 00root root 0000000 0000000 // Copyright © 2013-2014 David Caldwell
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
// Usage
// -----
// The module exports one entry point, the `renderjson()` function. It takes in
// the JSON you want to render as a single argument and returns an HTML
// element.
//
// Options
// -------
// renderjson.set_icons("+", "-")
// This Allows you to override the disclosure icons.
//
// renderjson.set_show_to_level(level)
// Pass the number of levels to expand when rendering. The default is 0, which
// starts with everything collapsed. As a special case, if level is the string
// "all" then it will start with everything expanded.
//
// Theming
// -------
// The HTML output uses a number of classes so that you can theme it the way
// you'd like:
// .disclosure ("⊕", "⊖")
// .syntax (",", ":", "{", "}", "[", "]")
// .string (includes quotes)
// .number
// .boolean
// .key (object key)
// .keyword ("null", "undefined")
// .object.syntax ("{", "}")
// .array.syntax ("[", "]")
exports = {};
exports.renderjson = renderjson = (function() {
var themetext = function(/* [class, text]+ */) {
var spans = [];
while (arguments.length)
spans.push(append(span(Array.prototype.shift.call(arguments)),
text(Array.prototype.shift.call(arguments))));
return spans;
};
var append = function(/* el, ... */) {
var el = Array.prototype.shift.call(arguments);
for (var a=0; a 0)
show();
return el;
};
if (json.constructor == Array) {
if (json.length == 0) return themetext(null, my_indent, "array syntax", "[]");
return disclosure("[", "]", "array", function () {
var as = append(span("array"), themetext("array syntax", "[", null, "\n"));
for (var i=0; i