Coder Social home page Coder Social logo

enefce / androidlibraryforgithubpackagesdemo Goto Github PK

View Code? Open in Web Editor NEW
59.0 3.0 36.0 173 KB

Sample project showcasing the steps to publish and consume Android Libraries on the GitHub Packages Registry

Home Page: https://proandroiddev.com/publishing-android-libraries-to-the-github-package-registry-part-1-7997be54ea5a

License: Apache License 2.0

Kotlin 100.00%
github-packages github-package-registry android-library kotlin gradle android-studio android-application android-development android github-actions

androidlibraryforgithubpackagesdemo's Introduction

Build Status FOSSA Status Library Version

License

Sample Android Library Publishing to GitHub Package Registry

This Android project showcases the steps to publish and consume Android Libraries on the GitHub Package Registry. It is made up of 2 modules

  1. sampleAndroidLib
  • Android library module with basic functionality
  • Publishes the generated library file onto the GitHub Package Registry
  • The build.gradle file inside this module has the code (plugin, tasks and authentication) related to publishing the library
  1. app
  • Sample Android application module with the build.gradle file that shows the code for consuming an Android library from GitHub Package Registry.

Publish Android library to GitHub Package Registry

Step 1 : Generate a Personal Access Token for GitHub

  • Inside you GitHub account:
    • Settings -> Developer Settings -> Personal Access Tokens -> Generate new token
    • Make sure you select the following scopes (" write:packages", " read:packages") and Generate a token
    • After Generating make sure to copy your new personal access token. You won’t be able to see it again!

Step 2: Store your GitHub - Personal Access Token details

  • Create a github.properties file within your root Android project
  • In case of a public repository make sure you add this file to .gitignore for keep the token private
    • Add properties gpr.usr=GITHUB_USERID and gpr.key=PERSONAL_ACCESS_TOKEN
    • Replace GITHUB_USERID with personal / organisation Github User ID and PERSONAL_ACCESS_TOKEN with the token generated in #Step 1

Alternatively you can also add the GPR_USER and GPR_API_KEY values to your environment variables on you local machine or build server to avoid creating a github properties file

Step 3 : Update build.gradle inside the library module

  • Add the following code to build.gradle inside the library module
apply plugin: 'maven-publish'
def githubProperties = new Properties()
githubProperties.load(new FileInputStream(rootProject.file("github.properties")))  
def getVersionName = { ->
    return "1.0.2"  // Replace with version Name
}
def getArtificatId = { ->
    return "sampleAndroidLib" // Replace with library name ID
}
publishing {
    publications {
        bar(MavenPublication) {
            groupId 'com.enefce.libraries' // Replace with group ID
            artifactId getArtificatId()
            version getVersionName()
            artifact("$buildDir/outputs/aar/${getArtificatId()}-release.aar")
        }
    }

    repositories {
        maven {
            name = "GitHubPackages"
            /** Configure path of your package repository on Github
             *  Replace GITHUB_USERID with your/organisation Github userID and REPOSITORY with the repository name on GitHub
             */
            url = uri("https://maven.pkg.github.com/GITHUB_USERID/REPOSITORY")

            credentials {
                /**Create github.properties in root project folder file with gpr.usr=GITHUB_USER_ID  & gpr.key=PERSONAL_ACCESS_TOKEN**/
                username = githubProperties['gpr.usr'] ?: System.getenv("GPR_USER")
                password = githubProperties['gpr.key'] ?: System.getenv("GPR_API_KEY")
            }
        }
    }
}

Step 4 : Publish the Android Library onto GitHub Package Registry

Make sure to build and run the tasks to generate the library files inside build/outputs/aar/ before proceeding to publish the library.

  • Execute the Publish gradle task which is inside your library module
$ gradle publish
  • Once the task is successful you should be able to see the Package under the Packages tab of the GitHub Account
  • In case of a failure run the task with --stacktrace, --info or --debug to check the logs for detailed information about the causes.

Using a library from the GitHub Package Registry

Currently the GitHub Package Registry requires us to Authenticate to download an Android Library (Public or Private) hosted on the GitHub Package Registry. This might change for future releases

Steps 1 and 2 can be skipped if already followed while publishing a library

Step 1 : Generate a Personal Access Token for GitHub

  • Inside you GitHub account:
    • Settings -> Developer Settings -> Personal Access Tokens -> Generate new token
    • Make sure you select the following scopes ("read:packages") and Generate a token
    • After Generating make sure to copy your new personal access token. You won’t be able to see it again!

Step 2: Store your GitHub - Personal Access Token details

  • Create a github.properties file within your root Android project
  • In case of a public repository make sure you add this file to .gitignore for keep the token private
    • Add properties gpr.usr=GITHUB_USERID and gpr.key=PERSONAL_ACCESS_TOKEN
    • Replace GITHUB_USERID with personal / organisation Github User ID and PERSONAL_ACCESS_TOKEN with the token generated in #Step 1

Alternatively you can also add the GPR_USER and GPR_API_KEY values to your environment variables on you local machine or build server to avoid creating a github properties file

Step 3 : Update build.gradle inside the application module

  • Add the following code to build.gradle inside the application module that will be using the library published on GitHub Packages Repository
