forked from nazarlitvin/gulp-utm2html
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
96 lines (79 loc) · 2.94 KB
/
index.js
File metadata and controls
96 lines (79 loc) · 2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'use strict';
var fs = require('fs'),
through = require('through2'),
gutil = require('gulp-util'),
cheerio = require('cheerio'),
url = require('url'),
PluginError = gutil.PluginError;
function utm2html(opts) {
return through.obj(function(file, enc, callback){
// Pass file through if:
// - file has no contents
// - file is a directory
if (file.isNull() || file.isDirectory()) {
return callback(null, file);
}
// No support for streams
if (file.isStream()) {
this.emit('error', new PluginError({
plugin: 'gulp-utm-builder',
message: 'Streams are not supported.'
}));
return callback();
}
// check for necessary parameters
// throw error if source/medium/campaign does not exist
if (!opts.source) {
this.emit('error', new PluginError({
plugin: 'gulp-utm-builder',
message: 'source can not be empty.'
}));
}
if (!opts.medium) {
this.emit('error', new PluginError({
plugin: 'gulp-utm-builder',
message: 'medium can not be empty.'
}));
}
if (!opts.campaign) {
this.emit('error', new PluginError({
plugin: 'gulp-utm-builder',
message: 'campaign can not be empty.'
}));
}
if (file.isBuffer()) {
var $ = cheerio.load(file.contents); // load in the HTML into cheerio
var links = $('a');
var preventChangesWords = ['nope', 'ignore', 'false'];
for (var i = 0, len = links.length; i < len; i++) {
var link = $(links[i]);
if (preventChangesWords.indexOf(link.attr('data-utm')) !== -1) {
link.removeAttr('data-utm')
continue;
}
var parsedLink = url.parse(link.attr('href'), true);
// ignore URL with mailto protocol
if (parsedLink.protocol === 'mailto:') {
continue;
}
parsedLink.query.utm_source = opts.source;
parsedLink.query.utm_medium = opts.medium;
parsedLink.query.utm_campaign = opts.campaign;
if (opts.term) {
parsedLink.query.utm_term = opts.term;
}
if (opts.content) {
parsedLink.query.utm_content = opts.content;
}
delete parsedLink.search;
link.attr('href', url.format(parsedLink))
}
var data = $.html();
var buffer = new Buffer(data.length);
buffer.write(data);
file.contents = buffer;
return callback(null, file);
}
});
}
module.exports = utm2html;