Github: How to embed a gist into README.md? - github

Is it possible to embed gists into README.md file that resides in a GitHub repository?
Something like:
<code id="gist-3167145"></code>

No, sorry, that is not possible. You will have to either have a link to it in your README.md or copy its contents.
Github Flavored Markdown will show you what you can put in your README.md file.

Update : My answer works with github pages, built via jekyll. I use the script tags in markdown which is then processed by jekyll.
Since markdown supports html, one can simply use the <script> tag to embed gist.
Simply copy the embed url of the gist provided by github
..and paste it in you markdown file.
Example : Copy the below and paste in your markdown file.
<script src="https://gist.github.com/nisrulz/11c0d63428b108f10c83.js"></script>
..and this is what you will get

This is do-able in 2017 when using GitHub Pages and a Jekyll theme:
See https://gist.github.com/benbalter/5555251 from #benbalter
Simple as: {% gist 123456789 %}

You can do it if you are using a markdown preprocessor such as Gitdown:
/**
* Resolve Gist (https://gist.github.com/)
*
* #param {Object} config
* #param {String} config.id Gist ID.
* #param {String} config.fileName Gist file name. Default to gistfile1.txt.
*/
gitdown.registerHelper('gist', {
compile: function (config) {
config = config || {};
config.fileName = config.fileName || 'gistfile1.txt';
if (!config.id) {
throw new Error('Gist ID must be provided.');
}
return new Promise(function (resolve) {
var https = require('https');
https.get({
host: 'api.github.com',
path: '/gists/' + config.id,
headers: {
// User agent is required to communicate with Github API.
'user-agent': 'Gitdown – gist'
}
}, function(res) {
var body = '';
res.setEncoding('utf8');
res.on('data', function (d) {
body += d;
});
res.on('end', function () {
var gist = JSON.parse(body);
if (!gist.files) {
throw new Error('Gist ("' + config.id + '") not found.');
}
if (!gist.files[config.fileName]) {
throw new Error('File ("' + config.fileName + '") is not part of the gist ("' + config.id + '").');
}
resolve(gist.files['gistfile1.txt'].content);
});
});
});
}
});
Then in your markdown your would reference the Gist using a JSON hook, e.g.
{"gitdown": "gist", "id": "d3e4212c799252bac5fa"}
This feature should become part of the Gitdown in a near future (there is an open issue, https://github.com/gajus/gitdown/issues/7).

Some people will end up here due to the fact that they want to use auto-generated gists to make their profile on github more interesting with activity box, productive box, etc. (list of this stuff).
However, you should note that these auto-generated gists should not be added to your profile dedicated README file but should be pinned using the "Customize your pins" option on your profile page.

Related

Create session redirect link in content asset

Our company has multiple brands and each brand has its own host name, but they are all part of the same site. We can let customers share baskets and other session information when they switch between brands via a redirect link using URLUtils.sessionRedirect.
But URLUtils is not available in content assets. Is it possible to form a session redirect link in content asset keeping all the session information?
Thanks in advance.
You can include dynamic content in Content Assets with the $include('Controller-Name', 'name1', 'value1', 'name2', 'value2', ...)$ syntax. See the MarkupText Class Documentation for more info on that syntax. The 'name1' and 'value1' parameters are mapped as query string attributes eg: Controller-Name?name1=value1&name2=value2
Create a controller that outputs the session redirect link you need, and call it via that syntax like: $include(Util-RenderSessionLink, 'siteID', 'foo')$
The controller would need to use a response Content-Type header of text/plain or something like that so that nothing is injected into the response. (eg: Storefront toolkit or tracking tags) For example:
response.setContentType('text/plain');
Alternatively, you could process the content asset for some sorts of keys that you perform find & replace operations on. For example, the following code does a find & replace on a Content Asset's body content for the key: '%%SessionLink%%'.
var ContentMgr = require('dw/content/ContentMgr');
var URLUtils = require('dw/web/URLUtils');
if (!empty(content) {
var content = ContentMgr.getContent('my-content-id');
var contentOut = "";
var viewData = {};
contentOut = content.custom.body.getMarkup()
.replace('%%SessionLink%%', URLUtils.sessionRedirect(...));
viewData.content = contentOut;
// then output your `pdict.content` key within a template with the appropriate encoding
}
If anybody else is running into this, we added a bit of client-side javascript that pickups up all outbound links and if it's one of our domains it sends them through a session redirect. This way we don't need content managers to fix very link between domains:
var domains = ["domaina.com", "domainb.com", "domainc.com"]
var sessionRedirectBase = '/s/Our-Site/dw/shared_session_redirect';
$(document).on("click.crossSite", "a", (e) => {
const href = $(e.currentTarget).attr("href");
if (href) { //does the link have a href
if (href.match(/^(http(s)?:)?\/\//)) { //is href an absolute url
const url = new URL(href);
if (url.hostname != window.location.hostname && domains.indexOf(url.hostname) > -1) { //is hostname not the current one and part of the domains array
e.preventDefault();
const sessionRedirect = `${sessionRedirectBase}?url=${encodeURIComponent(href)}`
window.location = sessionRedirect;
}
}
}
});

How to enable folders in Chrome devtools > Sources > Page > top > (no domain) (files with //# sourceURL=...)

Is there a way to show folders for path's in Chrome devtool > Page panel
for tree nodes in top > (no domain)
these are node comming from js eval with a //# sourceURL=...
as my code contains a lot of these I want them to show as
- top
- MyDomain
- MyFile
- (no domain)
- FolderA
- Eval1
- Eval2
- FolderB
- Eval3
- Eval4
Instead of
- top
- MyDomain
- MyFile
- (no domain)
- FolderA/Eval1
- FolderA/Eval2
- FolderB/Eval3
- FolderB/Eval4
Include the domain (origin) in the sourceUrl.
I had to find this out by trial and error, it is not well-documented anywhere.
JS syntax:
//# sourceURL=http://mySite:8000/FolderA/File1.js
Css syntax:
/*# sourceURL=http://mySite:8000/FolderA/File1.css */
Build it in the browser:
Create a sourceUrl from a relative url:
function jsSrcUrl(path) {
return "//# sourceURL=" + window.origin + path + " \n";
}
var src = "/js/myScript.js"; // use this url in your GET request via fetch()
var sourceUrl = jsSrcUrl(src); // append this and eval it later
Create a sourceUrl during a fetch request:
var src = "/ui/vue.js";
var fullUrl;
fetch(src)
.then(function(response) {
fullUrl = response.url;
return response.text()
})
.then(function(text) {
console.log(text)
})
var sourceUrl = "//# sourceURL=" + fullUrl + " \n"
Add a sourceUrl to your script (which is a string before eval):
var scriptWithSrcUrl = script.concat(sourceUrl);
Eval your script to load your script (string) into the browser and sources panel
eval(scriptWithSrcUrl)
Put it all together: Create a sourceUrl during a fetch request AND append it to the script AND eval it:
async function loadScript(url) {
var fullUrl;
async function getScript() {
return fetch(url)
.then(function(response) {
fullUrl = response.url;
return response.text();
})
.then(function(text) {
return text;
});
}
var script = await getScript();
var sourceUrl = "\n//# sourceURL=" + fullUrl + " \n";
var scriptWithSrcUrl = script.concat(sourceUrl);
(1, eval)(scriptWithSrcUrl);
}
loadScript("/path/to/script.js");
Look in your devtools sources panel and find your file in the proper folder and domain!
Dear Google, Mozilla, Microsoft, & Apple:
The fetch api is nice, but fetching js/css/html via a get request, injecting a sourceUrl, and eval'ing it is not just lame, it's ultra lame. Loading everything in a script tag in the document head doesn't play nice with lazy-loading components, code-splitting, tree shaking, and SSR in general. Wouldn't it be nice if there was an api to load js, css, html templates, components, and js modules into global scope - all from js (not from html) natively using browser api's?
A way that doesn't involve:
ES6 module syntax and scope (for loading into local scope)
fetch() + sourceUrl + eval()
document.createElement('script') + set src + onload() (pollutes the doc head)
Some library/dependency (Jquery $.getScript(), Fetch inject, Requirejs, etc.)
I am sure that this api already exists within the browser, script tags probably already consume that js api...can't we just have nice things?
loadScript("path/to/js.js"); // for loading js into global scope
Such a simple use case, yet no API.

Sailsjs - Cloud SDK - Blueprint API auto generated routes?

I wonder if it is possible to have the Blueprint API support in Cloud SDK.
But apparently, the generated cloud.setup.js file does not contain blueprint APIs. Just normal routes beginning with /api
It is written in the Cloud.js file :
* ### Basic Usage
*
* var user = await Cloud.findOneUser(3);
*
* var user = await Cloud.findOneUser.with({ id: 3 });
It lets think that it's possible to have auto generated routes to the blueprint APIs like actionModel -> findOneUser, createServer, addToGame, and so on...
Do you know if that is possible ? I don't find a documentation about this.
Thanks
I took original code in rebuild-cloud-sdk.js and created a rcsdk.js with the code below before the actual for (let address in sails.config.routes):
_.each(_.keys(sails.models), model => {
let action = sails.config.blueprints.prefix + sails.config.blueprints.restPrefix + '/' + model;
_.each([['GET', 'find'], ['POST', 'create']], pair => {
endpointsByMethodName[`${pair[1]}${model}`] = {
verb: pair[0],
url: action,
}
});
_.each([['GET', 'findOne'], ['PUT', 'update'], ['DELETE', 'delete']], pair => {
endpointsByMethodName[`${pair[1]}${model}`] = {
verb: pair[0],
url: action,
args: ['id'],
}
});
});
I also asked this question the other day. It is not possible. We need to be explicit here. Blueprint routes is only for quick integration testing with postman. I don't recommend this though. You should not be using postman or auto routes. You should write tests in files so they are permanent.

nodejs router docblock comment

I am writing below docblock for one of my app routers. Is it right?
also, tell me the meaning of each line as I don't know exactly.
/**
* Router serving Activity log page.
* #name get/activity_log
* #function
* #memberof module:routers/activity_log
* #inner
* #param {string} path - Activity log path
* #param {callback} middlewear - Express middlewear.
*/
router.get('/', function(req, res) {
var async = require('async');
var telemetry = require(modulePath)(req.dbquery,req.nosql);
telemetry.getTelemetryLog(function(err, data) {
console.log(data);
if(err) {
res.send(error);
} else {
res.render('_admin/activity_log', {
title: 'App Admin',
username: req.session.user.name,
notifications: req.session.notifications,
tasks: req.session.tasks,
telemetry: data
});
}
});
});
OK, as for the comments in upper part of code, they are docblock documentation parameters. You can use a documentation generator tool like JSDoc in case of Javascript, if it is meaningful to you.
You can find meaning of the tags like #name, #function, and others in links below:
http://usejsdoc.org/tags-name.html
http://usejsdoc.org/tags-function.html
http://usejsdoc.org/tags-inner.html
http://usejsdoc.org/tags-param.html
and so on.
After all code, or at least part is documented like that, you can generate a HTML content to browse your documentation clearly with hyperlinks.
To do this you need to install the JSDoc NPM package:
npm install -g jsdoc
Then you run the command line inside your main code directory indicating all you js files:
jsdoc *.js folder1/*.js folder2/*.js
This command will generate the HTML files for you code documentation in the out/ directory.
Open out/index.html to view the documentation.

Github-api get commits

Can someone explain me or give some tutorial to get all the commit details for a particular in github. I saw this and I didn't understand how to use that.
You can check my article about this:
http://ondrek.me/articles/how-to-parse-github-API-in-nodejs/
This is NodeJs way
(for client js change require("https") to client ajax JSON - code is very simular)
Quick sample link for repo MDOWN of user ONDREK
https://api.github.com/repos/ondrek/mdown/git/refs/heads/
How to make a request to Github API
var options = {
user : 'ondrek',
repo : 'favicon-blog',
branch : 'master'
};
function getHttpRequestJson(customPath, callback){
require('https').request({
hostname: 'api.github.com',
path: customPath,
method: 'GET'
}, function(res){
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
callback(JSON.parse(data));
});
}).end();
}
How to get user details json from Github API
(inject previous code)
var url = '/repos/'+options.user+'/'+options.repo+'/git/refs/heads/'+options.branch;
getHttpRequestJson(url, function(userJson){
var lastCommitUrl = userJson.object.url;
getLastCommit(lastCommitUrl);
});
How to get last commit json from Github API
(inject previous code)
function getLastCommit(url){
getHttpRequestJson(url+auth, function(lastCommitJson){
var treeUrl = lastCommitJson.tree.url;
getTree(treeUrl);
});
}
How to get tree of last commit from Github API
(inject previous code)
function getTree(url){
getHttpRequestJson(url+auth, function(treeJson){
var treeArr = treeJson.tree;
getOnlyPages(treeArr);
});
}
How to get specific folder of last commit from Github API
(inject previous code)
function getOnlyPages(treeArr){
treeArr.forEach(function(ele){
if (ele.path==='blog') { getArticles(ele.url); }
});
}
function getArticles(url){
getHttpRequestJson(url+auth, function(treeJson){
var treeArr = treeJson;
parseMarkdownArticles(treeArr.tree);
});
}