def githubProperties = new Properties()
githubProperties.load(new FileInputStream(rootProject.file("github.properties")))  
    repositories {
        maven {
            name = "GitHubPackages"
            /*  Configure path to the library hosted on GitHub Package Registry
             *  Replace UserID with package owner userID and REPOSITORY with the repository name
             *  e.g. "https://maven.pkg.github.com/enefce/AndroidLibraryForGitHubPackagesDemo"
             */
            url = uri("https://maven.pkg.github.com/UserID/REPOSITORY")

            credentials {
                username = githubProperties['gpr.usr'] ?: System.getenv("GPR_USER")
                password = githubProperties['gpr.key'] ?: System.getenv("GPR_API_KEY")
            }
        }
    }
  • inside dependencies of the build.gradle of app module, use the following code
dependencies {
    //consume library, e.q. 'com.enefce.libraries.sampleAndroidLib:sampleandroidlib:1.0.5'
    implementation '<groupId>:<artifactId>:<version>'
	...
}

License

FOSSA Status

androidlibraryforgithubpackagesdemo's People

Contributors

fossabot avatar prasad79 avatar up9cloud avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

androidlibraryforgithubpackagesdemo's Issues

Received status code 403 from server: Forbidden

Hi, thanks for your article, it was very enlightening!

Yet, I bumped into something. This is the repo: https://github.com/cesarferreira/android-unique-device-id

I'm trying to upload the github package, I followed your guide and it looks like i'm doing everything right but i keep getting this error:

~/code/github/android-unique-device-id master
❯ ./gradlew assembleRelease publish
> Task :android-unique-device-id:publishBarPublicationToGitHubPackagesRepository FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':android-unique-device-id:publishBarPublicationToGitHubPackagesRepository'.
> Failed to publish publication 'bar' to repository 'GitHubPackages'
> Could not PUT 'https://maven.pkg.github.com/cesarferreira/android-unique-device-id/cesarferreira/android-unique-device-id/0.0.1/android-unique-device-id-0.0.1.aar'. Received status code 403 from server: Forbidden

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 4s
59 actionable tasks: 3 executed, 56 up-to-date

my build gradle: https://github.com/cesarferreira/android-unique-device-id/blob/master/android-unique-device-id/build.gradle

def getArtifactId = { ->
  return "android-unique-device-id"
}

publishing {
	publications {
		bar(MavenPublication) {
			groupId 'cesarferreira'
			version "0.0.1"
			artifactId getArtifactId()
			artifact("$buildDir/outputs/aar/${getArtifactId()}-release.aar")
		}
}

repositories {
	maven {
		name = "GitHubPackages"
		url = uri("https://maven.pkg.github.com/cesarferreira/android-unique-device-id")
		credentials {
			username = System.getenv("GITHUB_USER")
			password = System.getenv("GITHUB_TOKEN")
		}
	}
}

I even made a token with ALL permissions to see if those basic permissions weren't enough.

I made sure that the environment variables are there.

Does anything stand out to you that I'm missing?
Thanks in advance!

Failed to resolve package

First of all this is a great tutorial thanks for that.
I followed every step and succesfully published my package and i can see it on my repo and package but unfortunatelly when i try to use my package it's failing to resolve package.Also instead of build.gradle i am using settings.gradle file to add repositories.

Failed to resolve: com.trive.libraries.kycsdk:1.0.2

any thoughts ?

Why command failed and unexpected result

Hello, thanks for your step, it is clear.

But I met some problems, one is the command failed, I used "gradle publish", but it failed, error message showed "Received status code 409 from server: Conflict". Actually it upload success to GitHub Packages, I am stranged it seemed to upload twice.

Another problem is why the package contains some files which suffix are "*.sha1" and ".md5"?

Invalid publication 'release': multiple artifacts with the identical extension and classifier ('aar', 'null').

I have been following this Medium doc: Publishing Android libraries to GitHub Packages

This is build.gradle file:

import java.util.Properties

plugins {
    id("com.android.library")
    id("org.jetbrains.kotlin.android")
    id("maven-publish")
}
val getVersionName = "1.0.0"
val getArtifactId = "dynamic-map"
val githubProperties = Properties()
githubProperties.load(
    rootProject.file("github.properties").inputStream()
) // Load GitHub credentials from github.properties file

android {
    ...
}

dependencies {
   ...
}

afterEvaluate {
    val gitUsername = githubProperties.getProperty("gpr.usr")
    val gitPassword = githubProperties.getProperty("gpr.key")

    println("GitHub Username: $gitUsername")
    println("GitHub Token: $gitPassword")

    publishing {
        publications {
            create<MavenPublication>("release") {
                from(components["release"])
                groupId = "com.gaurav.kumar"
                artifactId = getArtifactId
                version = getVersionName
                artifact("$buildDir/outputs/aar/${getArtifactId}-release.aar")
            }
        }
        repositories {
            maven {
                name = "DynamicMapRepo"
                url = uri("https://maven.pkg.github.com/Cypher103360/DynamicMap")

                credentials {
                    username = gitUsername
                    password = gitPassword
                }
            }
        }
    }
}

When I try to publish the library I get this:

gaurav@gaurav-ThinkPad-E15-Gen-4:~/AndroidStudioProjects/DynamicMap$ ./gradlew publish

> Configure project :dynamic-map
GitHub Username: Cypher103360
GitHub Token: *****

> Task :dynamic-map:publishReleasePublicationToDynamicMapRepoRepository FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':dynamic-map:publishReleasePublicationToDynamicMapRepoRepository'.
> Failed to publish publication 'release' to repository 'DynamicMapRepo'
   > Invalid publication 'release': multiple artifacts with the identical extension and classifier ('aar', 'null').

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
> Get more help at https://help.gradle.org.

BUILD FAILED in 1s
25 actionable tasks: 21 executed, 4 up-to-date

@prasad79 @up9cloud @fossabot
Please help me to address this issue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.