<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>gulp Archives - Hiago Silva Souza</title>
	<atom:link href="https://www.hiago.me/tag/gulp/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.hiago.me/tag/gulp/</link>
	<description></description>
	<lastBuildDate>Wed, 28 Nov 2018 01:50:12 +0000</lastBuildDate>
	<language>pt-BR</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.5.5</generator>

<image>
	<url>https://www.hiago.me/wp-content/uploads/2019/01/cropped-icon-hiagus-2-32x32.png</url>
	<title>gulp Archives - Hiago Silva Souza</title>
	<link>https://www.hiago.me/tag/gulp/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">147457425</site>	<item>
		<title>Gulp + Ionic: Automatizando Release no Android</title>
		<link>https://www.hiago.me/2018/08/18/gulp-ionic-automatizando-release-no-android/</link>
					<comments>https://www.hiago.me/2018/08/18/gulp-ionic-automatizando-release-no-android/#comments</comments>
		
		<dc:creator><![CDATA[Hiago Souza]]></dc:creator>
		<pubDate>Sat, 18 Aug 2018 21:48:54 +0000</pubDate>
				<category><![CDATA[Ionic]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[NodeJS]]></category>
		<category><![CDATA[automatizando]]></category>
		<category><![CDATA[build]]></category>
		<category><![CDATA[gulp]]></category>
		<category><![CDATA[ionic]]></category>
		<guid isPermaLink="false">https://www.hiago.me/?p=368</guid>

					<description><![CDATA[<p>Todos que já finalizaram um projeto em ionic, tiveram que passar pelo &#8220;Publishing your app&#8221; e quando você tem que lançar suas atualizações constantemente fica chato ter que ficar repetindo esses procedimentos, por isso resolvi fazer esse post para mostrar como vocês podem automatizar não só esse, como qualquer outro processo usando o Gulp + &#8230;</p>
<p>The post <a href="https://www.hiago.me/2018/08/18/gulp-ionic-automatizando-release-no-android/">Gulp + Ionic: Automatizando Release no Android</a> appeared first on <a href="https://www.hiago.me">Hiago Silva Souza</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Todos que já finalizaram um projeto em ionic, tiveram que passar pelo &#8220;<a href="https://ionicframework.com/docs/v1/guide/publishing.html">Publishing your app</a>&#8221; e quando você tem que lançar suas atualizações constantemente fica chato ter que ficar repetindo esses procedimentos, por isso resolvi fazer esse post para mostrar como vocês podem automatizar não só esse, como qualquer outro processo usando o Gulp + Ionic.</p>
<h1>Gulp</h1>
<p>O Gulp é um kit de ferramentas para automatizar tarefas massantes/demoradas no fluxo de trabalho do desenvolvimento, com ele é possível automatizar essas tarefas de maneira simples e confiável.</p>
<h1>Preparando o ambiente</h1>
<p><span style="display: inline !important; float: none; background-color: transparent; color: #333333; cursor: text; font-family: 'Source Sans Pro',Arial,sans-serif; font-size: 16px; font-style: normal; font-variant: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-decoration: none; text-indent: 0px; text-transform: none; -webkit-text-stroke-width: 0px; white-space: normal; word-spacing: 0px;">[wp_ad_camp_3]</span></p>
<p>Primeiro você deve instalar em seu projeto ionic as dev-dependencies abaixo:</p>
<pre class="brush: plain; title: ; notranslate">

npm install --save-dev gulp run-sequence shelljs

</pre>
<h1>Criando sua KeyStore</h1>
<p>A keystore é única, ela é quem garante que você e somente você consiga fornecer uma atualização segura para seus usuários.</p>
<p>Como a KeyStore é gerada uma única vez, não vejo motivos para automatizar no processo do Gulp. A Keystore é o segundo passo do &#8220;<a href="https://ionicframework.com/docs/v1/guide/publishing.html">Publishing your app</a>&#8220;. Entre no diretório de sua aplicação e na mesma pasta de seu package.json, execute o comando abaixo informando os seus dados e criando uma senha que você vai usar depois na nossa tarefa do Gulp. Mantenha a mesma senha, tanto para o keystore quanto para o alias.</p>
<pre class="brush: plain; title: ; notranslate">
keytool -genkey -v -keystore chave-distribuicao.keystore -alias ID_DO_SEU_CONFIG_XML -keyalg RSA -keysize 2048 -validity 10000
</pre>
<p>Note que no comando acima tem a informação <em><strong>ID_DO_SEU_CONFIG_XML</strong></em> essa informação deve ser substituída pelo id que você colocou no seu config.xml, o padrão para os id do config.xml é <em><strong>br.com.seuappsite.app</strong></em>.</p>
<h1>Package.Json</h1>
<p><span style="display: inline !important; float: none; background-color: transparent; color: #333333; cursor: text; font-family: 'Source Sans Pro',Arial,sans-serif; font-size: 16px; font-style: normal; font-variant: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-decoration: none; text-indent: 0px; text-transform: none; -webkit-text-stroke-width: 0px; white-space: normal; word-spacing: 0px;">[wp_ad_camp_2]</span></p>
<p>Agora vamos editar nosso package.json, e vamos adicionar um novo valor dentro dos scripts. Crie uma nova chave com o nome &#8220;<strong>build:release</strong>&#8221; com o valor &#8220;<strong>gulp release</strong>&#8220;.</p>
<h1>Gulpfile</h1>
<p>Agora precisamos criar um arquivo chamado gulpfile.js no mesmo diretório do seu package.json ele é quem vai fazer todo o trabalho de executar o &#8220;ionic cordova build &#8211;prod &#8211;release&#8221;, e os outros passos para assinar e alinhar o seu aplicativo. E o resultado final vai ser o seu APK pronto para distribuição na pasta dist.</p>
<p>Conteúdo do Gulpfile.js:</p>
<pre class="brush: plain; title: ; notranslate">
const gulp = require('gulp'),
      fs = require('fs'),
      path = require('path'),
      runSequence = require('run-sequence'),
      shelljs = require('shelljs'),
      config = {
           pwd: &quot;SENHA_ESCOLHIDA_NA_CHAVE&quot;,
           alias: &quot;ID_DO_SEU_CONFIG_XML&quot;,
           keystore: &quot;chave-distribuicao.keystore&quot;
      };

gulp.task('release', function () {

    const apks = fs.readdirSync('./dist');
    for(apk of apks) {
        // verificando apks não assinados
        if(apk.indexOf('.apk') &gt; -1) {
            fs.unlinkSync(`./dist/${apk}`);
        }
    }

    if(config.pwd === 'keystore_password' || config.pwd === '') {
        console.error('Edite o gulpfile.js e informe a senha de sua keystore.');
        return shelljs.exit(1);
    }

    runSequence('compilar-release', 'assinar-apk', 'alinhar-apk', function () {

    });
});

/**
 * Compilo com a flag --prod e --release no ionic
 */
gulp.task('compilar-release', function () {
    const out = shelljs.exec('ionic cordova build android --release --prod --no-interactive', {silent:true}).stdout;
    const buildReturn = out.split('Built the following apk(s):');

    // verifico se o build deu certo
    if(buildReturn.length &gt; 1) {
        const apks = buildReturn&#x5B;1].replace(/\r/, '').replace(/\t/, '').split('\n'),
              realApks = &#x5B;];
        for(apk of apks) {
            // recupero os apks releases gerados
            if(apk.indexOf('release-unsigned.apk') &gt; -1) {
                realApks.push(apk);
            }
        }

        // verificando se a pasta dist existe.
        if(!fs.existsSync('./dist')) {
            fs.mkdirSync('./dist');
        }

        // movendo apks para a dist
        for(apk of realApks) {
            let splitter = &quot;/&quot;;
            if(apk.indexOf(&quot;\\&quot;) &gt; -1) {
                splitter = &quot;\\&quot;;
            }

            let fileName = apk.split(splitter);
            fileName = fileName&#x5B;fileName.length - 1];

            fs.copyFileSync(apk, './dist/' + fileName);
            fs.unlinkSync(apk);
        }
    } else {
        // erro no build
        shelljs.exit(1);
    }
});

/**
 * Assina o APK com release
 */
gulp.task('assinar-apk', function () {
    const apks = fs.readdirSync('./dist');
    for(apk of apks) {
        // verificando apks não assinados
        if(apk.indexOf('release-unsigned.apk') &gt; -1) {
            let signCommand = `jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore ${config.keystore} -storepass ${config.pwd} -keypass ${config.pwd} ./dist/${apk} ${config.alias}`;
            const signCommandResult = shelljs.exec(signCommand, {silent:true}).stdout;
            console.log(signCommandResult);
        }
    }
});

/**
 * Assina o APK com release
 */
gulp.task('alinhar-apk', function () {
    let bdtools = process.env.ANDROID_HOME + path.sep + 'build-tools' + path.sep + fs.readdirSync(process.env.ANDROID_HOME + path.sep + 'build-tools')&#x5B;0] + path.sep;
    console.log(bdtools);
    const apks = fs.readdirSync('./dist');
    for(apk of apks) {
        // verificando apks não assinados
        if(apk.indexOf('release-unsigned.apk') &gt; -1) {
            let alignCommand = `&quot;${bdtools}zipalign&quot; -v 4 ./dist/${apk} ./dist/${apk.replace('-release-unsigned.apk', '')}.apk`;
            const alignCommandResult = shelljs.exec(alignCommand, {silent:true}).stdout;
            fs.unlinkSync(`./dist/${apk}`);
            console.log(alignCommandResult);
        }
    }
});
</pre>
<h1>Testando</h1>
<p><span style="display: inline !important; float: none; background-color: transparent; color: #333333; cursor: text; font-family: 'Source Sans Pro',Arial,sans-serif; font-size: 16px; font-style: normal; font-variant: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-decoration: none; text-indent: 0px; text-transform: none; -webkit-text-stroke-width: 0px; white-space: normal; word-spacing: 0px;">[wp_ad_camp_1]</span></p>
<p>Agora para gerar e assinar seus apks basta você executar o comando abaixo:</p>
<pre class="brush: plain; title: ; notranslate">

npm run build:release

</pre>
<p>Obrigado pessoal, espero que o conteúdo seja útil para vocês.</p>
<p><strong>[27/11/2018] Edição:</strong> Adicionei na linha 32 do Gulpfile.js o parâmetro <strong>&#8211;no-interactive</strong> para corrigir o problema de travar a compilação pelo fato da CLI do ionic perguntar se você deseja fazer a atualização.</p>
<p>The post <a href="https://www.hiago.me/2018/08/18/gulp-ionic-automatizando-release-no-android/">Gulp + Ionic: Automatizando Release no Android</a> appeared first on <a href="https://www.hiago.me">Hiago Silva Souza</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.hiago.me/2018/08/18/gulp-ionic-automatizando-release-no-android/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">368</post-id>	</item>
	</channel>
</rss>
